repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
stardot/ncc
armthumb/peeptest.c
/* * C compiler file arm/peeptest.c. * Copyright (C) 1992 Advanced Risc Machines Limited. All rights reserved * Peepholer testbed. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <stdarg.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include "globals.h" typedef union VRegInt /* extracted (and pruned) from cgdefs.h */ { int32 i; char *str; void *p; } VRegInt; int32 pp_pragmavec[26]; int32 procflags, procauxflags; /* NONLEAF used */ RealRegSet regmaskvec; /* bit R_LR */ int32 localcg_debugcount = 2; int32 config; int32 pcs_flags; #include "jopcode.h" #define DEFINE_A_JOPTABLE 1 typedef int32 RealRegister; #include "mcdpriv.h" int32 a_loads_r1(J_OPCODE op) { return (op & J_TABLE_BITS) > J_LAST_JOPCODE ? a_attributes(op) & _a_set_r1: loads_r1(op); } int32 a_uses_r1(J_OPCODE op) { return (op & J_TABLE_BITS) > J_LAST_JOPCODE ? a_attributes(op) & (_a_set_r1 | _a_read_r1) : uses_r1(op); } int32 a_reads_r1(J_OPCODE op) { return (op & J_TABLE_BITS) > J_LAST_JOPCODE ? a_attributes(op) & _a_read_r1 : reads_r1(op); } int32 a_uses_r2(J_OPCODE op) { return (op & J_TABLE_BITS) > J_LAST_JOPCODE ? a_attributes(op) & (_a_read_r2 | _a_set_r2) : uses_r2(op); } int32 a_reads_r2(J_OPCODE op) { return (op & J_TABLE_BITS) > J_LAST_JOPCODE ? a_attributes(op) & _a_read_r2 : reads_r2(op); } int32 a_loads_r2(J_OPCODE op) { return (op & J_TABLE_BITS) > J_LAST_JOPCODE ? a_attributes(op) & _a_set_r2 : loads_r2(op); } int32 a_uses_r3(J_OPCODE op) { return (op & J_TABLE_BITS) > J_LAST_JOPCODE ? a_attributes(op) & _a_read_r3 : uses_r3(op); } int32 a_uses_r4(J_OPCODE op, int32 peep) { return (peep & P_RSHIFT) || (op == J_MLA) || (op == J_CALLI); } int32 a_modifies_mem(J_OPCODE op) { return (op & J_TABLE_BITS) > J_LAST_JOPCODE ? a_attributes(op) & _a_modify_mem : stores_r1(op) ? 1 : op == J_PUSHM || op == J_PUSHF || op == J_PUSHD || op == J_MOVC || op == J_CLRC; } #define a_pseudo_reads_r1(op) ((op) <= J_LAST_JOPCODE && pseudo_reads_r1(op)) bool setspsr(J_OPCODE op, int32 m) { return ( a_pseudo_reads_r1(op) #ifdef TARGET_HAS_BLOCKMOVE || ((op == J_MOVC || op == J_CLRC || op == J_PUSHC) && m > MOVC_LOOP_THRESHOLD) #endif ); } int32 power_of_two(int32 m) { int32 r = 0; while (!(m & 1)) { m = m>>1; r++; } return r; } #define ROR(x, n) (((x)<<(32L-(n))) | (((x)>>(n)) & ((1L<<(32L-(n)))-1L))) int32 eightbits(int32 n) { /* If n fits in an ARM immediate field this function returns a 12-bit */ /* quantity suitable for use there. Otherwise it returns -1 */ int32 shift; for (shift = 0; shift<0x1000; shift += 0x100) { if ((n&0xffffff00)==0) return(shift|n); n = ROR(n, 30); } return(-1); } void show_inst_direct(PendingOp *p) { IGNORE(p); } extern void syserr(char *, ...); void syserr(char *s, ...) { va_list ap; va_start(ap, s); fprintf(stderr, "fatal error: "); vfprintf(stderr, s, ap); va_end(ap); exit(1); } void cc_msg(char *s, ...) { va_list ap; va_start(ap, s); vfprintf(stderr, s, ap); va_end(ap); } int32 bitcount(int32 n) { /* return the number of bits present in the integer n. */ int32 r = 0; while (n!=0) n ^= n & (-n), r++; return(r); } int32 sysdebugmask = -1; int arthur_module = 0; extern void *SynAlloc(size_t); void *SynAlloc(size_t n) { return malloc(n); } extern void pr_stringsegs(StringSegList *z); void pr_stringsegs(StringSegList *z) { putc('"', stderr); for (; z!=NULL; z = z->strsegcdr) { char *s = z->strsegbase; int32 len = z->strseglen, i; for (i=0; i<len; i++) { int ch = ((unsigned char *)s)[i]; /* for isprint */ if (isprint(ch)) putc(ch, stderr); else if (ch=='\n') fprintf(stderr, "\\n"); else fprintf(stderr, "\\%lo", (long)ch); } } putc('"', stderr); } extern bool is_exit_label(void *); bool is_exit_label(void *l) { return ((int)l) < 0; } typedef struct { J_OPCODE op; int32 r1, r2, r3; int32 df; } Op; #define skipsp(f, ch) { while (isspace(ch)) ch = fgetc(f); } static int ReadN(FILE *f, int ch, int32 *p) { char b[16]; int i = 0; if (ch == ',') ch = fgetc(f); skipsp(f, ch); if (ch == '-') { b[i++] = ch; ch = fgetc(f); } if (ch == '&') { b[i++] = '0'; b[i++] = 'x'; ch = fgetc(f); } else if (ch == '0') { b[i++] = ch; ch = fgetc(f); if (ch == 'x' || ch == 'X') { b[i++] = ch; ch = fgetc(f); } } while (isxdigit(ch)) { b[i++] = ch; ch = fgetc(f); } b[i] = 0; sscanf(b, "%li", p); return ch; } typedef struct { char *name; int32 val; } JopAttr; static JopAttr attr_table[] = { {"EQ", Q_EQ}, {"NE", Q_NE}, {"HS", Q_HS}, {"LO", Q_LO}, {"HI", Q_HI}, {"LS", Q_LS}, {"GE", Q_GE}, {"LT", Q_LT}, {"GT", Q_GT}, {"LE", Q_LE}, {"AL", Q_AL}, {"NOT", Q_NOT}, {"UEQ", Q_UEQ}, {"UNE", Q_UNE}, {"UKN", Q_UKN}, {"VOLATILE", J_VOLATILE}, {"NEGINDEX", J_NEGINDEX}, {"SIGNED", J_SIGNED}, {"UNSIGNED", J_UNSIGNED}, {0,0} }; static JopAttr sh_table[] = { {"RSHIFT", SHIFT_RIGHT << J_SHIFTPOS}, {"LSHIFT", 0 << J_SHIFTPOS}, {"ARSHIFT", (SHIFT_ARITH + SHIFT_RIGHT) << J_SHIFTPOS}, {0,0} }; static JopAttr dead_table[] = { {"DEAD_R1", J_DEAD_R1}, {"DEAD_R2", J_DEAD_R2}, {"DEAD_R3", J_DEAD_R3}, {"0", 0}, {0,0} }; static PendingOp *ReadOp(FILE *f) { static PendingOp op; int ch = fgetc(f); op.op = op.r1 = op.r2 = op.r3 = op.r4 = op.peep = op.dataflow = op.cond = 0; skipsp(f, ch); if (ch == EOF) return NULL; { char b[32]; int i = 0; int32 n = 0; while (isalpha(ch)) { b[i++] = toupper(ch); ch = fgetc(f); } b[i] = 0; while (joptable[n].name != 0 && strcmp(b, joptable[n].name) != 0) n++; if (joptable[n].name == 0) { fprintf(stderr, "%s??\n", b); n = 0; } skipsp(f, ch); while (ch == '+') { i = 0; ch = fgetc(f); while (isalpha(ch)) { b[i++] = toupper(ch); ch = fgetc(f); } b[i] = 0; { JopAttr *p = attr_table; int32 a; while (p->name != 0 && strcmp(p->name, b) != 0) p++; if (p->name != 0) a = p->val; else { p = sh_table; while (p->name != 0 && strcmp(p->name, b) != 0) p++; if (p->name == 0) { fprintf(stderr, "%s??\n", b); a = 0; } else { int32 n; a = p->val; skipsp(f, ch); ch = ReadN(f, ch, &n); a |= n << J_SHIFTPOS; } } n |= a; } skipsp(f, ch); } op.op = n; } ch = ReadN(f, ch, &op.r1); ch = ReadN(f, ch, &op.r2); ch = ReadN(f, ch, &op.m); if (ch == ',') ch = fgetc(f); if (ch != '\n') { skipsp(f, ch); op.dataflow = 0; for (;;) { char b[32]; int i = 0; while (isalnum(ch) || ch == '_') { b[i++] = toupper(ch); ch = fgetc(f); } b[i] = 0; { JopAttr *p = dead_table; while (p->name != 0 && strcmp(p->name, b) != 0) p++; if (p->name != 0) op.dataflow |= p->val; else fprintf(stderr, "%s??\n", b); } if (ch!='+') break; ch = fgetc(f); } } ungetc(ch, f); return &op; } int main(int argc, char **argv) { peephole_init(); peephole_reinit(); if (argc <= 1) { fprintf(stderr, "what file?\n"); } else { FILE *f; f = (strcmp(argv[1], "-") == 0) ? stdin : fopen(argv[1], "r"); if (f == NULL) fprintf(stderr, "can't read \"%s\"\n", argv[1]); else { PendingOp *p; while ((p = ReadOp(f)) != NULL) peephole_op(p, 0); } } peephole_tidy(); }
stardot/ncc
mip/aeops.h
<reponame>stardot/ncc<filename>mip/aeops.h<gh_stars>0 /* * C compiler file aeops.h, Version 46 * Copyright (C) Codemist Ltd., 1988-1992. * Copyright Advanced RISC Machines Limited, 1990-1992. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _aeops_LOADED #define _aeops_LOADED 1 /* Notes (AM): 0) This is a core file of tree and syntax operators. Only some operators appear in the tree -- others are just punctuation or for language frontend internal use. 1) some lexical operators, like ++ and & correspond to more than one AE tree operation (pre/post incr. and bitand/addrof). The lexical routines are all assumed to return the operator corresponding to the binary or prefix form. Macros unaryop_() and postop_() are here provided for the syntax analyser to use for getting the other form. 2) Assignment operators are treated similarly. This time by the lexical routines which use assignop_() to get the assignment form. 3) It goes without saying that the caller must only apply these macros to valid arguments. 4) s_and provides a good view of this. 5) some AE operators do not have tokens (e.g. s_fnap, s_block). I have tried to enclose these in parens in the following. */ /* Here is a list of all tokens types used in C */ typedef enum AE_op { s_nothing, /* identifier, constants: */ s_error, s_unknown, /* e.g. template parameter value. */ #define iserrororunknown_(op) ((op) <= s_unknown) s_identifier, s_integer, s_floatcon, s_int64con, s_boolean, /* mainly represented by s_integer (type char) */ s_character, /* mainly represented by s_integer (type bool) */ s_wcharacter, /* mainly represented by s_integer (type wchar) */ s_string, #ifdef EXTENSION_UNSIGNED_STRINGS s_ustring, s_sstring, #endif s_wstring, /* s_binder heads binding records - see type Binder */ s_binder, s_tagbind, /* AM may want this soon LDS wants NOW */ s_member, /* LDS wants this too... for C++ */ #define hastypefield_(op) ((s_invisible<=(op) && (op)<=s_cast)) #define hasfileline_(op) ((op)==s_integer || (hastypefield_(op))) s_invisible, #define isdiad_(op) (s_andand<=(op) && (op)<=s_assign) /* expression operators, mainly non-letter symbols */ s_andand, s_comma, s_oror, s_arrowstar, /* C++ only */ s_dotstar, /* C++ only */ /* relations: reorder to make NOT or SWAP easier? */ #define isrelational_(op) (s_equalequal<=(op) && (op)<=s_lessequal) s_equalequal, s_notequal, #define isinequality_(op) (s_greater<=(op) && (op)<=s_lessequal) s_greater, s_greaterequal, s_less, s_lessequal, /* NB: the next 3 blocks of opcodes must correspond. */ #define floatableop_(op) \ (isrelational_(op)||(s_times<=(op) && (op)<=s_div)||(op) == s_cond) s_and, s_times, s_plus, s_minus, s_power, /* Needed for Fortran */ s_div, s_leftshift, s_or, s_idiv, s_rem, s_rightshift, s_xor, #define can_have_becomes(x) (((x)>= s_and) && ((x) <= s_xor)) #define and_becomes(x) ((AE_op)((x)+(s_andequal-s_and))) #define assignop_(op) ((AE_op)((op)+(s_andequal-s_and))) #define unassignop_(op) ((AE_op)((op)-(s_andequal-s_and))) #define isassignop_(x) (((x)>= s_andequal) && ((x) <= s_xorequal)) s_andequal, s_timesequal, s_plusequal, s_minusequal, s_powerequal, /* here for consistency - do not remove */ s_divequal, s_leftshiftequal, s_orequal, s_idivequal, s_remequal, s_rightshiftequal, s_xorequal, #define diadneedslvalue_(op) (s_andequal<=(op) && (op)<=s_assign) s_displace, /* no repn in C, ++ is spec case */ s_init, /* initialising '=' */ s_assign, /* unary ops. note that the first 4 correspond (via unaryop_()) to diads */ #define ismonad_(op) (s_addrof<=(op) && (op)<=s_postdec) #define unaryop_(x) ((AE_op)((x) + (s_addrof-s_and))) s_addrof, s_content, s_monplus, s_neg, s_bitnot, s_boolnot, s_content4, s_evalerror, /* A special sort of invisible mode */ /* move the next block of 4 to just before s_addrof? */ #define monadneedslvalue_(op) (isincdec_(op) || (op)==s_addrof) #define isincdec_(op) (s_plusplus<=(op) && (op)<=s_postdec) #define incdecisinc_(op) ((op) <= s_postinc) #define incdecispre_(op) ((((op)-s_plusplus) & 1) == 0) #define postop_(preop) ((AE_op)((preop)+(s_postinc-s_plusplus))) s_plusplus, s_postinc, s_minusminus, s_postdec, /* end of unary ops */ s_dot, s_arrow, s_cond, s_throw, /* CPLUSPLUS */ /* pseudo expression operators */ s_fnap, s_fnapstruct, s_fnapstructvoid, s_subscript, s_let, #ifdef EXTENSION_VALOF s_valof, /* BCPL-like valof block support */ #endif #ifdef RANGECHECK_SUPPORTED s_rangecheck, s_checknot, #endif s_qualdot, /* C++ expr.T::f() - no virtual call */ s_const_cast, /* CPLUSPLUS */ s_dynamic_cast, /* CPLUSPLUS */ s_reinterpret_cast, /* CPLUSPLUS */ s_static_cast, /* CPLUSPLUS */ s_cast, /* see hastypefield_() above */ s_sizeoftype, s_sizeofexpr, s_typeoftype, s_typeofexpr, s_ptrdiff, /* mip/cg.c command nodes (mainly keywords): */ s_break, s_case, s_catch, /* CPLUSPLUS */ s_colon, s_continue, s_default, s_do, s_endcase, /* C switch break = bcpl endcase */ s_for, s_goto, s_if, s_return, s_semicolon, s_switch, s_while, s_block, s_thunkentry, /* C++ virtual functions */ #ifdef EXTENSION_VALOF s_resultis, /* used with valof blocks */ #endif /* declaration nodes: */ s_decl, s_fndef, s_typespec, /* note the next two blocks must be adjacent for the next 3 tests. */ #define istypestarter_(x) (s_bool<=(x) && (x)<=s_lasttype) #define isstorageclass_(x) (s_auto<=(x) && (x)<=s_globalfreg) #define isdeclstarter_(x) (s_bool<=(x) && (x)<=s_typestartsym) #define shiftoftype_(x) ((x)-s_bool) #define bitoftype_(x) (1L<<((x)-s_bool)) /* soon: stop bool, float, wchar being a proper type. Map bool to */ /* short char, and wchar to long char. syn.c still needs older form? */ s_wchar, /* reserved, not yet used. */ s_bool, s_char, s_double, s_enum, s_float, s_int, s_struct, s_class, /* here, whether or not C++ */ s_union, # define CLASSBITS (bitoftype_(s_union+1)-bitoftype_(s_struct)) # define ENUMORCLASSBITS (CLASSBITS|bitoftype_(s_enum)) s_void, s_longlong, /* C extension */ s_typedefname, #define NONQUALTYPEBITS (bitoftype_(s_typedefname+1)-bitoftype_(s_bool)) /* modifiers last (high bits for m&-m trick) */ s_long, s_short, s_signed, s_unsigned, /* rework the next two lines? */ #define TYPEDEFINHIBITORS (bitoftype_(s_unsigned+1)-bitoftype_(s_bool)) #define CVBITS (bitoftype_(s_unaligned+1)-bitoftype_(s_const)) s_const, s_volatile, s_unaligned, #define s_lasttype s_unaligned #define NUM_OF_TYPES (s_lasttype-s_bool+1) /* currently 18 */ #define TYPEBITS (bitoftype_(s_lasttype+1)-bitoftype_(s_bool)) s_opaque, /* not in TYPEBITS since it is only kept for tagbinders */ /* storage classes and qualifiers */ #define bitofstg_(x) (1L<<((x)-s_auto+16)) /* ***NOTE*** bitofstg_() is ***NOT*** the same as bitoftype_(). Callers must be careful to use the right one. */ s_auto, s_extern, s_static, s_typedef, s_globalreg, s_register, s_friend, s_inline, s_virtual, s_weak, /* N.B. s_register is equivalent to 0x100000. See h.defs for other bits */ #define PRINCSTGBITS (bitofstg_(s_register)-bitofstg_(s_auto)) #define STGBITS (bitofstg_(s_weak+1)-bitofstg_(s_auto)) #define NUM_OF_STGBITS (s_weak-s_auto+1) /* currently 10 */ s_globalfreg, #define bitoffnaux_(x) ((FnAuxFlags)1<<((x)-s_pure)) #define isfnaux_(x) (s_pure<=(x) && (x)<s_typestartsym) s_pure, s_structreg, s_swi, s_swi_i, s_irq, s_commutative, s_typestartsym, /* used to help error reporting */ /* impedementia (not appearing in parse trees) */ s_mutable, /* CPLUSPLUS - currently ignored */ s_explicit, /* CPLUSPLUS - currently ignored */ s_namespace, /* CPLUSPLUS - currently ignored */ s_using, /* CPLUSPLUS - currently ignored */ s_else, s_toplevel, s_lbrace, s_lbracket, s_lpar, s_rbrace, s_rbracket, s_rpar, s_try, s_typeof, /* 2 special cases above */ s_sizeof, /* 2 special cases above */ s_typeid, /* CPLUSPLUS */ s_ellipsis, s_eol, s_eof, s_hash, /* inline assembler */ s_quote, /* inline assembler */ /* C++ keywords not in ANSI C. */ /* AM: memo, arrange non-aetree ops to be treated by langfe\*.[ch] */ /* via s_frontend to avoid mip getting lots of ops per language. */ s_asm, s_delete, s_new, s_operator, s_template, s_typename, /* names the following id a type, post-ARM feature */ s_export, s_this, # define isaccessspec_(op) (s_private <= (op) && (op) <= s_public ) /* bitofaccess_() bits are contiguous with CLASSBITS... */ # define bitofaccess_(x) (1L<<((x)-s_private+shiftoftype_(s_union+1))) # define ACCESSBITS (bitofaccess_(s_public+1)-bitofaccess_(s_private)) s_private, s_protected, s_public, /* non-keyword C++ operators... */ s_coloncolon, s_ovld, s_convfn, /* C++ front end only (temp?) */ s_pseudoid, /* C++ things like operator + */ s_cppinit, /* C++ syntax node for int a(5) */ s_memfndef, /* local to C++ f.e. */ s_ctor, /* C++ front end only. */ s_dtor, /* C++ front end only. */ #ifdef PASCAL /* PASCAL front-end symbols (not tree nodes) */ s_array, s_begin, s_downto, s_else, s_end, s_file, s_function, s_in, s_label, s_nil, s_of, s_packed, s_procedure, s_program, s_record, s_repeat, s_set, s_then, s_to, s_type, s_until, s_var, s_with, #endif /* PASCAL */ #ifdef BCPL s_global, s_manifest, s_abs, s_get, s_else, s_eqv, s_query, s_vecap, s_andlet, s_be, s_by, s_false, s_finish, s_into, s_repeat, s_repeatwhile, s_repeatuntil, s_test, s_true, s_table, s_unless, s_vec, s_valdef, #endif /* BCPL */ #ifdef FORTRAN s_boolean, /* needed for Fortran */ s_complex, /* needed for Fortran */ #endif #ifndef BCPL s_true, s_false, #endif s_SPARE1, s_SPARE2, s_NUMSYMS } AE_op; /* Any unqualified symbol is less than s_NUMSYMS <= s_SYMMASK */ #define s_SYMMASK 255 /* ORR this bit in to qualify a symbol... a hack for C++... */ #define s_qualified 512 /* synonyms (used in types for clarity) -- soon a separate ADT */ /* (along with s_typespec!, but see use of t_coloncolon etc in syn.c). */ #define t_fnap s_fnap #define t_subscript s_subscript #define t_content s_content #define t_ref s_addrof #define t_coloncolon s_coloncolon #define t_ovld s_ovld #define t_unknown s_unknown /* template type parameter */ #ifdef EXTENSION_UNSIGNED_STRINGS # define case_s_any_string case s_string: case s_wstring: \ case s_ustring: case s_sstring: #else # define case_s_any_string case s_string: case s_wstring: #endif #define isstring_(op) (s_string<=(op) && (op)<=s_wstring) #endif /* we use 'short long int' internally to represent 'long long int'. */ #define ts_longlong (bitoftype_(s_int)|bitoftype_(s_short)|bitoftype_(s_long)) #define ts_long (bitoftype_(s_int)|bitoftype_(s_long)) #define ts_short (bitoftype_(s_int)|bitoftype_(s_short)) #define ts_int (bitoftype_(s_int)) #define ts_float (bitoftype_(s_short)|bitoftype_(s_double)) #define ts_double (bitoftype_(s_double)) #define ts_longdouble (bitoftype_(s_long)|bitoftype_(s_double)) #define int_isshort_(m) \ (((m) & (bitoftype_(s_long) | bitoftype_(s_short))) ==\ bitoftype_(s_short)) #define is_float_(m) \ (((m) & (bitoftype_(s_short) | bitoftype_(s_double))) ==\ (bitoftype_(s_short)|bitoftype_(s_double))) #define is_double_(m) \ (((m) & (bitoftype_(s_long)|bitoftype_(s_short) | bitoftype_(s_double))) ==\ bitoftype_(s_double)) #define is_longdouble_(m) \ (((m) & (bitoftype_(s_long) | bitoftype_(s_double))) ==\ (bitoftype_(s_long)|bitoftype_(s_double))) #define is_anydouble_(m) \ (((m) & (bitoftype_(s_short) | bitoftype_(s_double))) ==\ bitoftype_(s_double)) #define int_islonglong_(m) \ (((m) & (bitoftype_(s_long) | bitoftype_(s_short))) ==\ (bitoftype_(s_long)|bitoftype_(s_short))) #define int_decodelength_(m) \ (((m) & bitoftype_(s_short)) ? \ (((m) & bitoftype_(s_long)) ? sizeof_longlong : sizeof_short) : \ (((m) & bitoftype_(s_long)) ? sizeof_long : sizeof_int)) #define int_decodealign_(m) \ (((m) & bitoftype_(s_short)) ? \ (((m) & bitoftype_(s_long)) ? alignof_longlong : alignof_short) : \ (((m) & bitoftype_(s_long)) ? alignof_long : alignof_int)) /* end of file aeops.h */
stardot/ncc
mip/util.h
<gh_stars>0 /* * C compiler file util.h, version 0.02 * Copyright (C) Codemist Ltd., 1987. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _util_LOADED #define _util_LOADED 1 #define isodigit(c) (!((c)-'0' & ~7)) /* tests for octal digit */ #define intofdigit(c) ((c)-'0') /* turns oct or dec digit to int */ #define pad_to_word(n) ((n)+3L & ~3L) #define padsize(n,align) (-((-(n)) & (-(align)))) /* the next routine pads a string size to a whole number of words (and counts 1 for the terminating NUL, returning the size in bytes. */ #define padstrlen(n) ((((int32)(n))+sizeof(int32)) & ~(sizeof(int32)-1L)) #endif /* end of util.h */
stardot/ncc
mip/regalloc.c
/* * C compiler file mip/regalloc.c. * Copyright (C) Codemist Ltd., 1988, 1991. * Copyright (C) Acorn Computers Ltd., 1988. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 73 * Checkin $Date$ * Revising $Author$ */ /* AM, Sept 91: In this version of the code (67), I have arranged to */ /* store local (within basic block) liveness info in 2 data structures. */ /* One, the traditional VRegSetP, and also a vector reg_lsbusetab[]. */ /* These are checked for consistency at all times. */ /* SOON I INTEND TO ELIMINATE VRegSetP FOR LOCAL INFO (BUT NOT GLOBAL). */ /* Vectors are converted to/from VRegSetP's at begining and end of */ /* basic blocks. The effect is to allow optimisation of char/short */ /* assignment w.r.t masking/sign extension. */ /* The code propagates demand (i.e. how many bits are needed) */ /* and currently uses this to turn LDRBs/u to plain LDRB &c and also */ /* smashes redundant J_AND/J_EXTEND to J_MOV. */ /* AM memo: tidy up the use of 'curstats'. */ /* AM whinge: Recently I changed the type of RealRegSet to allow */ /* machines with more than 32 registers. I found this very hard to do */ /* reliably due to the vast number of VoidStar formal parameters */ /* meaning it is impossible to find all occurrences. Please can we */ /* try to get rid of some? Unions would be MUCH safer. My view is */ /* that VoidStar should really only be used where it is essential */ /* and not to reduce type-checking (which indirectly increases the cost */ /* of modifications and the chances of buggy releases. */ /* Key suspicion: mapping fns are defined VoidStar for pseudo- */ /* polymorphism and then only used at one type. */ /* WGD,AM 7-1-88 Op deadbits bug corrected - when several live virtual regs are allocated to the same real register (this is encouraged by the voiding of copy instructions) - then only the final occurrence of the set should be recorded as dead, not the final occurrence of each member separately. New routine update_deadflags handles this. */ /* The simplest code AM can produce to exhibit this is: */ /* extern int z; void f(x) { while (x) z=1; while (x) z=1; } */ /* Experimental test of using SynAlloc/syn_list2 here wasted space. */ /* Following Nov 87 comment referenced below. */ /* Nov 87: Dataflow determination of dead registers introduced to allow */ /* store-to-store ops to be peepholed in (e.g. x = y; vs. x = y = z;) */ /* and use of ibm 370 RX arithmetic operations. */ /* Dead regs are indicated by the J_DEAD_Rx bits. Two points: */ /* 1. We do not claim that *ALL* dead regs are detected -- it seems */ /* overkill to detect it for (e.g. CALLR). However, we do guarantee */ /* that J_DEAD_Rx guarantees that Rx fields may be corrupted, but... */ /* 2. A (real) register may be marked dead, but become alive again by */ /* being set in the R1 field. As to why this is so, and why nothing */ /* can sensibly be done about it, observe that */ /* f(int x) { register int a = x; ... } will produce something like */ /* MOVR rt, rx; MOVR ra, rt. Note that (if x is not used further) */ /* then the first MOVR will mark R3 (rx) as dead and the second MOVR */ /* also R3 (now rt). Now either or both of these MOVR's may be */ /* killed by the mapping of virt. regs to (possibly same) phys. regs. */ /* The use of RetImplLab is nasty here (equivalent to RetVoidLab). */ /* move towards this code being machine independent apart from a few parameters, such as 'number of registers'. */ #define uint HIDE_HPs_uint #include <limits.h> #undef uint #include <time.h> #ifdef __STDC__ # include <string.h> #else # include <strings.h> #endif #include "globals.h" #include "regalloc.h" #include "errors.h" #include "sem.h" /* princtype -- @@@ yuk, lets use abstract interface */ #include "jopcode.h" #include "regsets.h" #include "store.h" #include "cg.h" #include "mcdep.h" /* immed_cmp, usrdbg(xxxx) */ #include "flowgraf.h" /* top_block, bottom_block */ #include "builtin.h" /* sim */ #include "aeops.h" /* bitofstg_(), s_register - sigh */ #include "sr.h" #include "armops.h" #include "inlnasm.h" static uint32 warn_corrupted_regs; /* Only one (of size vregistername) of these is allocated, so array OK. */ static unsigned char *reg_lsbusetab; #define ALLBITS 32 static int spaceofmask(unsigned32 m) { int k = 0; if (m & 0x80000000) return 32; /* For sake of 64 bit machines */ while (m) m>>=1, k++; return k==0 ? 1 : k; /* treat 0 as 1 */ } static int min(int a, int b) /* max is in misc.c!! */ { return a<=b ? a : b; } #define extend_bitsused(x) ((x)==0 || (x)==1 ? 8 : (x)==2 ? 16 : ALLBITS) /* Return number of least sig bits in arg which contribute to result. */ /* The case we really want for 'short' on the ARM is that SHRK 8; STRB */ /* only uses the low 16 bits of the SHRK. */ /* Always return at least 1 (so far) so that result matches classical */ /* dataflow analysis based on booleans. */ /* BEWARE: otherwise 2 shifts could give 0 bits required, but liveness */ /* would disagree, giving a syserr() in current code. */ /* Note that 'op' here has been masked with J_TABLE_BITS. */ static int reg_bitsrefd(const Icode *const ic, int demand, int pos) { switch (ic->op & J_TABLE_BITS) { /* can't optimise demand for CMP/DIV/SHRR etc. as all bits count. */ /* cases J_MOVK, J_ADCON, J_ADCONV probably can't benefit anyway. */ default: demand = ALLBITS; break; case J_STRBK: case J_STRBR: case J_STRBV: case J_STRBVK: demand = pos==1 ? 8 : ALLBITS; break; case J_STRWK: case J_STRWR: case J_STRWV: case J_STRWVK: demand = pos==1 ? 16 : ALLBITS; break; case J_MOVR: break; case J_ADDK: case J_SUBK: case J_MULK: break; case J_ORRK: case J_EORK: break; case J_ADDR: case J_SUBR: case J_MULR: break; case J_ANDR: case J_ORRR: case J_EORR: break; case J_RSBR: break; case J_NOTR: case J_NEGR: break; case J_STRV: /* Propagate number of bits needed from variable to value */ /* stored into it */ break; case J_LDRV: /* Propagate number of bits needed to variable from value */ /* value loaded from it */ break; /* Now some more fun cases... */ case J_ANDK: demand = (int)min(demand,spaceofmask(ic->r3.i)); break; /* For the next cautious test remember TARGET_LACKS_RIGHTSHIFT. */ case J_SHLK: demand = 0<=ic->r3.i && ic->r3.i<32 ? (int)max(demand-(int)ic->r3.i,1) : ALLBITS; break; case J_SHRK: demand = 0<=ic->r3.i && ic->r3.i<32 ? (int)min(demand+(int)ic->r3.i,32) : ALLBITS; break; /* Why don't we change extend so that it takes a mask like ANDK? */ case J_EXTEND: demand = extend_bitsused(ic->r3.i); break; } #ifdef J_SHIFTPOS if (pos == 3 && (ic->op & J_SHIFTMASK) != 0) /* shifted R3 */ { int32 shift = (ic->op >> J_SHIFTPOS) & SHIFT_MASK; switch((ic->op >> J_SHIFTPOS) & (SHIFT_ARITH | SHIFT_RIGHT)) { case 0: /* ROR */ if (shift == 0) shift = 1; /* RRX!! */ case SHIFT_RIGHT: /* LSR */ case SHIFT_RIGHT | SHIFT_ARITH: /* ASR */ demand += shift; if (demand > ALLBITS) demand = ALLBITS; break; case SHIFT_ARITH: /* LSL! */ demand -= shift; if (demand < 0) demand = 0; break; } } #endif return demand; } #define ClashAllocType AT_Syn #define ListAllocType AT_Syn #define CopyAllocType AT_Syn /* extra value for the r->realreg field... */ #define R_UNSCHEDULED (-1L) /* not scheduled for allocation yet */ #define R_SCHEDULED (-2L) /* now scheduled for allocation */ #define R_WILLFIT (-3L) /* allocatable, but not yet assigned */ /* (now defunct: future spilling considered */ /* harmful) */ #define R_SPILT (-4L) /* need to spill onto stack */ #define R_BOGUS (-5L) /* used transiently: != SPILT, != WILLFIT */ typedef struct ValnRegList ValnRegList; typedef struct VRegister { VRegnum rname; VRegSetP clash2; /* with registers earlier in allocation order */ VRegSetP clashes; /* and later */ union { int32 nclashes; Binder *spillbinder;} u; RealRegister realreg; int32 heapaddr; /* effectively the inverse permutation */ struct VRegister *perm; int32 ncopies; int32 refcount; VRegnum slave; uint32 valnum; ValnRegList *valsource; uint32 valwritecount; } VRegister; #define vregname_(vr) ((vr)->rname & ~REGSORTMASK) #define vregtype_(vr) ((vr)->rname & REGSORTMASK) #define valnr_(vr) (vreg_(vr)->valnum) #define valsource_(vr) (vreg_(vr)->valsource) #define valwritecount_(vr) (vreg_(vr)->valwritecount) #define VALN_UNSET 0 #define VALN_MULTIPLE 0x80000000 #define VALN_SLAVE 0x40000000 #define VALN_DEAD 0x20000000 #define VALN_MASK 0x1fffffff #define VALN_REAL 1 #define is_real_valn_(n) ((n)!=VALN_UNSET && !((n) & VALN_MULTIPLE)) #define val_(n) ((n) & VALN_MASK) #define using_valnr (!(var_cc_private_flags & 0x08000000)) RealRegSet regmaskvec; /* registers used or corrupted in this proc */ static RealRegSet m_intregs, m_notpreserved; #ifndef TARGET_SHARES_INTEGER_AND_FP_REGISTERS static RealRegSet m_fltregs; #endif #ifdef ADDRESS_REG_STUFF static RealRegSet m_addrregs; #endif static int32 n_real_spills, n_cse_spills, /* these seem to be real.. */ tot_real_spills, tot_cse_spills, /* while these are just for. */ spill_cost, tot_cost, choose_count; /* the trace option. */ static Icode ic_noop; /* The following routines take pointers to RealRegSets as args even */ /* though conceptually RealRegSets should be passed by value. */ #if (NMAGICREGS <= 32) bool member_RealRegSet(RealRegSet const *a, unsigned32 r) { return ((a->map)[0] & regbit(r)) != 0; } void augment_RealRegSet(RealRegSet *a, unsigned32 r) { (a->map)[0] |= regbit(r); } unsigned32 delete_RealRegSet(RealRegSet *a, unsigned32 r) { unsigned32 oldval = (a->map)[0] & regbit(r); (a->map)[0] ^= oldval; return oldval; } bool intersect_RealRegSet(RealRegSet *a, RealRegSet const *b, RealRegSet const *c) { return ((a->map)[0] = (b->map)[0] & (c->map)[0]) != 0; } void union_RealRegSet(RealRegSet *a, RealRegSet const *b, RealRegSet const *c) { (a->map)[0] = (b->map)[0] | (c->map)[0]; } void difference_RealRegSet(RealRegSet *a, const RealRegSet *b, const RealRegSet *c) { (a->map)[0] = (b->map)[0] & ~(c->map)[0]; } void map_RealRegSet(RealRegSet const *a, RealRegSet_MapFn *f, RealRegSet_MapArg *arg) { unsigned32 m = ((a)->map)[0]; int j; for (j = 0; m != 0; j++) if (m & regbit(j)) { f(j, arg); m ^= regbit(j); } } #else bool member_RealRegSet(RealRegSet const *a, unsigned32 r) { return ((a->map)[r/32] & regbit(r % 32)) != 0; } void augment_RealRegSet(RealRegSet *a, unsigned32 r) { (a->map)[r/32] |= regbit(r % 32); } unsigned32 delete_RealRegSet(RealRegSet *a, unsigned32 r) { unsigned32 oldval = (a->map)[r/32] & regbit(r % 32); (a->map)[r/32] ^= oldval; return oldval; } bool intersect_RealRegSet(RealRegSet *a, const RealRegSet *b, const RealRegSet *c) { int i; bool res = 0; for (i = 0; i < (NMAGICREGS+31)/32; i++) if (((a->map)[i] = (b->map)[i] & (c->map)[i]) != 0) res = 1; return res; } void union_RealRegSet(RealRegSet *a, const RealRegSet *b, const RealRegSet *c) { int32 i; for (i = 0; i < (NMAGICREGS+31)/32; i++) (a->map)[i] = (b->map)[i] | (c->map)[i]; } void difference_RealRegSet(RealRegSet *a, const RealRegSet *b, const RealRegSet *c) { int32 i; for (i = 0; i < (NMAGICREGS+31)/32; i++) (a->map)[i] = (b->map)[i] & ~(c->map)[i]; } void map_RealRegSet(RealRegSet const *a, RealRegSet_MapFn *f, RealRegSet_MapArg *arg) { int32 i, j; for (i = 0; i < (NMAGICREGS+31)/32; i++) { unsigned32 m = ((a)->map)[i]; int j; for (j = 0; m != 0; j++) if (m & regbit(j)) { f(32*i + j, arg); m ^= regbit(j); } } } #endif static void print_RealRegSet_cb(RealRegister r, RealRegSet_MapArg *arg) { cc_msg("%s%ld", *(arg->s), (long)r); *(arg->s) = " "; } void print_RealRegSet(RealRegSet const *a) { char *s = ""; RealRegSet_MapArg arg; arg.s = &s; map_RealRegSet(a, print_RealRegSet_cb, &arg); } #ifdef TARGET_SHARES_INTEGER_AND_FP_REGISTERS #ifdef never /* I demand an even/odd pair for float regs as well as double ones */ /* because doing so (slightly) simplifies allocation and because float */ /* registers will not often arise in C anyway. Fix up later maybe. */ #define needsregpair_(rsort) ((rsort) == DBLREG || (rsort) == FLTREG) #else /* The aih324 wants it this way... */ #define needsregpair_(rsort) ((rsort) == DBLREG) #endif #define other_halfreg(r) ((r)+1) /* works on vregs and physical regs. */ static bool two_bits(unsigned32 w) { /* Used to test if an even/odd register pair is available */ /* There is probably a fast trick involving w+0x55555555! */ int i; for (i=0; i<31; i++) { if ((w & 3) == 3) return YES; else w = w >> 2; } return NO; } static bool nonempty_RealRegSet(const RealRegSet *a, int32 rsort) { int32 i; bool res = 0; if (needsregpair_(rsort)) { for (i = 0; i < (NMAGICREGS+31)/32; i++) if (two_bits((a->map)[i])) res = 1; } else { for (i = 0; i < (NMAGICREGS+31)/32; i++) if ((a->map)[i] != 0) res = 1; } return res; } #else /* TARGET_SHARES_INTEGER_AND_FP_REGISTERS */ # if NMAGICREGS <= 32 # define nonempty_RealRegSet_x(a) (((a)->map)[0] != 0) # else static bool nonempty_RealRegSet_x(const RealRegSet *a) { int32 i; bool res = 0; for (i = 0; i < (NMAGICREGS+31)/32; i++) if ((a->map)[i] != 0) res = 1; return res; } #endif #define nonempty_RealRegSet(a,sort) nonempty_RealRegSet_x(a) #endif /* TARGET_SHARES_INTEGER_AND_FP_REGISTERS */ #ifdef ADDRESS_REG_STUFF static bool spillpanic; /* forced to demote A to D register? */ #endif /* @@@ tidy up these two parallel representations... */ static VRegSetP globalregvarset; static RealRegSet globalregvarvec; static void regalloc_changephase(void); typedef union vreg_type { VRegister *vreg; VRegnum type; } vreg_type; static vreg_type (*(vregheap[REGHEAPSEGMAX]))[REGHEAPSEGSIZE]; static unsigned32 vregistername; #define vregtypetab_(n) (*vregheap[(n)>>REGHEAPSEGBITS]) \ [(n)&(REGHEAPSEGSIZE-1L)].type #define vreg_(n) (*vregheap[(n)>>REGHEAPSEGBITS]) \ [(n)&(REGHEAPSEGSIZE-1L)].vreg /* Note that vreg_() is set and then never updated -- permregheap_() is */ #define permregheap_(n) (vreg_((n)+NMAGICREGS)->perm) /* * Statistics-gathering stuff. */ typedef struct RegStats { unsigned32 dataflow_iterations; unsigned32 ncopies; unsigned32 copysquares; unsigned32 copysquarebytes; unsigned32 nlists; unsigned32 newlists; unsigned32 listbytes; unsigned32 nvregs; unsigned32 vregbytes; unsigned32 nsquares; unsigned32 squarebytes; unsigned32 nregsets; unsigned32 newregsets; unsigned32 regsetbytes; unsigned32 clashbytes; /* total of clashmatrix/regset stuff */ } RegStats; static RegStats curstats, maxstats; static clock_t regalloc_clock1, regalloc_clock2, dataflow_clock; /* register_number() returns the physical register corresponding to a */ /* virtual register, else a number < 0 (like R_BOGUS, q.v.) */ extern RealRegister register_number(VRegnum a) { return vreg_(a)->realreg; } /* TARGET_IS_NULL is defined when the system being built is a Lint-like */ /* checker or some source-to-source conversion utility. It is desirable */ /* to keep enough of the register allocation code that data-flow oddities */ /* such as unused variables can be reported on, but much of the rest can */ /* (and should) be skipped as unnecessary. */ #ifndef TARGET_IS_NULL /* first routines to keep the register heap in order of number of clashes */ /* so allocation can proceed from the most(?) clashing register first. */ /* Note that these permute the vregheap table. */ /* Comparison routine for deciding heap-orderedness property. */ /* Use ->nclashes as primary key, but experimentally use number of real */ /* register copies for secondary one in lexicographic order. */ /* To achieve this in a way which does not change during allocation */ /* (which would upset the ordering property (but not chaotically)) */ /* we eliminate registers, 1. by least clashes and then 2. by least */ /* register copies, counting a physical (magic) register many times. */ #define has_physical_copy_(r) ((r)->ncopies>=0x10000) static int32 reg_cmp(VRegister *v, VRegister *w) { int32 d; if (v->u.nclashes == 0 && has_physical_copy_(v)) { if (w->u.nclashes == 0 && has_physical_copy_(w)) return v->ncopies - w->ncopies; else return 1; } if (w->u.nclashes == 0 && has_physical_copy_(w)) return 0; if ((d = v->u.nclashes - w->u.nclashes) != 0) return d; return v->ncopies - w->ncopies; } static void downheap(int32 k, int32 n) { /* fix up heap property at position k in the register heap */ /* see Sedgewick's book on algorithms for commentary on this. */ VRegister *v = permregheap_(k), *w; while (k <= (n/2L)) { int32 j = k + k; if (j < n) { if (reg_cmp(permregheap_(j),permregheap_(j+1)) > 0) j++; } if (reg_cmp(v, permregheap_(j)) <= 0) break; w = permregheap_(k) = permregheap_(j); w->heapaddr = k; k = j; } permregheap_(k) = v; v->heapaddr = k; } static void upheap(int32 k) { VRegister *v = permregheap_(k), *w; int32 k1; /* NB that there is a sentinel register with nclashes=-1 in the 0 */ /* position of the heap - that simplifies the end-test here. */ while (k1 = k/2L, w = permregheap_(k1), reg_cmp(w,v) > 0) { permregheap_(k) = w; w->heapaddr = k; k = k1; } permregheap_(k) = v; v->heapaddr = k; } #define printvregclash(a) print_clashes(a) #define printvregclash2(a) vregset_print((a)->clash2) static Relation clashmatrix; static Relation copymatrix; static RelationAllocRec clashrallocrec; /* = {ClashAllocType, &curstats.nsquares, &curstats.squarebytes}; */ static RelationAllocRec copyallocrec; /* = {CopyAllocType, &curstats.copysquares, &curstats.copysquarebytes}; */ static void clash_reinit(int32 nregs) { curstats.nvregs = nregs; clashmatrix = relation_init(&clashrallocrec, nregs, &curstats.vregbytes); copymatrix = relation_init(&copyallocrec, nregs, &curstats.vregbytes); vregset_init(); } static void add_copy(VRegnum a, VRegnum b); static void add_clash(VRegnum a, VRegnum b) { /* a register can never clash with itself */ if (a == b) { if (!(procflags & PROC_INLNASM)) syserr(syserr_regalloc_clash, a); return; } /* registers with the same value number never clash */ if (using_valnr) { uint32 vala = valnr_(a), valb = valnr_(b); if ( (is_real_valn_(vala) && is_real_valn_(valb) && val_(vala) == val_(valb)) || (is_real_valn_(vala) && (vala & VALN_SLAVE) && RegList_Member(b, valsource_(a))) || (is_real_valn_(valb) && (valb & VALN_SLAVE) && RegList_Member(a, valsource_(b))) ) { if (debugging(DEBUG_REGS)) cc_msg("Prevent clash %ld %ld - %ld%s%s\n", (long)a, (long)b, (long)val_(vala), vala & VALN_SLAVE ? "S" : "", vala & VALN_DEAD ? "D" : ""); add_copy(a, b); return; } } #ifndef TARGET_SHARES_INTEGER_AND_FP_REGISTERS { RegSort atype = vregtype_(vreg_(a)); RegSort btype = vregtype_(vreg_(b)); # ifdef ADDRESS_REG_STUFF if (atype == ADDRREG) atype = INTREG; if (btype == ADDRREG) btype = INTREG; # endif if (atype != btype) { if ((atype == INTREG) || (btype == INTREG)) return; } } #endif if (a < b) { VRegnum t = a; a = b; b = t; } if ((b < 0) || ((uint32)a >= vregistername)) syserr(syserr_addclash, (long)a, (long)b); if (relation_add(a, b, clashmatrix, &clashrallocrec)) { vreg_(a)->u.nclashes++; vreg_(b)->u.nclashes++; } } static void clashkillbits_cb(int32 k, VoidStar arg) { /* clashkillbits_cb is passed as parameter and so needs silly type. */ RealRegSet *m = (RealRegSet *) arg; RealRegister r = register_number((VRegnum)k); if ((unsigned32)r<(unsigned32)NMAGICREGS) /* @@@ isany_realreg()? */ #ifdef TARGET_SHARES_INTEGER_AND_FP_REGISTERS { /* I certainly need to do more here */ delete_RealRegSet(m,r); } #else delete_RealRegSet(m,r); #endif } static void clashkillbits(RealRegSet *m, VRegister *reg) { vregset_map(reg->clash2, clashkillbits_cb, (VoidStar)m); } static VRegSetAllocRec clashvallocrec; /* = { * ClashAllocType, * &curstats.nregsets, * &curstats.newregsets, * &curstats.regsetbytes }; */ static void removeclashes_rcb(int32 vr, VoidStar arg) { VRegSetP *residual = (VRegSetP *) arg; VRegister *clashee = vreg_(vr); clashee->u.nclashes--; *residual = vregset_insert(vr, *residual, NULL, &clashvallocrec); if (clashee->realreg == R_UNSCHEDULED) upheap(clashee->heapaddr); } static void removeclashes(VRegister *vreg) { VRegnum reg = vregname_(vreg); VRegSetP residual = NULL; relation_mapanddelete(reg, clashmatrix, removeclashes_rcb, (VoidStar)&residual); vreg->clash2 = residual; vreg->clashes = vregset_difference(vreg->clashes, vreg->clash2); vreg->u.nclashes = 0; } static void printvreg(VRegnum vr) { int c = 'g'; if (vr != GAP) { RegSort type = vregtype_(vreg_(vr)); c = type == FLTREG ? 'f' : type == DBLREG ? 'd' : #ifdef ADDRESS_REG_STUFF type == ADDRREG ? 'a' : #endif 'r'; } cc_msg(" %c%ld", c, (long)vr); } static void print_clashes(VRegister *vreg) { /* print the set of VRegisters which clash with vreg */ VRegnum reg = vregname_(vreg); relation_map1(reg, clashmatrix, printvreg); } static void add_copy(VRegnum a, VRegnum b) /* Somebody has issued a 'MOVR a,b' or maybe a 'MOV b,a'. Life will be */ /* distinctly better if I can arrange that r1 and r2 get put in the */ /* same real register. Make a table of associations to help me to */ /* achieve this at least some of the time. */ { if (a == b) return; #ifndef TARGET_SHARES_INTEGER_AND_FP_REGISTERS { RegSort atype = vregtype_(vreg_(a)); RegSort btype = vregtype_(vreg_(b)); #ifdef ADDRESS_REG_STUFF if (atype == ADDRREG) atype = INTREG; if (btype == ADDRREG) btype = INTREG; #endif if (atype != btype) { /* AM believes that atype and btype will always be the same */ /* with the possible exception of MOVDFR. Hence the RETURN */ /* below can never be executed. */ if ((atype == INTREG) || (btype == INTREG)) return; } } #endif /* Corresponding code in add_clash() ensures a<b here. Should we? */ if (relation_add(a, b, copymatrix, &copyallocrec)) { curstats.ncopies++; vreg_(a)->ncopies += b<NMAGICREGS ? 0x10000 : 1; vreg_(b)->ncopies += a<NMAGICREGS ? 0x10000 : 1; } } static void vregset_print(VRegSetP set) { vregset_map1(set, printvreg); } /* * End of abstract data type for reg clash matrix. */ #else /* TARGET_IS_NULL */ static void add_clash(VRegnum r1n, VRegnum r2n) { IGNORE(r1n); IGNORE(r2n); } static VRegSetP set_register_copy(VRegnum r, VRegSetP s, VRegnum rsource) { IGNORE(r); IGNORE(s); IGNORE(rsource); return NULL; } static VRegSetP set_register_slave(VRegnum r, VRegSetP s, VRegnum rmaster) { IGNORE(r); IGNORE(s); IGNORE(rmaster); return NULL; } #endif /* TARGET_IS_NULL */ static void stats_print(RegStats *p) { cc_msg("-- passes %2li: copies =%4ld, lists = %4ld, vregs = %4ld\n", p->dataflow_iterations, p->ncopies, p->nlists, p->nvregs); cc_msg("%19s %6ld %13ld %13ld\n", "space", p->copysquarebytes, p->listbytes, p->vregbytes); cc_msg("-- squares =%4ld, regsets =%4ld, bytes =%6ld\n", p->nsquares, p->nregsets, p->clashbytes); cc_msg("%19s %6ld %13ld total=%6ld\n", "space", p->squarebytes, p->regsetbytes, p->clashbytes); } static void stats_endproc(void) { unsigned32 x, j, *cur, *max; curstats.clashbytes = curstats.vregbytes + curstats.squarebytes + curstats.regsetbytes; if (curstats.nvregs >= 128) { cc_msg("regalloc space stats for big procedure:\n"); stats_print(&curstats); } cur = (unsigned32 *)&curstats; max = (unsigned32 *)&maxstats; for (j = 0; j < sizeof(curstats)/sizeof(unsigned32); ++j) { x = *cur++; if (x > *max) *max = x; ++max; } } /* Consider (p() ? 0:1). If we generate <test> ... MOVK v,0 ... MOVK v,1 */ /* and 0,1 are put in master regs i0,i1 then we find that v is a slave of */ /* both i0 and i1. The code in regalloc then causes v not to clash with */ /* either i0 nor i1 which can allow i0 to share with v in spite of the fact*/ /* that v can be updated to 1 when i0 is still live. */ /* HACK. Note that things are OK when slave_list is a (reverse) forest */ /* Hence delete all entries (v,i0), (v,i1) when i0 != i1. */ /* Memo to AM: the idea of slave_list would better be replaced with a */ /* general algorithm which stops x & y clashing in: */ /* f(x) { int y = x; return x+y;} */ #ifndef TARGET_IS_NULL typedef struct ReadonlyCopy /* loopopt.c and regalloc.c interface */ { struct ReadonlyCopy *next; VRegnum r1; VRegnum r2; } ReadonlyCopy; static ReadonlyCopy *slave_list; /* note_slave() and forget_slave() are exported for cse.c: */ void note_slave(VRegnum slave, VRegnum master) { ReadonlyCopy *p; for (p = slave_list; p != NULL; p = p->next) if (p->r1 == slave) { if (p->r2 != master) p->r2 = GAP; /* see above note re trees */ return; } /* allocate BindAlloc store to survive into regalloc.c */ p = (ReadonlyCopy *) BindAlloc(sizeof(ReadonlyCopy)); p->next = slave_list, p->r1 = slave, p->r2 = master; slave_list = p; } void forget_slave(VRegnum slave, VRegnum master) { ReadonlyCopy *p, **prev; for (prev = &slave_list; (p = *prev) != NULL; prev = &p->next) if (p->r1 == slave) { if (p->r2 == master) *prev = p->next; else if (!isany_realreg_(slave) && p->r2 != GAP) syserr(syserr_forget_slave, slave, master, p->r2); return; } } static bool reg_overlord(VRegnum r1, VRegnum r2) /* true iff (r1,r2) is in the transitive closure of slave_list */ { for (;;) { VRegnum r = vreg_(r1)->slave; if (r == r2) return YES; else if (r == GAP) return NO; r1 = r; } } #else void note_slave(VRegnum slave, VRegnum master) { IGNORE(slave); IGNORE(master); } #endif #ifdef LSBUSE_CONSISTENCY_CHECK static uint8 *lsbmap; #define LSBQUANTUM 128 #define lsbmap_(r) (lsbmap[r/(8*LSBQUANTUM)] & (1<<((r/LSBQUANTUM)%8))) #define setlsbmap_(r) (lsbmap[r/(8*LSBQUANTUM)] |= 1<<((r/LSBQUANTUM)%8)) #else #define lsbmap_(r) 1 #define setlsbmap_(r) #endif static VRegSetAllocRec listallocrec; /* = {ListAllocType, &curstats.nlists, &curstats.newlists, * &curstats.listbytes}; */ /* Sept 91: define procs to hide vregset_xxx/reg_lsbusetab reps. */ static int reg_demand(VRegnum r) { if ((unsigned32)r >= vregistername) syserr(syserr_regno, (long)r); return reg_lsbusetab[r]; } static void live_print(char *s) { unsigned i; cc_msg("live(%s):", s); for (i = 0; i < vregistername; i++) if (reg_lsbusetab[i]) cc_msg(" r%d:%d", i, reg_lsbusetab[i]); cc_msg("\n"); } static void live_union_anon(VRegnum r) { if ((unsigned32)r >= vregistername) syserr(syserr_regno, (long)r); setlsbmap_(r); reg_lsbusetab[r] = ALLBITS; } static VRegSetP live_union(VRegSetP s1, VRegSetP s2, VRegSetAllocRec *allocrec) { vregset_map1(s2, live_union_anon); return vregset_union(s1, s2, allocrec); } static bool live_member(VRegnum r, VRegSetP set) { return vregset_member((int32)r, set); } static VRegSetP live_delete(VRegnum r, VRegSetP set, bool *livep) { if ((unsigned32)r >= vregistername) syserr(syserr_regno, (long)r); setlsbmap_(r); reg_lsbusetab[r] = 0; return vregset_delete((int32)r, set, livep); } /* One can think of 'reference_register()' as 'live_insert()'... */ static VRegSetP reference_register( VRegnum r, int demand, VRegSetP s, bool *alreadylive) /* s is a list of registers whose value is needed. We have encountered */ /* (in a backwards scan over a basic block) an instruction that uses the */ /* value of register r. r gets added to the list of registers that need */ /* to be given a value. */ /* BEWARE: the result is compared with s to determine if s became live. */ /* Sep 91: Is this still true? */ { if ((unsigned32)r >= vregistername) /* includes 'GAP' */ syserr(syserr_regno, (long)r); s = vregset_insert(r, s, alreadylive, &listallocrec); setlsbmap_(r); if (reg_lsbusetab[r] < demand) reg_lsbusetab[r] = demand; return s; } /* things for pass2 (the exact clash info) only ... */ static BindList *thisBlocksBindList; static void makebindersclash(VRegnum r, BindList *bl, VRegnum rx) { BindList *ab = argument_bindlist; for ( ; ab!=NULL ; ab = ab->bindlistcdr ) { VRegnum r1 = bindxx_(ab->bindlistcar); if (r1!=GAP && r1!=rx && r1!=r) add_clash(r1, r); } for ( ; bl!=NULL ; bl = bl->bindlistcdr ) { VRegnum r1 = bindxx_(bl->bindlistcar); if (r1!=GAP && r1!=rx && r1!=r) add_clash(r1, r); } } static void setregister_cb(int32 r, VoidStar r1) { /* the type of 'r1' is a lie for map-function vregset_map. */ add_clash((VRegnum)r, (VRegnum)(IPtr)r1); } static VRegSetP set_register1(VRegnum r, VRegSetP s) { vregset_map(s, setregister_cb, (VoidStar)(IPtr)r); #ifdef TARGET_SHARES_INTEGER_AND_FP_REGISTERS if (is_physical_double_reg_(r)) vregset_map(s, setregister_cb, (VoidStar)(IPtr)other_halfreg(r)); #endif if (usrdbg(DBG_VAR) && !usrdbg(DBG_OPT_REG)) makebindersclash(r, thisBlocksBindList, GAP); return s; } static void corrupt_register(VRegnum r, VRegSetP s) /* register r has its value altered by this instruction, but not in a */ /* useful or predictable way. Ensure that r is not unified with any */ /* other register currently active */ { /* AM has thought and sees no real difference between corrupt_register */ /* and set_register */ if (vregset_member(r, s)) { if (procflags & PROC_INLNASM) { if (!(warn_corrupted_regs & regbit(r))) cc_warn(asm_err_corrupted_reg, r); warn_corrupted_regs |= regbit(r); return; } else syserr(syserr_corrupt_register, (long)r, s); /* insert to check */ } set_register1(r, s); } static void corrupt_physical_register(VRegnum r, VRegSetP s) { /* 'r' must be a physical register, corrupt it and add it to */ /* regmaskvec. */ if (!isany_realreg_(r)) syserr(syserr_regalloc); augment_RealRegSet(&regmaskvec, r); #ifdef TARGET_SHARES_INTEGER_AND_FP_REGISTERS if (is_physical_double_reg_(r)) augment_RealRegSet(&regmaskvec, other_halfreg(r)); #endif corrupt_register(r, s); } static VRegSetP set_register(VRegnum r, VRegSetP s) /* This is called when an instruction that sets r is found (and when the */ /* instruction is not a direct copy instruction, and when then value of */ /* the register is (expected to be) needed. */ { if (isany_realreg_(r)) /* physical register used -> need to be saved */ augment_RealRegSet(&regmaskvec, r); /* In the next line, if !member(r,s) we have the dataflow anomaly */ /* 'register set but value not used'. In general this will be */ /* optimised away, but it also occurs for calls to void functions */ /* and so is better reported elsewhere (see J_STRV code below). */ s = live_delete(r, s, NULL); #ifdef TARGET_SHARES_INTEGER_AND_FP_REGISTERS if (is_physical_double_reg_(r)) s = live_delete(other_halfreg(r), s, NULL); #endif return set_register1(r, s); } #ifndef TARGET_IS_NULL typedef struct { VRegnum r; VRegnum rsource; RegList *rlist; } SRCRecord; static void setregistercopy_cb(int32 ar, VoidStar arg) { SRCRecord *p = (SRCRecord *)arg; VRegnum r = (VRegnum)ar; if (r != p->rsource && r != p->r) add_clash(p->r, r); } static void setregistercopy_cb2(int32 ar, VoidStar arg) { SRCRecord *p = (SRCRecord *)arg; VRegnum r = (VRegnum)ar; if (val_(valnr_(r)) == val_(valnr_(p->r))) p->rlist = mkRegList(p->rlist, r); } static VRegSetP set_register_copy(VRegnum r, VRegSetP s, VRegnum rsource) /* This is called when an instruction that copies rsource into r is seen */ { SRCRecord sc; bool debug_regs = usrdbg(DBG_VAR) && !usrdbg(DBG_OPT_REG); /* If r is a global register variable and r is dead, other vregs * may share the same register. Only when register optimizations * are disabled this is suppressed by not calling live_delete. */ if (!debug_regs || !vregset_member(r, globalregvarset)) s = live_delete(r, s, NULL); sc.r = r; sc.rsource = rsource; if (using_valnr && val_(valnr_(r)) == val_(valnr_(rsource)) && is_real_valn_(valnr_(r))) { sc.rlist = NULL; relation_map(r, copymatrix, setregistercopy_cb2, &sc); while (sc.rlist != NULL) { add_copy(rsource, (VRegnum)sc.rlist->rlcar); sc.rlist = (RegList *)discard2(sc.rlist); } } /* r conflicts with all live registers EXCEPT rsource. */ vregset_map(s, setregistercopy_cb, (VoidStar) &sc); if (debug_regs) makebindersclash(r, thisBlocksBindList, rsource); if (debugging(DEBUG_REGS)) cc_msg("Record copy %ld %ld\n", (long)r, (long)rsource); add_copy(r, rsource); return s; } static void setregisterslave_cb(int32 r, VoidStar r1) { /* the type of 'r1' is a lie for map-function vregset_map. */ if (!reg_overlord((VRegnum)(IPtr)r1, (VRegnum)r)) add_clash((VRegnum)r, (VRegnum)(IPtr)r1); } static VRegSetP set_register_slave(VRegnum r, VRegSetP s, VRegnum rmaster) /* This is a re-working of slave_list. Not yet final because it builds */ /* in the knowledge that code in other parts of the compiler did it. */ /* r is a slave target register being set. Arrange that it clashes with */ /* all live registers except its masters. */ { s = live_delete(r, s, NULL); /* r conflicts with all live registers EXCEPT its masters. */ vregset_map(s, setregisterslave_cb, (VoidStar)(IPtr)r); if (usrdbg(DBG_VAR) && !usrdbg(DBG_OPT_REG)) { BindList *bl = thisBlocksBindList; for ( ; bl!=NULL ; bl = bl->bindlistcdr ) { VRegnum r1 = bindxx_(bl->bindlistcar); if (r1 != GAP && !reg_overlord(r, r1)) add_clash(r1, r); } } if (debugging(DEBUG_REGS)) cc_msg("Record slave copy %ld %ld\n", (long)r, (long)rmaster); add_copy(r, rmaster); return s; } #endif /* TARGET_IS_NULL */ /* Value numbering pass, called once per block before register clashes */ /* are collected for the block. All registers are set to a distinguished */ /* 'UNSET' state, apart from those imported to the block (which are each */ /* allocated distinct value numbers). Writes to a destination register */ /* are either */ /* copies from a source register. The value number of the source */ /* register is written to the value number of the destination */ /* something else. A new value number, distinct from any other, is */ /* given to the destination register */ /* In either case, if the value number of the destination is not 'UNSET',*/ /* the destination receives a sticky 'WRITTEN TWICE' flag. */ /* Then, during the collection of register clashes, if a call to */ /* add_clash(a, b) is made but valnr_(a) == valnr_(b) (and neither has */ /* the 'WRITTEN TWICE' flag) the clash is not added and moreover, a is */ /* made a copy of b. */ /* This is still not perfect, even given its strictly local nature. */ /* for example in k = i; j = f(k); (k now dead) i = new value */ /* it cannot detect that k need not clash with i (indeed, k can be a */ /* slave of i) */ static uint32 current_value_number; static uint32 max_value_number; struct ValnRegList { ValnRegList *cdr; VRegnum rno; uint32 wc; }; #define rno_(rl) ((rl)->rno) #define wc_(rl) ((rl)->wc) #define ValnRegList_DiscardOne(l) ((ValnRegList *)discard3(l)) #define VALNSEGBITS 9 #define VALNSEGSIZE (1<<VALNSEGBITS) #define VALNSEGMAX 64 static ValnRegList **valn_index[VALNSEGMAX]; #define valn_list_(n) (valn_index[(n)>>VALNSEGBITS])[(n)&(VALNSEGSIZE-1)] static void init_value_number(int n) { current_value_number = n; } static void init_valn_seg(uint32 n) { ValnRegList **newv = (ValnRegList **)SynAlloc(VALNSEGSIZE * sizeof(ValnRegList *)); uint32 i; for (i = 0; i < VALNSEGSIZE; i++) newv[i] = NULL; valn_index[n>>VALNSEGBITS] = newv; } static void valn_reinit(void) { current_value_number = max_value_number = 0; init_valn_seg(0); } static uint32 new_valnr(void) { uint32 n = ++current_value_number; if (n > max_value_number) { max_value_number = n; if ((n & (VALNSEGSIZE-1)) == 0) init_valn_seg(n); } valn_list_(n) = NULL; return n; } static ValnRegList *MkValnRegList(ValnRegList *l, VRegnum r, uint32 wc) { ValnRegList *res = (ValnRegList *)SynAlloc(sizeof(ValnRegList)); cdr_(res) = l; rno_(res) = r; wc_(res) = wc; return res; } static ValnRegList *ValnRegList_Discard(ValnRegList *p) { while (p != NULL) p = ValnRegList_DiscardOne(p); return NULL; } static ValnRegList *ValnRegList_Copy(ValnRegList *p) { ValnRegList *res = NULL; for (; p != NULL; p = cdr_(p)) res = MkValnRegList(res, rno_(p), wc_(p)); return res; } static ValnRegList *ValnRegList_NDelete(VRegnum a, ValnRegList *l) { ValnRegList *r = l, *s; if (l == NULL) return l; else if (rno_(l) == a) return (ValnRegList *)discard3(l); do { s = l; l = cdr_(l); if (l == NULL) return r; } while (rno_(l) != a); cdr_(s) = (ValnRegList *)discard3(l); return r; } static void write_valnr(VRegnum dst, uint32 newvaln) { uint32 oldvaln = val_(valnr_(dst)); if (newvaln == VALN_UNSET) { /* This is unfortunately necessary because there's no way to mark */ /* instructions which are going to be killed, but the registers */ /* they read won't be seen as imports to a block (so will still be*/ /* marked unset). */ newvaln = new_valnr(); } if (oldvaln == VALN_UNSET) { valsource_(dst) = ValnRegList_Copy(valn_list_(val_(newvaln))); } else { valn_list_(oldvaln) = ValnRegList_NDelete(dst, valn_list_(oldvaln)); valsource_(dst) = ValnRegList_Discard(valsource_(dst)); newvaln |= VALN_MULTIPLE; } valn_list_(val_(newvaln)) = MkValnRegList(valn_list_(val_(newvaln)), dst, ++valwritecount_(dst)); valnr_(dst) = newvaln; if (debugging(DEBUG_REGS)) cc_msg("%ld - %ld%s\n", dst, newvaln & ~VALN_MULTIPLE, newvaln & VALN_MULTIPLE ? "!" : ""); } #define copy_valnr(dst, src) write_valnr((dst), val_(valnr_(src))) #define set_valnr(dst) write_valnr((dst), new_valnr()) static void check_valnr_slave(VRegnum r) { if (is_real_valn_(r)) { ValnRegList *p, **prevp = &valsource_(r); while ((p = *prevp) != NULL) if (val_(valnr_(r)) != val_(valnr_(rno_(p))) || (valnr_(rno_(p)) & VALN_DEAD) || wc_(p) != valwritecount_(rno_(p))) *prevp = ValnRegList_DiscardOne(p); else { if (debugging(DEBUG_REGS)) cc_msg("valn_slave %ld %ld\n", r, rno_(p)); valnr_(r) |= VALN_SLAVE; prevp = &cdr_(p); } valnr_(r) |= VALN_DEAD; } } static void set_valnr_f1(RealRegister r) { set_valnr(r); } static void set_valnr_f2(RealRegister r, RealRegSet_MapArg *a) { IGNORE(a); set_valnr(r); } static void init_value_numbers(BlockHead *b) { uint32 n, r; for (n = 0; n < max_value_number; n++) valn_list_(n) = ValnRegList_Discard(valn_list_(n)); /* Mark all registers as 'not yet written' ... */ init_value_number(VALN_REAL); for (r = 0; r < vregistername; r++) { valnr_(r) = VALN_UNSET; valsource_(r) = ValnRegList_Discard(valsource_(r)); valwritecount_(r) = 0; } /* ... except those used by the block, which acquire new value */ /* numbers now ... */ vregset_map1(blkuse_(b), set_valnr_f1); } static void instruction_copy_info(const Icode *ic) { const int32 op = ic->op & J_TABLE_BITS; switch (op) { case J_INIT: case J_INITF: case J_INITD: break; case J_MOVR: case J_MOVFR: case J_MOVDR: #ifdef TARGET_IS_ARM case J_MOVFDR: #endif copy_valnr(ic->r1.r, ic->r3.r); break; case J_LDRV: case J_LDRFV: case J_LDRDV: if (bindxx_(ic->r3.b) != GAP) copy_valnr(ic->r1.r, bindxx_(ic->r3.b)); else set_valnr(ic->r1.r); break; case J_STRV: case J_STRFV: case J_STRDV: if (bindxx_(ic->r3.b) != GAP) copy_valnr(bindxx_(ic->r3.b), ic->r1.r); break; case J_ADCON: case J_ADCONV: case J_ADCONF: case J_ADCOND: case J_MOVK: if (ic->r2.r != GAP) copy_valnr(ic->r1.r, ic->r2.r); else set_valnr(ic->r1.r); break; default: { RealRegUse reg; RealRegSet corrupt; RealRegisterUse(ic, &reg); map_RealRegSet(&reg.def, set_valnr_f2, NULL); difference_RealRegSet(&corrupt, &reg.c_in, &reg.def); union_RealRegSet(&corrupt, &reg.c_out, &corrupt); map_RealRegSet(&corrupt, set_valnr_f2, NULL); if (loads_r1(op) || corrupts_r1(ic)) set_valnr(ic->r1.r); if (loads_r2(op) || corrupts_r2(ic)) set_valnr(ic->r2.r); } } if (ic->op & J_DEAD_R1) check_valnr_slave(ic->r1.r); if (ic->op & J_DEAD_R2) check_valnr_slave(ic->r2.r); if (ic->op & J_DEAD_R3) { if (uses_stack(op)) check_valnr_slave(bindxx_(ic->r3.b)); else check_valnr_slave(ic->r3.r); } if (ic->op & J_DEAD_R4) check_valnr_slave(ic->r4.r); } static VRegSetP instruction_ref_info(VRegSetP s1, Icode const *const ic, uint32 *exact, int demand) { const int32 op = ic->op & J_TABLE_BITS; int32 dataflow = 0; /* 'exact' is non-0 for the final pass when exact dataflow info is required */ /* It is convenient to arrange it to be a pointer to where J_DEAD_Rx is put */ /* Note that 'op' here has been masked with J_TABLE_BITS. */ if (isproccall_(op)) /* global register variables are live at any call */ s1 = live_union(s1, globalregvarset, &listallocrec); if (reads_r2(op) || (pseudo_reads_r2(op) && ic->r2.r!=GAP)) /* MOVK/ADCON loopopt */ { bool alreadylive; s1 = reference_register(ic->r2.r, reg_bitsrefd(ic,demand,2), s1, &alreadylive); if (exact && !alreadylive) dataflow |= J_DEAD_R2; } if (reads_r3(op)) { bool alreadylive; s1 = reference_register(ic->r3.r, reg_bitsrefd(ic, demand, 3), s1, &alreadylive); if (exact && !alreadylive) dataflow |= J_DEAD_R3; } else if (loads_r1(op) && uses_stack(op) && op != J_ADCONV) { VRegnum r = bindxx_(ic->r3.b); if (r != GAP) { bool alreadylive; s1 = reference_register(r, reg_bitsrefd(ic,demand,3), s1, &alreadylive); if (exact && !alreadylive) dataflow |= J_DEAD_R3; } } if (reads_r4(op)) { bool alreadylive; s1 = reference_register(ic->r4.r, reg_bitsrefd(ic,demand,4), s1, &alreadylive); if (exact && !alreadylive) dataflow |= J_DEAD_R4; } if (reads_r1(op) || (pseudo_reads_r1(op) && ic->r1.r!=GAP)) /* CMPK loopopt */ { bool alreadylive; s1 = reference_register(ic->r1.r, reg_bitsrefd(ic,demand,1), s1, &alreadylive); if (exact && !alreadylive) dataflow |= J_DEAD_R1; } if (reads_psr(ic)) { s1 = reference_register(R_PSR, ALLBITS, s1, NULL); } if (exact) { *exact = (*exact & ~J_DEADBITS) | dataflow; } return s1; } VRegSetP exitregset(VRegnum result, VRegSetP s) { /* return registers which are alive on function exit */ int32 n; s = live_union(s, globalregvarset, &listallocrec); if (result != GAP) { s = reference_register(result, ALLBITS, s, NULL); for (n = 1; n < currentfunction.nresultregs; n++) s = reference_register(result + n, ALLBITS, s, NULL); } if (pcs_flags & PCS_NOFP) s = reference_register(R_SP, ALLBITS, s, NULL); /* SP or FP alive on exit */ else s = reference_register(R_FP, ALLBITS, s, NULL); if (!(pcs_flags & PCS_NOSTACKCHECK)) s = reference_register(R_SL, ALLBITS, s, NULL); /* SL alive if stackchecking */ if (pcs_flags & PCS_REENTRANT) s = reference_register(R_SB, ALLBITS, s, NULL); /* SB alive if reentrant */ return s; } static VRegSetP extra_regs(VRegSetP s, LabelNumber *q) /* update the list s to reflect things needed by the block with label q. */ /* Note that q can have one of the special values RetIntLab, RetFloatLab */ /* or RetVoidLab (for exit labels). New RetImplLab. */ /* This procedure is applied repeatedly to all blocks in the flowgraph */ /* to find definitive information about what registers are used by which */ /* blocks. */ { /* local to successor_regs() */ if (q == RetIntLab) return exitregset(V_Presultreg(INTREG), s); else if (q == RetDbleLab) return exitregset(V_Presultreg(DBLREG), s); else if (q == RetFloatLab) return exitregset(V_Presultreg(FLTREG), s); else if (q == RetVoidLab || q == RetImplLab) return exitregset(GAP, s); else return live_union(s, blkuse_(q->block), &listallocrec); } static VRegSetP successor_regs(BlockHead *p) { /* local to collect_register_clashes and update_block_use_info */ /* Produce a list of the registers required at the end of block p */ /* This is done by merging the blkuse_() information from all succesor */ /* blocks. */ VRegSetP s1 = NULL; memclr(reg_lsbusetab, (size_t)vregistername); #ifdef LSBUSE_CONSISTENCY_CHECK memclr(lsbmap, (size_t)(vregistername/(LSBQUANTUM*8))+1); #endif if (blkflags_(p) & BLKSWITCH) { LabelNumber **v = blktable_(p); int32 i, n = blktabsize_(p); for (i=0; i<n; i++) s1 = extra_regs(s1, v[i]); } else { s1 = extra_regs(s1, blknext_(p)); if (blkflags_(p) & BLK2EXIT) s1 = extra_regs(s1, blknext1_(p)); } if (debugging(DEBUG_REGS)) live_print("succ regs"); return s1; } static VRegSetP live_deleteresults(VRegInt r2, VRegSetP s1, bool *livep) { int32 n = k_resultregs_(r2.i); bool live = NO; for (; --n >= 0;) { bool live2; s1 = live_delete(R_A1+n, s1, &live2); live |= live2; } *livep = live; return s1; } static void use_f(RealRegister r, RealRegSet_MapArg * a) { a->vr = reference_register(r, ALLBITS, a->vr, NULL); } static void def_f(RealRegister r, RealRegSet_MapArg * a) { a->vr = live_delete(r, a->vr, NULL); } static VRegSetP add_instruction_info(VRegSetP s1, Icode *ic, uint32 *deadp, bool removed) { bool live_r1, live_r2, live_psr = NO; J_OPCODE op = ic->op & J_TABLE_BITS; if (sets_psr(ic)) s1 = live_delete(R_PSR, s1, &live_psr); if (loads_r2(op) && loads_r1(op) && !removed) { /* more code needed for (1) 'removed' and (2) SHARES_INT_AND_FP */ s1 = live_delete(ic->r2.r, s1, &live_r2); s1 = live_delete(ic->r1.r, s1, &live_r1); if (!live_r1 && !live_r2 && !live_psr && !has_side_effects(ic)) { if (debugging(DEBUG_REGS)) print_xjopcode(ic, "-> NOOP loads r1&r2 (a)"); ic = &ic_noop, op = J_NOOP; } } else if (loads_r2(op) && !removed) { s1 = live_delete(ic->r2.r, s1, &live_r2); if (!live_r2 && !live_psr && !has_side_effects(ic)) { if (debugging(DEBUG_REGS)) print_xjopcode(ic, "-> NOOP loads r2 (a)"); ic = &ic_noop, op = J_NOOP; } } else if (loads_r1(op) && !removed) { bool live_results; if ( iscalln_(op, ic->r2.i) && (s1 = live_deleteresults(ic->r2, s1, &live_results), live_results)) /*nothing*/; else #ifdef TARGET_SHARES_INTEGER_AND_FP_REGISTERS if ((J_fltisdouble(op) && isany_realreg_(ic->r1.r) ? s1 = live_delete(other_halfreg(ic->r1.r), s1, NULL) : NULL), s1 = live_delete(ic->r1.r, s1, &live_r1), live_r1) /*nothing*/; #else if (s1 = live_delete(ic->r1.r, s1, &live_r1), live_r1) /*nothing*/; #endif else if (usrdbg(DBG_VAR+DBG_LINE) && !usrdbg(DBG_OPT_REG)) /*nothing*/; /* leave unused code alone if debugging */ else if (op == J_CALLK) /* I suppose this should really be just calls with K_PURE */ { if (ic->r3.b == exb_(arg1_(sim.mulfn))) /* ignore mult if result seems (so far) unwanted */ ic = &ic_noop, op = J_NOOP; else if (ic->r3.b == exb_(arg1_(sim.divfn)) || ic->r3.b == exb_(arg1_(sim.udivfn)) || ic->r3.b == exb_(arg1_(sim.remfn)) || ic->r3.b == exb_(arg1_(sim.uremfn))) { /* a division where the result is not needed can be treated as a one-arg */ /* function call. */ Icode icnew = *ic; icnew.r2.i = k_argdesc_(1, 0, 1,0,0,0); ic = &icnew; } } else if (op == J_OPSYSK || op == J_CALLR) /*nothing*/; else if (!live_psr && !has_side_effects(ic)) { /* we had better not treat a voided fn as dead code */ if (debugging(DEBUG_REGS)) print_xjopcode(ic, "-> NOOP loads r1 (a)"); ic = &ic_noop, op = J_NOOP; } } if (uses_stack(op) && op!=J_ADCONV) { VRegnum r3 = bindxx_(ic->r3.b); /* usage information is accumulated for the virtual register that I will */ /* use if I manage to map this stack location onto a register. */ if (r3 != GAP) { bool live_r3; if (loads_r1(op)) { /* Now handled by instruction_ref_info() */ /* this else case is really J_STRV/STRDV/STRFV */ } else if (vregset_member(r3, globalregvarset) || (s1 = live_delete(r3, s1, &live_r3), live_r3)) { /* nothing */ } else if ((bindstg_(ic->r3.b) & (b_addrof|b_spilt)) == 0 && (!usrdbg(DBG_VAR+DBG_LINE) || usrdbg(DBG_OPT_REG))) { if (debugging(DEBUG_REGS)) print_xjopcode(ic, "-> NOOP store %ld (a)", (long)r3); ic = &ic_noop, op = J_NOOP; } } } #ifdef TARGET_IS_ARM_OR_THUMB { RealRegUse reg; RealRegSet_MapArg a; a.vr = s1; RealRegisterUse(ic, &reg); if (nonempty_RealRegSet(&reg.def, INTREG)) map_RealRegSet(&reg.def, def_f, &a); if (nonempty_RealRegSet(&reg.use, INTREG)) map_RealRegSet(&reg.use, use_f, &a); s1 = a.vr; /* copy altered set back! */ } #endif return instruction_ref_info(s1, ic, deadp, ALLBITS); } static bool update_block_use_info(BlockHead *p) /* scan a basic block backwards recording information about which */ /* virtual registers will be needed at the start of the block. */ { VRegSetP s1 = successor_regs(p); Icode *const q = blkcode_(p); int32 w; /* Now scan this block backwards to see what is needed at its head. */ if (blkflags_(p) & BLK2EXIT) s1 = reference_register(R_PSR, ALLBITS, s1, NULL); for (w=blklength_(p)-1; w>=0; w--) s1 = add_instruction_info(s1, &q[w], &q[w].op, 0); { VRegSetP s2 = blkuse_(p); bool same = vregset_equal(s1, s2); vregset_discard(s2); blkuse_(p) = s1; #ifndef TARGET_IS_NULL if (debugging(DEBUG_REGS)) { cc_msg("Block %ld uses: ", (long)lab_name_(blklab_(p))); vregset_print(s1); cc_msg("\n"); } #endif #ifdef LSBUSE_CONSISTENCY_CHECK /* REGALLOC_CHAR_OPTIMISER */ { /* lets do a consistency check on the new code. */ uint32 i; if (debugging(DEBUG_REGS)) live_print("block regs"); for (i = 0, s2 = NULL; i < vregistername; i += LSBQUANTUM) if (lsbmap_(i)) { int32 j, max = i+LSBQUANTUM < vregistername ? i+LSBQUANTUM : vregistername; for (j = i; j < max; j++) if (reg_lsbusetab[j]) s2 = vregset_insert(j, s2, NULL, &listallocrec); } if (!vregset_equal(s1, s2)) syserr(syserr_liveness); vregset_discard(s2); } #endif return !same; } } static void increment_refcount(VRegnum n, BlockHead *p) { if (n != GAP) vreg_(n)->refcount += (8L << blknest_(p)); } static bool liveresult(VRegnum r2, VRegSetP s1) { int32 n = k_resultregs_(r2); for (; --n >= 0;) if (live_member(R_A1result+n, s1)) return YES; return NO; } static VRegSetP set_result_registers(VRegnum r2, VRegSetP s1) { int32 n = k_resultregs_(r2); for (; --n >= 0;) s1 = set_register(R_A1+n, s1); return s1; } static void crc_f1(RealRegister r, RealRegSet_MapArg *a) { corrupt_physical_register(r, a->vr); } static void use_f_reg(RealRegister r, RealRegSet_MapArg * a) { a->vr = reference_register(r, ALLBITS, a->vr, NULL); } static void def_f_reg(RealRegister r, RealRegSet_MapArg *a) { a->vr = set_register(r, a->vr); } static void clash_f_reg(RealRegister r, RealRegSet_MapArg *a) { if (r != a->r) add_clash(r, a->r); } static void collect_register_clashes(BlockHead *p) /* Called after block register use info has converged. (!pass1) */ /* scan a basic block backwards recording information about which */ /* virtual registers clash with each other. */ /* Essentially a souped-up version of update_block_use_info (merge?) */ { VRegSetP s1 = successor_regs(p); Icode *const q = blkcode_(p); int32 w; #ifdef TARGET_IS_ARM_OR_THUMB RealRegUse reg; #endif thisBlocksBindList = blkstack_(p); if (usrdbg(DBG_VAR) && !usrdbg(DBG_OPT_REG)) { /* if we are generating debug data, cause all binders with extent that */ /* includes this block to clash with all others. */ BindList *bl = blkstack_(p); for ( ; bl!=NULL ; bl = bl->bindlistcdr ) { Binder *b = bl->bindlistcar; VRegnum r = bindxx_(b); if (r!=GAP) makebindersclash(r, bl->bindlistcdr, GAP); } } if (blkflags_(p) & BLK2EXIT) s1 = reference_register(R_PSR, ALLBITS, s1, NULL); /* Do the value numbering pass - initialize all global registers */ init_value_number(VALN_REAL); init_value_numbers(p); for (w = 0; w <blklength_(p); w++) instruction_copy_info(&q[w]); for (w=blklength_(p)-1; w>=0; w--) { Icode *const ic = &q[w]; int32 op = ic->op & J_TABLE_BITS; int demand = ALLBITS; bool live_psr = NO; /* Obviously, if TARGET_SHARES_INTEGER_AND_FP_REGISTERS then J_MOVDIR */ /* could make some optimisations... */ #ifdef TARGET_IS_ARM_OR_THUMB RealRegisterUse(ic, &reg); if (nonempty_RealRegSet(&reg.c_out, INTREG)) { RealRegSet_MapArg a; a.vr = s1; map_RealRegSet(&reg.c_out, crc_f1, &a); } #endif if (sets_psr(ic)) s1 = live_delete(R_PSR, s1, &live_psr); if (updates_r2(op) && !live_member(ic->r2.r, s1)) remove_writeback(ic); if (updates_r1(op) && !live_member(ic->r1.r, s1)) remove_writeback(ic); op = ic->op & J_TABLE_BITS; if (loads_r2(op) && loads_r1(op)) { /* assumes 'loads_r2' ops demand ALLREGS... */ if (!live_member(ic->r2.r, s1) && !live_member(ic->r1.r, s1) && !live_psr && !has_side_effects(ic)) { if (debugging(DEBUG_REGS)) print_xjopcode(ic, "-> NOOP loads r1&r2"); INIT_IC (*ic, J_NOOP); op = J_NOOP; } else { s1 = set_register(ic->r2.r, s1); s1 = set_register(ic->r1.r, s1); add_clash(ic->r1.r, ic->r2.r); } } else if (loads_r2(op)) { if (!live_member(ic->r2.r, s1) && !live_psr && !has_side_effects(ic)) { if (debugging(DEBUG_REGS)) print_xjopcode(ic, "-> NOOP loads r2"); INIT_IC (*ic, J_NOOP); op = J_NOOP; } else s1 = set_register(ic->r2.r, s1); } else if (loads_r1(op)) /* /* Unreconstructed WRT sharing TARGET_SHARES_INTEGER_AND_FP_REGISTERS */ { if (live_member(ic->r1.r, s1)) { demand = reg_demand(ic->r1.r); /* amazing things happen here because MOV r1, r2 does not want to cause */ /* r1 and r2 to clash - indeed the very opposite is true. */ if (op==J_MOVR || op==J_MOVFR || op==J_MOVDR #ifdef TARGET_IS_ARM || op==J_MOVFDR #endif ) s1 = set_register_copy(ic->r1.r, s1, ic->r3.r); else if ((op==J_LDRV || op==J_LDRFV || op==J_LDRDV) && bindxx_(ic->r3.b) != GAP) { s1 = set_register_copy(ic->r1.r, s1, bindxx_(ic->r3.b)); } else if (pseudo_reads_r2(op) && ic->r2.r!=GAP) s1 = set_register_slave(ic->r1.r, s1, ic->r2.r); #ifdef REGALLOC_CHAR_OPTIMISER else if ((uint32)ic->r1.r < vregistername && ( (op == J_EXTEND && extend_bitsused(ic->r3.r) >= reg_lsbusetab[ic->r1.r]) || (op == J_ANDK && spaceofmask(ic->r3.r) >= reg_lsbusetab[ic->r1.r] && just32bits_(ic->r3.r) == (1L<<spaceofmask(ic->r3.r))-1))) { ic->op = op = J_MOVR; ic->r3.r = ic->r2.r; ic->r2.r = GAP; s1 = set_register_copy(ic->r1.r, s1, ic->r3.r); if (debugging(DEBUG_REGS)) live_print("EXTEND/ANDK => MOVR"); } #endif else { /* it is not clear that J_INIT should set_register(r1) */ if (op == J_INIT || op == J_INITF || op == J_INITD) if ((feature & FEATURE_ANOMALY) && ic->r3.b != 0 && /* For binders generated by range splitting, there has already been a warning (with a sensible name) */ !(bindstg_(ic->r3.b) & b_pseudonym)) cc_warn(regalloc_warn_use_before_set, ic->r3.b); #ifdef REGALLOC_CHAR_OPTIMISER if ((uint32)ic->r1.r < vregistername && reg_lsbusetab[ic->r1.r] <= 8) switch (op) { case J_LDRBK: case J_LDRBR: case J_LDRBV: case J_LDRBVK: ic->op &= ~(J_SIGNED|J_UNSIGNED); if (debugging(DEBUG_REGS)) live_print("plain LDRBx"); } if ((uint32)ic->r1.r < vregistername && reg_lsbusetab[ic->r1.r] <= 16) switch (op) { case J_LDRWK: case J_LDRWR: case J_LDRWV: case J_LDRWVK: ic->op &= ~(J_SIGNED|J_UNSIGNED); if (debugging(DEBUG_REGS)) live_print("plain LDRWx"); } #endif if (iscalln_(op, ic->r2.r)) s1 = set_result_registers(ic->r2.r, s1); else s1 = set_register(ic->r1.r, s1); } } else if (usrdbg(DBG_VAR) && !usrdbg(DBG_OPT_REG)) s1 = set_register(ic->r1.r, s1); else if (iscalln_(op, ic->r2.r) && liveresult(ic->r2.r, s1)) s1 = set_result_registers(ic->r2.r, s1); else { /* This load seems to be unnecessary */ /* NB loading of volatile values will be protected by the jopcodes J_USE */ /* and friends which make it seem that the value loaded is used even */ /* if it isn't. */ if (op == J_CALLK || op == J_OPSYSK) { if ((ic->r2.i & K_PURE) && op != J_OPSYSK) { if (ic->r3.b == exb_(arg1_(sim.divfn)) || ic->r3.b == exb_(arg1_(sim.udivfn)) || ic->r3.b == exb_(arg1_(sim.remfn)) || ic->r3.b == exb_(arg1_(sim.uremfn))) { if (debugging(DEBUG_REGS)) cc_msg("void a divide\n"); ic->r2.i = k_argdesc_(1, 0, 1,0,0,0); /* Reduce to one arg */ ic->r3.i = (IPtr)arg1_(sim.divtestfn); } else { if (debugging(DEBUG_REGS)) cc_msg("void call to $b\n", ic->r3.b); INIT_IC (*ic, J_NOOP); op = J_NOOP; } } else s1 = set_register(ic->r1.r, s1); /* cannot remove a call */ } else if (op == J_CALLR) s1 = set_register(ic->r1.r, s1); /* cannot remove this call */ else if (!live_psr && !has_side_effects(ic)) /* cannot remove instr which alters a live PSR */ { if (debugging(DEBUG_REGS)) print_xjopcode(ic, "-> NOOP loads r1"); INIT_IC (*ic, J_NOOP); op = J_NOOP; } else s1 = set_register(ic->r1.r, s1); } } if (uses_stack(op) && op!=J_ADCONV) { VRegnum r3 = bindxx_(ic->r3.b); /* usage information is accumulated for the virtual register that I will */ /* use if I manage to map this stack location onto a register. */ if (r3 != GAP) { if (loads_r1(op)) { /* This case now handed by instruction_ref_info() */ } else { /* this else case is really J_STRV/STRDV/STRFV */ if (live_member(r3, s1) || (usrdbg(DBG_VAR+DBG_LINE) && !usrdbg(DBG_OPT_REG))) { demand = reg_demand(r3); s1 = set_register_copy(r3, s1, ic->r1.r); } else if (bindstg_(ic->r3.b) & (b_addrof|b_spilt)) syserr(syserr_dataflow); else { /* spurious store -- var not live. Kill to NOOP. */ #ifdef EXPERIMENTAL_DATAFLOW /* The following code is foiled (generates warnings from sensible code) */ /* by an action of the optimiser earlier. (See 'justregister'). Consider */ /* f() { int x = 1; return x;}. This generates JOPCODE like */ /* MOVK r,1; STRV r,x; MOVR a1,r which reuses r instead of re-using x */ /* Possible solution, use the LDRV r2 field to indicate plausible reg? */ /* Note that I consider the warning required in f() { int x; return x=1;} */ if (feature & FEATURE_ANOMALY) cc_warn(regalloc_warn_never_used, ic->r3.b); #endif if (debugging(DEBUG_REGS)) print_xjopcode(ic, "-> NOOP stored %ld", (long)r3); INIT_IC (*ic, J_NOOP); op = J_NOOP; } } } } if (uses_r1(op)) increment_refcount(ic->r1.r, p); if (uses_r2(op)) increment_refcount(ic->r2.r, p); if (uses_stack(op)) { VRegnum n = bindxx_(ic->r3.b); increment_refcount(n, p); if (n != GAP) vreg_(n)->refcount |= 1L; /* mark as 'real', rather than */ } /* as a re-evaluable CSE binder.*/ else if (uses_r3(op)) increment_refcount(ic->r3.r, p); if (uses_r4(op)) increment_refcount(ic->r4.r, p); if (corrupts_r1(ic)) corrupt_register(ic->r1.r, s1); if (corrupts_r2(ic)) corrupt_register(ic->r2.r, s1); if (corrupts_psr(ic)) corrupt_register(R_PSR, s1); /* let's rationalise the below someday. */ #ifdef TARGET_IS_ARM_OR_THUMB if (op == J_MULR || op == J_MLAR) add_clash(ic->r1.r, ic->r3.r); if (op == J_MULL || op == J_MLAL) { add_clash(ic->r1.r, ic->r2.r); add_clash(ic->r1.r, ic->r3.r); add_clash(ic->r2.r, ic->r3.r); } #ifdef ARM_INLINE_ASSEMBLER if (op == J_SWP || op == J_SWPB) { add_clash(ic->r1.r, ic->r3.r); add_clash(ic->r2.r, ic->r3.r); } else if (op == J_LDMW) { /* all registers in the registerlist clash with the base */ RealRegSet_MapArg a; a.r = ic->r1.r; map_RealRegSet(&reg.def, clash_f_reg, &a); } #endif #endif #ifdef TARGET_HAS_2ADDRESS_CODE # ifdef AVOID_THE_ACN_ADJUSTMENT_MADE_HERE if (jop_asymdiadr_(op) && ic->r2.r != ic->r3.r) add_clash(ic->r1.r, ic->r3.r); # else /* See the comment in flowgraf.c (line 99) for why I think this test wants to be like this and why the previous version was wrong. Note also that any test on register equality here is pretty suspect since it tests virtual registers not real ones - thus (and especially given that SUBR seems to be used but rarely) I might prefer a test just on jop_asymdiadr(op). */ if (ic->r1.r != ic->r2.r) { if (jop_asymdiadr_(op) && two_address_code(op) && ic->r1.r != ic->r3.r) add_clash(ic->r1.r, ic->r3.r); #ifdef NEVER /* WD: under investigation... */ if ((j_is_diadr(op) || j_is_diadk(op)) && (op != J_ADDR && op != J_SUBR && op != J_CMPR && op != J_CMPK) ) /* WD: diadr/k BROKEN - includes CMP MOV etc, which have GAPs */ if (ic->r1.r != GAP && ic->r2.r != GAP) add_copy(ic->r1.r, ic->r2.r); #endif } # endif #endif #ifdef TARGET_IS_ARM_OR_THUMB { RealRegUse reg; RealRegSet_MapArg a; a.vr = s1; RealRegisterUse(ic, &reg); if (nonempty_RealRegSet(&reg.def, INTREG)) map_RealRegSet(&reg.def, def_f_reg, &a); if (nonempty_RealRegSet(&reg.use, INTREG)) map_RealRegSet(&reg.use, use_f_reg, &a); s1 = a.vr; /* copy altered set back! */ } #endif s1 = instruction_ref_info(s1, ic, NULL, demand); /* The following things that allow for workspace registers MUST be done */ /* here after other register-use info for the instruction has been dealt */ /* with. Again, this needs parameterising instead of #ifdef. */ #ifdef TARGET_IS_ARM_OR_THUMB if (op == J_CALLK || op == J_CALLR) { /* WD: Very nasty hack!!! This causes regmaskvec to be incorrect for * calls. The idea is that if a call gets turned into a tailcall * the tailcall doesn't seem to save LR. */ reg.c_in.map[0] &= ~regbit(R_LR); corrupt_register(R_LR, s1); } if (nonempty_RealRegSet(&reg.c_in, INTREG)) { RealRegSet_MapArg a; a.vr = s1; map_RealRegSet(&reg.c_in, crc_f1, &a); } #endif } vregset_discard(s1); if (debugging(DEBUG_REGS)) cc_msg("Scanned block %ld\n", (long)lab_name_(blklab_(p))); } /* end of ban on vregset direct operations. */ #ifndef TARGET_IS_NULL typedef struct { VRegnum vreg; RealRegister rreg; Icode *icode; int32 mask; } UDFRec; static void udf_cb(VRegnum r, VoidStar arg) { UDFRec *udf = (UDFRec *) arg; if (r != udf->vreg && register_number(r) == udf->rreg) udf->icode->op &= udf->mask; } /* The reason for update_deadflags() is that the DEADBITS information */ /* for virtual registers is a superset of that for physical registers -- */ /* consider examples like */ /* extern int z; void f(x) { while (x) z=1; while (x) z=1; } */ /* Since the mapping from virtual register (with clashes) to physical */ /* register graphs (with inequality) is a homomorphism one would expect */ /* some nice theory to cover it. Note that the property of deadness is */ /* not preserved by the homomorphism, but it IS semi-preserved. */ /* So the code removes the DEAD infomation from any register which */ /* has a another live register mapped to the same physical register. */ /* AM is not sure that the tests below of ->realreg!=0 are really */ /* required, but they look harmless. */ static void update_deadflags(BlockHead *p) { VRegSetP s = successor_regs(p); Icode *q = blkcode_(p); int32 w; UDFRec udf; for (w=blklength_(p)-1; w>=0; w--) { Icode *const ic = &q[w]; int32 op = ic->op & J_TABLE_BITS; /* The following three lines take care of the fact that we really want */ /* ^^^^^ i.e. to the vregset_delete() call? */ /* to execute this code half-way through add_instruction_info(). */ /* This code ensures that we do not remove deadflags from r2 for (say) */ /* LDRK r1,r2,0 if r1 and r2 map to the same physical register (and */ /* of course r2 is dead at the virtual level). */ /* WGD's 32000 code depends on this as he was entitled to from the */ /* Nov87 comment above. Whether we ought to reconsider this is another */ /* matter. Discuss with WGD one day. */ bool removed = 0; if (debugging(DEBUG_LOOP)) { cc_msg("live"); vregset_print(s), cc_msg("\n %c%c%c%c", (ic->op & J_DEAD_R1 ? '1': '-'), (ic->op & J_DEAD_R2 ? '2': '-'), (ic->op & J_DEAD_R3 ? '3': '-'), (ic->op & J_DEAD_R4 ? '4': '-')); print_jopcode(ic); } udf.icode = ic; if (loads_r1(op) || corrupts_r1(ic)) s = vregset_delete(ic->r1.r, s, &removed); if (loads_r2(op) || corrupts_r2(ic)) { bool removed1 = 0; s = vregset_delete(ic->r2.r, s, &removed1); removed = removed || removed1; } if ((ic->op & J_DEAD_R2) && (reads_r2(op) || (pseudo_reads_r2(op) && ic->r2.r!=GAP))) /* MOVK/ADCON loopopt */ { RealRegister rr = register_number(ic->r2.r); if (debugging(DEBUG_LOOP)) cc_msg("try remove dead_r2 %ld %ld", (long)ic->r2.r, (long)rr); if (rr >= 0) { udf.vreg = ic->r2.r; udf.rreg = rr; udf.mask = ~J_DEAD_R2; vregset_map(s, udf_cb, (VoidStar)&udf); } if (debugging(DEBUG_LOOP)) cc_msg("%s", udf.icode->op & J_DEAD_R2 ? "\n": ": removed\n"); } if ((ic->op & J_DEAD_R3) && reads_r3(op) /* && op != J_CALLR*/) /* see above */ { RealRegister rr = register_number(ic->r3.r); if (debugging(DEBUG_LOOP)) cc_msg("try remove dead_r3 %ld %ld ", (long)ic->r3.r, (long)rr); if (rr >= 0) { udf.vreg = ic->r3.r; udf.rreg = rr; udf.mask = ~J_DEAD_R3; vregset_map(s, udf_cb, (VoidStar)&udf); } if (debugging(DEBUG_LOOP)) cc_msg("%s", udf.icode->op & J_DEAD_R3 ? "\n": ": removed\n"); } /* This can only be a LDRV or equivalent (STRV doesn't have DEAD_R3) */ if ((ic->op & J_DEAD_R3) && uses_stack(op) && bindxx_(ic->r3.b) != GAP) { VRegnum r = bindxx_(ic->r3.b); RealRegister rr = register_number(r); if (debugging(DEBUG_LOOP)) cc_msg("try remove dead_r3 %ld %ld ", (long)r, (long)rr); if (rr >= 0) { udf.vreg = bindxx_(ic->r3.b); udf.rreg = rr; udf.mask = ~J_DEAD_R3; vregset_map(s, udf_cb, (VoidStar)&udf); } if (debugging(DEBUG_LOOP)) cc_msg("%s", udf.icode->op & J_DEAD_R3 ? "\n": ": removed\n"); } if ((ic->op & J_DEAD_R4) && reads_r4(op)) { RealRegister rr = register_number(ic->r4.r); if (debugging(DEBUG_LOOP)) cc_msg("try remove dead_r4 %ld %ld ", (long)ic->r4.r, (long)rr); if (rr >= 0) { udf.vreg = ic->r4.r; udf.rreg = rr; udf.mask = ~J_DEAD_R4; vregset_map(s, udf_cb, (VoidStar)&udf); } if (debugging(DEBUG_LOOP)) cc_msg("%s", udf.icode->op & J_DEAD_R4 ? "\n": ": removed\n"); } if ((ic->op & J_DEAD_R1) && (reads_r1(op) || (pseudo_reads_r1(op) && ic->r1.r!=GAP))) /* CMPK loopopt */ { RealRegister rr = register_number(ic->r1.r); if (debugging(DEBUG_LOOP)) cc_msg("try remove dead_r1 %ld %ld ", (long)ic->r1.r, (long)rr); if (rr >= 0) { udf.vreg = ic->r1.r; udf.rreg = rr; udf.mask = ~J_DEAD_R1; vregset_map(s, udf_cb, (VoidStar)&udf); } if (debugging(DEBUG_LOOP)) cc_msg("%s", udf.icode->op & J_DEAD_R1 ? "\n": ": removed\n"); } s = add_instruction_info(s, ic, NULL, removed); } vregset_discard(s); } /*************************************************************************/ /* Here comes the code that allocates and assigns registers */ /*************************************************************************/ static void MaybePrefer(VRegnum vr, void *vprefer) { RealRegSet *prefer = (RealRegSet *)vprefer; RealRegister r1 = register_number(vr); if (isany_realreg_(r1)) augment_RealRegSet(prefer,r1); } static void MaybePrefer2(VRegnum vr, void *vprefer) { RealRegister r1 = register_number(vr); if (!isany_realreg_(r1)) { VRegister *r = vreg_(vr); relation_map(vregname_(r), copymatrix, MaybePrefer, vprefer); } } static void GetPhysicalCopies(VRegnum vr, RealRegSet *copies) { /* return in *copies the set of physical registers which are preferred */ /* allocations for vr (are copied from/to vr and don't clash with it) */ RealRegister r1 = register_number(vr); memclr((void *)copies, sizeof(RealRegSet)); if (isany_realreg_(r1)) augment_RealRegSet(copies, r1); else { VRegister *r = vreg_(vr); relation_map(vregname_(r), copymatrix, MaybePrefer, (void *)copies); vregset_map(r->clashes, clashkillbits_cb, (void *)copies); } } static void avoid_cb(VRegnum vr, void *arg) { RealRegSet *possible = (RealRegSet *)arg; /* Remove from the set *possible the physical registers which we'd */ /* like to allocate to vr (which clashes with the register for which */ /* we're considering *possible for allocation) */ RealRegSet avoid; GetPhysicalCopies(vr, &avoid); if (intersect_RealRegSet(&avoid, &avoid, possible)) { difference_RealRegSet(possible, possible, &avoid); if (debugging(DEBUG_REGS)) { cc_msg("%ld: available {", vr); print_RealRegSet(possible); cc_msg("}\n"); } } } typedef struct { RealRegSet onecopy; RealRegSet *possible; } AvoidRec; static void avoid_cb2(VRegnum vr, void *arg) { AvoidRec *ar = (AvoidRec *)arg; RealRegSet avoid, rs; GetPhysicalCopies(vr, &avoid); intersect_RealRegSet(&avoid, &avoid, ar->possible); if (intersect_RealRegSet(&rs, &avoid, &ar->onecopy)) difference_RealRegSet(ar->possible, ar->possible, &rs); union_RealRegSet(&ar->onecopy, &ar->onecopy, &avoid); } static bool choose_real_register(VRegister *r) /* select a real register to put r into: return 1 on success, 0 on failure */ { RealRegSet m1, m2, prefer; RealRegister r1; RegSort rsort = vregtype_(r); #ifdef ENABLE_SPILL ++choose_count; #endif memclr((VoidStar)&prefer, sizeof(RealRegSet)); relation_map(vregname_(r), copymatrix, MaybePrefer, (VoidStar)&prefer); m1 = *( #ifdef ADDRESS_REG_STUFF rsort == ADDRREG ? (!spillpanic ? &m_addrregs : &m_intregs) : #endif #ifndef TARGET_SHARES_INTEGER_AND_FP_REGISTERS rsort != INTREG ? &m_fltregs : #endif &m_intregs); clashkillbits(&m1, r); /* Test if this register can be allocated at all. */ if (!nonempty_RealRegSet(&m1, rsort)) { if (debugging(DEBUG_REGS) || debugging(DEBUG_SPILL)) { cc_msg("Unable to allocate v%ld(%ld):", (long)vregname_(r), (long)r->heapaddr); if (debugging(DEBUG_REGS)) { cc_msg(" to miss "); printvregclash2(r); cc_msg("\n"); } } r->realreg = R_BOGUS; /* If I fail to allocate a real register to this binder I drop into the */ /* code that spills things. This will choose a register to spill based */ /* on a number of criteria. If possible it will spill either the binder */ /* that failed to get allocated or one of the binders that clashes with */ /* it directly (thus having the best chance of unblocking this particular*/ /* clash). Failing that it will spill some binder that has already been */ /* allocated a real register (ones that have not yet been considered for */ /* allocation would not be sensible to spill, would they?). In this */ /* context it is desirable that the binder that causes the clash should */ /* seem to have a real register allocated to it so that it can be */ /* selected for spilling under this heading. Priority within the above */ /* categories is based on usage information (->refcount) and register */ /* provided by the user. After spilling a binder all binders that have */ /* been given registers so far get reset to a null state (thus undoing */ /* the spurious allocation of R_BOGUS above) so that the entire process */ /* of allocation can be restarted: with some binder marked as spilt it */ /* will generally be possible to proceed further, until at last it */ /* becomes possible to allocate all registers. */ return NO; } #ifdef ADDRESS_REG_STUFF spillpanic = 0; #endif /* If possible allocate r1 so as to remove a copy operation somewhere */ if (intersect_RealRegSet(&m2, &m1, &prefer) && !(var_cc_private_flags & 2048L)) { /* This is somewhat experimental ... */ /* It says: if a preferred allocation for r is also a preferred */ /* allocation for more than one (not-yet-allocated) register which */ /* clashes with r, don't use it for r (since we hope that way to */ /* remove more copies). Since we don't count copy multiplicity, the */ /* code only approximates to the intent. */ AvoidRec ar; memclr((void *)&ar.onecopy, sizeof(RealRegSet)); ar.possible = &m2; vregset_map(r->clashes, avoid_cb2, (void *)&ar); } if (nonempty_RealRegSet(&m2, rsort)) { m1 = m2; } else { if (!(var_cc_private_flags & 4096L)) { /* we are about to make an essentially arbitrary allocation. Try to */ /* avoid doing so in a way that will interfere with an allocation we */ /* know will later be a good idea. */ if (debugging(DEBUG_REGS)) cc_msg("No preferred allocation for %ld\n", vregname_(r)); m2 = m1; vregset_map(r->clashes, avoid_cb, (VoidStar)&m2); memclr((VoidStar)&prefer, sizeof(RealRegSet)); relation_map(vregname_(r), copymatrix, MaybePrefer2, (void *)&prefer); if (intersect_RealRegSet(&prefer, &m2, &prefer)) m1 = prefer; else if (nonempty_RealRegSet(&m2, rsort)) m1 = m2; } } /* Try to allocate avoiding V1 to V<n> (and any floating var regs). */ /* AM (Dec 87) wonders how necessary this is in that ALLOCATION_ORDER */ /* can do this equally as well! */ /* /* The next line needs to ensure that the overlap is an even/odd */ /* pair if TARGET_SHARES_INTEGER_AND_FP_REGISTERS. */ if (intersect_RealRegSet(&m2, &m1, &m_notpreserved)) m1 = m2; /* Convert representation from bit-position to register number. */ { int32 i = 0; for (;; i++) { #ifdef ALLOCATION_ORDER /* a prespecified allocation ordering: */ static unsigned char o[] = ALLOCATION_ORDER; r1 = o[i]; #else /* else choose in a not particularly inspired order. */ r1 = i; #endif if ((uint32)r1 >= (uint32)NMAGICREGS) { syserr(syserr_choose_real_reg, (long)((m1.map)[0])); break; } if (member_RealRegSet(&m1,r1) #ifdef TARGET_SHARES_INTEGER_AND_FP_REGISTERS && (!needsregpair_(rsort) || member_RealRegSet(&m1,other_halfreg(r1))) #endif ) break; } } if (debugging(DEBUG_REGS)) { cc_msg("Now allocate %ld to %ld: miss ", (long)vregname_(r), (long)r1); printvregclash2(r); cc_msg("\n"); } /* Record the allocation. */ r->realreg = r1; /* regmaskvec gets bits set to show what registers this procedure uses. */ if (!member_RealRegSet(&globalregvarvec,r1)) { augment_RealRegSet(&regmaskvec,r1); /* register used */ #ifdef TARGET_SHARES_INTEGER_AND_FP_REGISTERS if (needsregpair_(rsort)) augment_RealRegSet(&regmaskvec, other_halfreg(r1)); #endif } return YES; /* success! */ } static int32 spill_binder(VRegister *rr, BindList *spill_order, VRegSetP *vr) /* Here virtual register rr could not be allocated. Try to pick the */ /* best Binder in spill_order to either spill rr to the stack or to */ /* help the process of allocating rr to a real register. */ { BindList *candidates = NULL; { BindList *lb; for (lb = spill_order; lb != NULL ; lb = lb->bindlistcdr) { Binder *bb = lb->bindlistcar; VRegnum r1n = bindxx_(bb); /* there is no joy in trying to spill a binder if either (a) it was not */ /* a candidate for slaving in a register anyway or (b) the corresponding */ /* register has not yet been scheduled for allocation. */ if (r1n != GAP) { RealRegister r1r = register_number(r1n); if (r1r != R_SCHEDULED) { #ifdef ADDRESS_REG_STUFF /* If we require an address reg and this one is not and we are not */ /* panicking yet -> don't consider this one because it wouldn't do */ /* any good any way. */ /* Maybe the next line should use member(m_addrregs), but AM is */ /* is not sure enough that r1v->realreg is in range. */ if (vregtype_(rr) == ADDRREG && !target_isaddrreg_(r1r) && !spillpanic) continue; #endif candidates = (BindList *) binder_cons2(candidates, bb); } } } } if (candidates==NULL) #ifdef ADDRESS_REG_STUFF { if( !spillpanic ) { spillpanic = 1; return 0; } else syserr(syserr_fail_to_spill, (long)vregname_(rr)); } #else syserr(syserr_fail_to_spill, (long)vregname_(rr)); #endif /* Now find the best binder, with ones that clash directly with the */ /* thing that could not be allocated taking precedence */ { Binder *bb = (Binder *) DUFF_ADDR; VRegister *r1 = (VRegister *) DUFF_ADDR; int32 leastspillcost = INT_MAX; bool foundgood = NO; for (; candidates != NULL; candidates = (BindList *)discard2((List *)candidates)) { Binder *bb2 = candidates->bindlistcar; VRegnum r2n = bindxx_(bb2); /* Presumably we know that r2n != GAP... */ VRegister *r2 = vreg_(r2n); int32 spillcost = r2->refcount; /* This is a good candidate if it was involved in the clash that caused */ /* me to decide that I needed to spill something, or if no such register */ /* was on the list of candidates and this is the one with fewest uses */ if (rr==r2 || vregset_member(r2n, rr->clash2)) { if (!foundgood || spillcost <= leastspillcost) { bb = bb2, r1 = r2, leastspillcost = spillcost; foundgood = YES; } } if (!foundgood && spillcost <= leastspillcost) { bb = bb2, r1 = r2, leastspillcost = spillcost; } } if (debugging(DEBUG_REGS|DEBUG_SPILL)) cc_msg(" spill: $b, v%lu(r%ld:%ld), cost = %lu\n", bb, (long)vregname_(r1), (long)r1->realreg, (long)r1->heapaddr, (long)leastspillcost); r1->realreg = R_SPILT; /* marker for spilled register */ r1->u.spillbinder = bb; *vr = vregset_insert(vregname_(r1), *vr, NULL, &listallocrec); bindxx_(bb) = GAP; /* this one has to stay on the stack */ if (bindstg_(bb) & b_pseudonym) bindsuper_(bb)->spillcount++; #ifdef ENABLE_SPILL if (r1->refcount & 1L) ++n_real_spills; else ++n_cse_spills; spill_cost += leastspillcost; #endif return r1->heapaddr; } } #endif /* TARGET_IS_NULL */ /* exported... */ static void addclashes_rcb(VRegnum n, void *arg) { /* the type of 'r1' is a lie for map-function vregset_map. */ VRegister *v = vreg_(n); VRegnum m = (VRegnum)(IPtr)arg; v->clash2 = vregset_insert(m, v->clash2, NULL, &listallocrec); } static void flattenrelation_cb(VRegnum n, VoidStar arg) { VRegSetP *v = (VRegSetP *)arg; *v = vregset_insert(n, *v, NULL, &clashvallocrec); } void allocate_registers(BindList *spill_order) /* spill_order is a list of all binders active in this function, */ /* ordered with the first-mentioned register variables LAST so that they */ /* are the things least liable to be spilled out to the stack. */ { clock_t t0 = clock(); uint32 i, nn; VRegSetP spillset = NULL; #ifndef TARGET_IS_NULL ReadonlyCopy *p; regalloc_changephase(); clash_reinit(vregistername); /* weight the reference counts of register variables to avoid spills */ { BindList *l = spill_order; Binder *b; while (l != NULL) { b = (Binder *)(l->bindlistcar); if (bindstg_(b) & bitofstg_(s_register)) { VRegnum r = bindxx_(b); /* register vars may be forced to memory by setjmp, leaving r == GAP */ if (r != GAP) vreg_(r)->refcount += 1000000; } l = l->bindlistcdr; } } if (debugging(DEBUG_REGS)) cc_msg("Slave list:\n"); /* transform slave_list into a more convenient form for our use */ for (p = slave_list; p!=NULL; p = p->next) { vreg_(p->r1)->slave = p->r2; if (debugging(DEBUG_REGS)) { cc_msg("%ld : ", (long)p->r1); if (p->r2 == GAP) cc_msg("GAP\n"); else cc_msg("%ld\n", (long)p->r2); } } #endif /* TARGET_IS_NULL */ /* First I iterate over the basic blocks to collect information about */ /* which registers are needed at the head of each block. With structured */ /* control-flow this should cost at worst one scan of the flowgraph */ /* (plus another to verify that there are no changes left over). With */ /* very contorted flow of control (e.g. via goto or switch with case */ /* labels inside embedded loops) it can take MANY iterations. */ phasename = "dataflow"; { bool changed; do { BlockHead *p; changed = NO; curstats.dataflow_iterations++; if (debugging(DEBUG_REGS)) cc_msg("Start a scan of register flow iteration\n"); for (p=bottom_block; p!=NULL; p = blkup_(p)) changed = changed | update_block_use_info(p); } while (changed); } if (debugging(DEBUG_REGS)) cc_msg("Block by block register use analysis complete\n"); dataflow_clock += clock() - t0; t0 = clock(); phasename = "clashmap"; { BlockHead *p; valn_reinit(); if (debugging(DEBUG_REGS)) for (p=top_block; p!=NULL; p=blkdown_(p)) flowgraf_printblock(p, YES); for (p=top_block; p!=NULL; p=blkdown_(p)) collect_register_clashes(p); } regalloc_clock1 += clock() - t0; t0 = clock(); #ifndef TARGET_IS_NULL if (debugging(DEBUG_REGS)) { cc_msg("\nGlobal register clash information collected\n"); for (i=0; i<NMAGICREGS; i++) { VRegister *r = vreg_(i); if (r->u.nclashes != 0) { cc_msg("r%ld clashes with:", (long)vregname_(r)); /* ==i */ printvregclash(r); cc_msg("\n"); } } for (i=1; i<vregistername-NMAGICREGS; i++) { VRegister *r = permregheap_(i); if (r->u.nclashes != 0) { if (r->realreg >= 0) cc_msg("[r%ld]: ", (long)r->realreg); cc_msg("v%ld clashes with:", (long)vregname_(r)); printvregclash(r); cc_msg("\n"); } } } for (i=1; i<vregistername-NMAGICREGS; i++) { VRegister *r = permregheap_(i); relation_map(vregname_(r), clashmatrix, flattenrelation_cb, (VoidStar)&r->clashes); } /* Form the register vector into a priority queue (heap) */ phasename = "regalloc"; for (i = (vregistername-NMAGICREGS-1)/2; i>=1; i--) downheap(i, vregistername-NMAGICREGS-1); for (i = vregistername-NMAGICREGS-1; i>0; i--) { VRegister *s = permregheap_(1), *t = permregheap_(i); if (debugging(DEBUG_REGS)) cc_msg("Register %ld clashes with %ld others\n", (long)vregname_(s), (long)s->u.nclashes); permregheap_(1) = t; t->heapaddr = 1; permregheap_(i) = s; s->heapaddr = i; downheap(1, i-1); s->realreg = R_SCHEDULED; removeclashes(s); } /* Now I will try the registers in the order just selected. */ for (i = 1; i < vregistername-NMAGICREGS; i++) { VRegister *rr = permregheap_(i); if (rr->realreg == R_SPILT) continue; /* spilt register */ if (!choose_real_register(rr)) { /* Here it is necessary to spill something */ uint32 spilt = spill_binder(rr, spill_order, &spillset); #ifdef ADDRESS_REG_STUFF if ( spilt == 0 ) { --i; /* spillpanic is now 1 */ continue; } #endif /* N.B. this loop modifies the main loop control variable!!! */ /* N.B. also (LDS) that while this loop appears to introduce quadratic */ /* complexity, experiment shows that the total number of re-tries is */ /* LESS than one scan through the list, ALMOST ALWAYS. Does this follow */ /* from ordering the list by most clashes first? */ while (i >= spilt) { VRegister *rr = permregheap_(i); if (rr->realreg != R_SPILT) rr->realreg = R_SCHEDULED; i--; } } } #ifdef ENABLE_SPILL if (debugging(DEBUG_SPILL)) cc_msg("%ld calls to choose_real_register() to allocate %ld vregs\n", (long)choose_count, (long)vregistername-NMAGICREGS); #endif nn = 0; if ((n_real_spills + n_cse_spills)> 1 && /* retrying may help */ (var_cc_private_flags & 4L) == 0) /* cleaning not suppressed */ { /* Here, we do some cleaning up of the register colouring to trying to */ /* the things that have already been spilt. Sometimes we'll succeed. */ /* This heuristic reduces the number of spills in the compiler by 2%, */ /* with significant savings in larger functions. First, then, we rebuild */ /* the complete clash lists for each spilt register. */ VRegSetP x; clock_t us_t = clock(); for (i = 1; i < vregistername-NMAGICREGS; ++i) { VRegister *rr = permregheap_(i); if (rr->realreg != R_SPILT) { /* the following destroys rr->clash2, saving store */ x = vregset_intersection(rr->clash2, spillset); rr->clash2 = (VRegSetP)DUFF_ADDR; } else x = vregset_intersection( vregset_copy(spillset, &listallocrec), rr->clash2); vregset_map(x, addclashes_rcb, (VoidStar)(IPtr)vregname_(rr)); } /* It isn't clear which way this loop should go - or even whether it's */ /* best to use notional spill cost order. So far, experiments on the */ /*compiler itself have been inconclusive. */ for (i = 1; i < vregistername-NMAGICREGS; ++i) { VRegister *rr = permregheap_(i); if (rr->realreg != R_SPILT) continue; if (choose_real_register(rr)) { Binder *bb = rr->u.spillbinder; bindxx_(bb) = vregname_(rr); if (bindstg_(bb) & b_pseudonym) bindsuper_(bb)->spillcount--; nn += 1; spill_cost -= rr->refcount; if (rr->refcount & 1L) --n_real_spills; else --n_cse_spills; if (debugging(DEBUG_SPILL)) cc_msg(" unspill: $b, v%lu = r%lu, saving = %lu\n", bb, vregname_(rr), rr->realreg, rr->refcount); } else if (debugging(DEBUG_SPILL)) cc_msg("\n"); } if (debugging(DEBUG_SPILL)) cc_msg("%lu vregs unspilt by cleaning pass in %ucs\n", nn, clock() - us_t); } /* WGD Now check for spurious deadbits arising from register copies */ { BlockHead *p; for (p=top_block; p!=NULL; p=blkdown_(p)) update_deadflags(p); for (p=top_block; p!=NULL; p=blkdown_(p)) vregset_discard(blkuse_(p)); } #else IGNORE(i); IGNORE(spill_order); #endif /* TARGET_IS_NULL */ regalloc_clock2 += clock() - t0; if (debugging(DEBUG_STORE | DEBUG_REGS)) stats_endproc(); #ifdef ENABLE_SPILL if (debugging(DEBUG_SPILL) && (n_real_spills + n_cse_spills + nn) > 0) { cc_msg("fn $r %3lu + %lu spills, cost = %6lu\n\n", currentfunction.symstr, n_real_spills, n_cse_spills, spill_cost); tot_real_spills += n_real_spills; tot_cse_spills += n_cse_spills; tot_cost += spill_cost; n_real_spills = n_cse_spills = spill_cost = 0; } #endif { SuperBinder *p = superbinders; for (; p != NULL; p = cdr_(p)) if (p->spillcount == 0) bindxx_(p->binder) = 0; } } #ifndef TARGET_IS_NULL /* change the union member in vregtable -- expand VRegnum's for allocation */ static void regalloc_changephase(void) { uint32 i; for (i = 0; i < vregistername; i++) { VRegnum rname = vregtypetab_(i); VRegister *v = (VRegister *) BindAlloc(sizeof(VRegister)); if (((uint32)rname & ~REGSORTMASK) != i) syserr(syserr_regalloc_reinit2); v->heapaddr = i-NMAGICREGS; /* -ve for real regs, 0 for sentinel */ v->perm = v; v->realreg = R_UNSCHEDULED; /* Not yet scheduled for allocation */ v->clash2 = (VRegSetP) DUFF_ADDR; v->u.nclashes = 0; v->rname = rname; v->ncopies = 0; v->refcount = 0; v->slave = GAP; v->clashes = NULL; v->valnum = VALN_UNSET; v->valsource = NULL; v->valwritecount = 0; vreg_(i) = v; if (i < NMAGICREGS) v->realreg = i; /* real register */ if (i == NMAGICREGS) v->u.nclashes = -1; /* heap sentinel */ } reg_lsbusetab = (unsigned char *)BindAlloc(vregistername); #ifdef LSBUSE_CONSISTENCY_CHECK lsbmap = (uint8 *)BindAlloc((vregistername/(LSBQUANTUM*8))+1); #endif } #endif /* TARGET_IS_NULL */ /* exported for cg.c and cse.c/csescan.c */ VRegnum vregister(RegSort rsort) { if ((vregistername&(REGHEAPSEGSIZE-1)) == 0) { int32 p = vregistername >> REGHEAPSEGBITS; if (p >= REGHEAPSEGMAX) syserr(syserr_regheap); else vregheap[p] = (vreg_type (*)[REGHEAPSEGSIZE]) BindAlloc(sizeof(*vregheap[0])); } vregtypetab_(vregistername) = rsort | vregistername; return vregistername++; } /* ... and its inverse (for cg/cse only, due regalloc_changephase()). */ RegSort vregsort(VRegnum r) { if ((unsigned32)r >= (unsigned32)vregistername) syserr(syserr_vregsort, (long)r); return vregtypetab_(r) & REGSORTMASK; } void globalregistervariable(VRegnum r) { unsigned32 dummy; VRegSetAllocRec a; a.alloctype = AT_Glob; a.statsloc = a.statsloc1 = a.statsbytes = &dummy; augment_RealRegSet(&globalregvarvec, r); vregset_init(); globalregvarset = vregset_insert(r, globalregvarset, NULL, &a); } RealRegSet const *globalregset(void) { return &globalregvarvec; } void avoidallocating(VRegnum r) { delete_RealRegSet(&m_intregs, r); #ifndef TARGET_SHARES_INTEGER_AND_FP_REGISTERS delete_RealRegSet(&m_fltregs, r); #endif #ifdef ADDRESS_REG_STUFF delete_RealRegSet(&m_addrregs, r); #endif } /* call before first use of vregister() */ void regalloc_reinit(void) { RealRegister i; /* parallel to vregistername here */ vregistername = 0; for (i = 0; i < NMAGICREGS; i++) (void)vregister(i < NINTREGS ? INTREG : DBLREG); (void)vregister(SENTINELREG); memclr((VoidStar)&curstats, sizeof(curstats)); memclr((VoidStar)&regmaskvec, sizeof(RealRegSet)); #ifndef TARGET_IS_NULL slave_list = NULL; #endif #ifdef ENABLE_SPILL n_real_spills = n_cse_spills = spill_cost = 0; #endif reg_lsbusetab = (unsigned char *)DUFF_ADDR; #ifdef LSBUSE_CONSISTENCY_CHECK lsbmap = (uint8 *)DUFF_ADDR; #endif } void regalloc_init(void) { VRegnum i; dataflow_clock = regalloc_clock1 = regalloc_clock2 = 0; /* * Active initialisations so that the compiled image has a chance to * be absolutely relocatable (e.g. for a RISC-OS relocatable module) */ clashrallocrec.alloctype = ClashAllocType; clashrallocrec.statsloc = &curstats.nsquares; clashrallocrec.statsbytes = &curstats.squarebytes; copyallocrec.alloctype = CopyAllocType; copyallocrec.statsloc = &curstats.copysquares; copyallocrec.statsbytes = &curstats.copysquarebytes; clashvallocrec.alloctype = ClashAllocType; clashvallocrec.statsloc = &curstats.nregsets; clashvallocrec.statsloc1 = &curstats.newregsets; clashvallocrec.statsbytes = &curstats.regsetbytes; listallocrec.alloctype = ListAllocType; listallocrec.statsloc = &curstats.nlists; listallocrec.statsloc1 = &curstats.newlists; listallocrec.statsbytes = &curstats.listbytes; memclr((VoidStar)(&maxstats), sizeof(maxstats)); memclr((VoidStar)&m_notpreserved, sizeof(RealRegSet)); for (i = 0; i<NMAGICREGS; i++) #ifdef target_preserves /* better? */ if (target_preserves(i)) #else if (!(R_V1 <= i && i < R_V1+NVARREGS #ifndef TARGET_SHARES_INTEGER_AND_FP_REGISTERS || R_FV1 <= i && i < R_FV1+NFLTVARREGS #endif )) #endif augment_RealRegSet(&m_notpreserved,i); memclr((VoidStar)&m_intregs, sizeof(RealRegSet)); for (i = 0; i<NMAGICREGS; i++) if (R_A1 <= i && i < R_A1+NARGREGS || R_P1 <= i && i < R_P1+NARGREGS || R_V1 <= i && i < R_V1+NVARREGS /* on many machines R_IP will be one of the NTEMPREGS, but to allow it */ /* to be non-contiguous we treat it specially. */ || i == R_IP || R_T1 <= i && i < R_T1+NTEMPREGS #ifndef TARGET_STACKS_LINK || i == R_LR #endif ) augment_RealRegSet(&m_intregs,i); #ifndef TARGET_SHARES_INTEGER_AND_FP_REGISTERS memclr((VoidStar)&m_fltregs, sizeof(RealRegSet)); for (i = 0; i<NMAGICREGS; i++) if (R_FA1 <= i && i < R_FA1+NFLTARGREGS || R_FP1 <= i && i < R_FP1+NFLTARGREGS || R_FT1 <= i && i < R_FT1+NFLTTEMPREGS || R_FV1 <= i && i < R_FV1+NFLTVARREGS) augment_RealRegSet(&m_fltregs,i); #endif #ifdef ADDRESS_REG_STUFF memclr((VoidStar)&m_addrregs, sizeof(RealRegSet)); for (i = 0; i<NMAGICREGS; i++) if (target_isaddrreg_(i)) augment_RealRegSet(&m_addrregs,i); #endif memclr((VoidStar)&globalregvarvec, sizeof(RealRegSet)); globalregvarset = 0; #ifdef ENABLE_SPILL tot_real_spills = tot_cse_spills = tot_cost = choose_count = 0; #endif INIT_IC(ic_noop, J_NOOP); warn_corrupted_regs = 0; } void regalloc_tidy(void) { #ifdef ENABLE_SPILL if (debugging(DEBUG_SPILL)) cc_msg("%lu binders spilt, %lu CSEs re-evaluated, total cost = %lu\n", tot_real_spills, tot_cse_spills, tot_cost); #endif if (!debugging(DEBUG_STORE | DEBUG_REGS)) return; cc_msg("Regalloc max space stats:\n"); stats_print(&maxstats); cc_msg("Dataflow time %ldcs, regalloc time %ld+%ldcs\n", (long)dataflow_clock, (long)regalloc_clock1, (long)regalloc_clock2); } /* The following routine should really be a 'const RealRegSet' extern */ /* definition. However, there seems to be no way to initialise it in */ /* C. Note that it gets called before regalloc_init() (e.g. builtin.c) */ /* and so the obvious initialisation fails. */ extern void reg_setallused(RealRegSet *s) { memset(s, 0xff, sizeof(*s)); } /* end of regalloc.c */
stardot/ncc
mip/flowgraf.c
/* * C compiler file mip/flowgraf.c * Copyright (C) Codemist Ltd., 1988. * Copyright (C) Acorn Computers Ltd., 1988. * Copyright (C) Advanced Risc Machines Ltd., 1991 * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 74 * Checkin $Date$ * Revising $Author$ */ /* AM hack in progress: fixup J_CMP to have the condition code which */ /* matches the J_B which follows. */ /* Moreover, this can now remove CMP's at end of basic blocks which */ /* have been make redundant by cross-jumping. */ /* Memo: it may be that tail-recursion optimisation should be done AFTER */ /* cross_jumping. This would allow common tails to be zipped. However */ /* it could lead to branches to branches if the tailcall expanded to just */ /* one branch instruction. */ /* Memo: move SETSP amalgamation here from armgen.c etc. */ #ifdef __STDC__ #include <string.h> #else #include <strings.h> #include <stddef.h> #endif #include "globals.h" #include "flowgraf.h" #include "store.h" #include "cg.h" #include "codebuf.h" #include "regalloc.h" #include "regsets.h" #include "aeops.h" #include "util.h" #include "jopcode.h" #include "mcdep.h" #include "builtin.h" #include "simplify.h" /* for mcrep fields/macros */ #include "xrefs.h" /* for xr_code/data */ #include "errors.h" #include "sr.h" #include "inline.h" /* Inline_RealUse */ #include "sem.h" /* AM Sep 88: Use obj_symref before J_ADCON (may kill J_FNCON on day) */ /* WGD 8- 3-88 Deadflag allowed for in expand_jop_macros */ /* WGD 26- 2-88 J_USEx passed to xxxgen as peepholer must also handle */ /* volatiles carefully */ /* WGD 15- 2-88 Corrected treatement of deadflags for pseudo_reads_rx ops */ /* WGD 19-10-87 Tailcall conversion blocked for assembler_call */ /* WGD 16-10-87 J_FNCON now passes static/extern flag in r2 */ /*@@@ AM:this shows that xr_xxx are not quite enough. */ /* AM 26-may-87: redo CASEBRANCH tables */ /* AM has changed RETURN so that it passes the xxxgen.c file a (possibly conditional) branch to RETLAB. This works nicely. However, we now have 5 special labels - RETLAB, RetIntLab, RetVoidLab, RetFltLab, NOTALAB. The last is notionally NULL, but changed for testing. Tidy sometime? */ /* The peepholer now effects the ARM elision of J_SETSP before RETURN. */ /* This means that remove_noops() & branch_chain() are not perfect. Think. */ /* @@@ The following lines are in flux: we need an environment of */ /* *user-declared* vars for debug info. This probably can be amalgamated */ /* with blkstack_ (discuss). There are some importance differences. */ struct CGState cgstate; #ifndef TARGET_IS_NULL static BindListList *current_env2; /* procedural interface to machine dependent code generator is via: */ /* show_instruction(), local_base(), local_address(), plus ... */ static void show_inst(Icode *ic) { if (uses_r1(ic->op)) { RealRegister r1r = register_number(ic->r1.r); if ((uint32)r1r >= (uint32)NMAGICREGS) syserr(syserr_r1r, (long)r1r); ic->r1.rr = r1r; } if (uses_r2(ic->op)) { RealRegister r2r = register_number(ic->r2.r); if ((uint32)r2r >= (uint32)NMAGICREGS) syserr(syserr_r2r, (long)r2r); ic->r2.rr = r2r; } if (uses_r3(ic->op)) { RealRegister r3r = register_number(ic->r3.r); if ((uint32)r3r >= (uint32)NMAGICREGS) syserr(syserr_r3r, (long)r3r); ic->r3.rr = r3r; } if (uses_r4(ic->op)) { RealRegister r4r = register_number(ic->r4.r); if ((uint32)r4r >= (uint32)NMAGICREGS) syserr(syserr_r4r, (long)r4r); ic->r4.rr = r4r; } #ifdef TARGET_HAS_2ADDRESS_CODE if (jop_asymdiadr_(ic->op) && two_address_code(ic->op)) { /* code in regalloc has ensured that r1 & r3 clash if r1 != r2 */ if (ic->r1.rr != ic->r2.rr && ic->r1.rr == ic->r3.rr) syserr(syserr_expand_jop); } /* Maybe turn all 3-address codes to 2-address + MOVR here, but */ /* think more w.r.t use of load-address target opcodes. */ #endif show_instruction(ic); } static void show_mem_inst1(J_OPCODE op, VRegnum r1, Binder *b, int32 k) { Icode ic; INIT_IC (ic, op); if (uses_r1(op)) { RealRegister r1r = register_number(r1); if ((uint32)r1r >= (uint32)NMAGICREGS) syserr(syserr_r1r, (long)r1r); ic.r1.rr = r1r; } else ic.r1.r = r1; ic.r2.rr = local_base(b); ic.r3.i = local_address(b) + k; ic.op &= ~J_DEAD_R3; #ifdef TARGET_HAS_RISING_STACK if ((bindaddr_(b) & BINDADDR_MASK) == BINDADDR_LOC) ic.r3.i += sizeof_int - ((b->bindmcrep) & MCR_SIZE_MASK); #endif if (op != J_ADDK && alignof_toplevel_auto >= 4) /* (ADCONV) */ ic.op |= J_BASEALIGN4; show_instruction(&ic); } static void show_mem_inst(J_OPCODE op, VRegnum r1, Binder *b) { show_mem_inst1(op, r1, b, 0); } static void show_inst3(J_OPCODE op, VRegInt r1, VRegInt r2, VRegInt r3) { Icode ic; INIT_IC3 (ic, op, r1, r2, r3); show_inst (&ic); } #endif /* TARGET_IS_NULL */ /* the next 4 private vars control start_basic_block() and emit() */ static Icode *icodetop, *currentblock; static int32 icoden; static bool deadcode; /* says to lose code = no current block */ typedef struct FreeIcodeChunk { struct FreeIcodeChunk *next; int32 size; } FreeIcodeChunk; static FreeIcodeChunk *holes; /* A list of the gaps at the top of Icode segments, for the use of CSE * and loop optimisations (NOT used while emitting code). The chaining * is in the Icode blocks themselves. */ static BlockHead *block_header; BlockHead *top_block, *bottom_block; /* exported to cg/regalloc */ /* beware: way_out is used for two different purposes. */ static LabelNumber *way_out; #define size_of_binders(l) sizeofbinders(l, NO) int32 sizeofbinders(BindList *l, bool countall) /* return total size of non-slaved binders in the given list */ /* Note that the BindList is in 'most recently bound first' order. */ /* Thus, if alignof_double>alignof_toplevel we must be careful to pad */ /* appropriately (a la padsize). But normal padding algorithms pad */ /* from the zero origin end. Hence the special one here. */ { int32 m = 0, m1 = 0; bool dbleseen = 0; for (; l!=NULL; l = l->bindlistcdr) { Binder *b = l->bindlistcar; if (!(bindstg_(b) & bitofstg_(s_auto))) syserr(syserr_nonauto_active); if (bindxx_(b) == GAP || countall) /* It is important that Binders processed here have had mcrepofexpr() */ /* called on them before so that a cached rep is present. This is because */ /* the TypeExpr may have been thrown away. */ { int32 rep = bindmcrep_(b); if (rep == NOMCREPCACHE) syserr(syserr_size_of_binder); /* The next line fixes up the backward scan of offsets. */ if (alignof_double > alignof_toplevel_auto && rep & MCR_ALIGN_DOUBLE && !dbleseen) (dbleseen = 1, m1 = m, m = 0); m = padtomcrep(m, rep) + padsize(rep & MCR_SIZE_MASK, alignof_toplevel_auto); } } if (dbleseen) m = padsize(m, alignof_double); return m+m1; } static BlockHead *newblock2(LabelNumber *lab, BindList *active_on_entry) { /* one day it may be nice to make the 2nd arg a union { int; BindList *} */ BlockHead *p = (BlockHead *) BindAlloc(sizeof(BlockHead)); cgstate.block_cur += sizeof(BlockHead); blkcode_(p) = (Icode *) DUFF_ADDR; blkusedfrom_(p) = NULL; blklab_(p) = lab; blklength_(p) = 0; blknext_(p) = (LabelNumber *) DUFF_ADDR; blknext1_(p) = (LabelNumber *) DUFF_ADDR; blkflags_(p) = 0; blkuse_(p) = 0; blkstack_(p) = active_on_entry; blknest_(p) = 0; blkexenv_(p) = currentExceptionEnv; return(p); } static BlockHead *newblock(LabelNumber *lab, BindList *active_on_entry) { BlockHead *p = newblock2(lab, active_on_entry); if (bottom_block!=0) blkdown_(bottom_block) = p; blkup_(p) = bottom_block; blkdown_(p) = NULL; blkdebenv_(p) = current_env; bottom_block = block_header = p; return(p); } BlockHead *insertblockbetween(BlockHead *before, BlockHead *after, bool insertingraph) { LabelNumber *newlab = nextlabel(); BlockHead *newbh = newblock2(newlab, blkstack_(after)); newlab->block = newbh; blknext_(newbh) = blklab_(after); /* Insert the new block after <before> in the blkdown chain */ /* Often, this will be between <before> and <after> */ { BlockHead *afterbefore = blkdown_(before); blkdown_(before) = newbh; blkdown_(newbh) = afterbefore; blkup_(newbh) = before; if (afterbefore == NULL) bottom_block = newbh; else blkup_(afterbefore) = newbh; } blkdebenv_(newbh) = blkdebenv_(after); blkexenv_(newbh) = blkexenv_(after); if (insertingraph) changesuccessors(before, newlab, blklab_(after)); return newbh; } void changesuccessors(BlockHead *b, LabelNumber *newl, LabelNumber *old) { bool replaced = NO; if (blkflags_(b) & BLKSWITCH) { LabelNumber **table = blktable_(b); int32 i, n = blktabsize_(b); for (i=0; i<n; i++) if (table[i] == old) replaced = YES, table[i] = newl; } else { if (blknext_(b) == old) replaced = YES, blknext_(b) = newl; if ((blkflags_(b) & BLK2EXIT) && blknext1_(b) == old) replaced = YES, blknext1_(b) = newl; } if (!replaced) syserr(syserr_insertblockbetween, (int32)lab_name_(blklab_(b)), (int32)lab_name_(old)); } void finishblock(void) { blkcode_(block_header) = currentblock; blklength_(block_header) = icoden; currentblock = &currentblock[icoden]; icoden = 0; } void end_emit(void) { if (currentblock < icodetop) freeicodeblock(currentblock, icodetop - currentblock); } Icode *newicodeblock(int32 size) { FreeIcodeChunk *p = holes, *prev = NULL; while (p != NULL) { int32 left = p->size - size; if (left >= 0) { if (left == 0) { if (prev == NULL) holes = p->next; else prev->next = p->next; return (Icode *)p; } else { p->size = left; return &((Icode *)p)[left]; } } prev = p; p = p->next; } return (Icode *) BindAlloc(size * sizeof(Icode)); } void freeicodeblock(Icode *p, int32 size) { FreeIcodeChunk *q = (FreeIcodeChunk *) p; q->next = holes; q->size = size; holes = q; } void reopen_block(BlockHead *p) { /* This is required during loop optimisation. *p is a block that has no */ /* code in it but which is otherwise complete. Set it up so that I can */ /* emit() code into the block. */ /* Note that I will need to call finishblock() again when I am done. */ IGNORE(p); syserr(syserr_reopen_block); } BlockHead *start_basic_block_at_level(LabelNumber *l, BindList *active_on_entry) { BlockHead *b; if (!deadcode) emitbranch(J_B, l); /* round off the previous block */ l->block = b = newblock(l, active_on_entry); /* set the label */ deadcode = 0; /* assume label will be referenced */ if (debugging(DEBUG_CG)) { cc_msg("L%ld: ", (long)lab_name_(l)); pr_bindlist(active_on_entry); cc_msg("\n"); } return b; } bool is_exit_label(LabelNumber *ll) /* exported to jopprint.c/cse.c. (lab_xname_) */ { if (ll == RetIntLab || ll == RetFloatLab || ll == RetDbleLab || ll == RetVoidLab || ll == RetImplLab || /* RETLAB is present here so that print_jopcode may safely be used on the * arguments to show_instruction (when all the above have turned into RETLAB). */ ll == RETLAB) return YES; else return NO; } /* emit() really takes a union mode as its last arg, so I provide a */ /* number of entrypoints here so that I can preserve some type security */ /* despite this mess. */ void emitfl(J_OPCODE op, FileLine fl) { Icode ic; INIT_IC(ic,op); ic.r1.p = fl.p; ic.r2.str = fl.f; ic.r3.i = fl.l; emitic(&ic); } void emitshift(J_OPCODE op, VRegnum r1, VRegnum r2, VRegnum r3, int32 m) { Icode ic; INIT_IC(ic,op); ic.r1.r = r1; ic.r2.r = r2; ic.r3.r = r3; if (m == 0) emitic(&ic); #if defined TARGET_HAS_SCALED_ADDRESSING || defined TARGET_HAS_SCALED_OPS || \ defined TARGET_HAS_SCALED_ADD else { ic.op |= (m << J_SHIFTPOS); emitic(&ic); } #else else syserr(syserr_scaled_address); #endif } void emitstring(J_OPCODE op, VRegnum r1, StringSegList *m) { Icode ic; INIT_IC(ic,op); ic.r1.r = r1; ic.r2.i = 0; ic.r3.s = m; emitic(&ic); } void emitbranch(J_OPCODE op, LabelNumber *m) { Icode ic; INIT_IC(ic,op); ic.r3.l = m; emitic(&ic); } void emitbinder(J_OPCODE op, VRegnum r1, Binder *m) { Icode ic; INIT_IC(ic,op); ic.r1.r = r1; ic.r2.r = GAP; ic.r3.b = m; emitic(&ic); } void emitvk(J_OPCODE op, VRegnum r1, int32 n, Binder *m) { Icode ic; INIT_IC(ic,op); ic.r1.r = r1; ic.r2.i = n; ic.r3.b = m; emitic(&ic); } void emitreg(J_OPCODE op, VRegnum r1, VRegnum r2, VRegnum m) { Icode ic; INIT_IC(ic,op); ic.r1.r = r1; ic.r2.r = r2; ic.r3.r = m; emitic(&ic); } void emitreg4(J_OPCODE op, int flags, VRegnum r1, VRegnum r2, VRegnum r3, VRegnum r4) { Icode ic; INIT_IC(ic,op); ic.flags = flags; ic.r1.r = r1; ic.r2.r = r2; ic.r3.r = r3; ic.r4.r = r4; emitic(&ic); } void emitfloat(J_OPCODE op, VRegnum r1, VRegnum r2, FloatCon *m) { Icode ic; INIT_IC(ic,op); ic.r1.r = r1; ic.r2.r = r2; ic.r3.f = m; emitic(&ic); } void emitint64(J_OPCODE op, VRegnum r1, VRegnum r2, Int64Con *m) { Icode ic; INIT_IC(ic,op); ic.r1.r = r1; ic.r2.r = r2; ic.r3.i64 = m; emitic(&ic); } void emitsetsp(J_OPCODE op, BindList *b2) { /* Note optimization performed here. */ if (active_binders != b2) { Icode ic; INIT_IC(ic,op); ic.r2.bl = active_binders; ic.r3.bl = b2; emitic(&ic); active_binders = b2; } } void emitsetspandjump(BindList *b2, LabelNumber *l) { /* Note optimization performed here. */ if (active_binders != b2) { Icode ic; INIT_IC(ic, J_SETSPENV); ic.r2.bl = active_binders; ic.r3.bl = b2; emitic(&ic); } { Icode ic; INIT_IC(ic, J_B); ic.r3.l = l; emitic(&ic); } } void emitsetspenv(BindList *b1, BindList *b2) { Icode ic; INIT_IC(ic, J_SETSPENV); ic.r2.p = b1; ic.r3.p = b2; emitic(&ic); } void emitsetspgoto(BindList *b1, LabelNumber *l) { Icode ic; INIT_IC(ic, J_SETSPGOTO); ic.r2.p = b1; ic.r3.p = l; emitic(&ic); } void emitcall(J_OPCODE op, VRegnum resreg, int32 nargs, Binder *fn) { Icode ic; INIT_IC(ic,op); ic.r1.r = resreg; ic.r2.i = nargs; ic.r3.p = fn; emitic(&ic); } void emitcallreg(J_OPCODE op, VRegnum resreg, int32 nargs, VRegnum fn) { Icode ic; INIT_IC(ic,op); ic.r1.r = resreg; ic.r2.i = nargs; ic.r3.i = fn; emitic(&ic); } void emitcasebranch(J_OPCODE op, VRegnum r1, LabelNumber **tab, int32 size) { /* op == J_CASEBRANCH or J_THUNKTABLE or J_TYPECASE */ Icode ic; INIT_IC(ic,op); ic.r1.r = r1; ic.r2.p = tab; ic.r3.i = size; emitic(&ic); } void emit(J_OPCODE op, VRegnum r1, VRegnum r2, int32 m) { Icode ic; INIT_IC(ic,op); ic.r1.r = r1; ic.r2.r = r2; ic.r3.i = m; emitic(&ic); } void emitic(const Icode *const ic) { if (deadcode) { if (!usrdbg(DBG_LINE) || usrdbg(DBG_OPT_DEAD)) return; start_new_basic_block(nextlabel()); } if (ic->op==J_B) { deadcode = 1; if (debugging(DEBUG_CG)) print_jopcode(ic); finishblock(); blknext_(block_header) = ic->r3.l; return; } /* Conditional branches terminate a basic block, so force a new start */ /* if one has just been appended to the block */ if ((ic->op & ~Q_MASK)==J_B) { blknext1_(block_header) = ic->r3.l; blkflags_(block_header) |= BLK2EXIT; blkflags_(block_header) |= ic->op & Q_MASK; if (debugging(DEBUG_CG)) print_jopcode(ic); start_new_basic_block(nextlabel()); return; } /* The next line fixes to recover when I fill up a segment of store */ if (&currentblock[icoden] >= icodetop) { if (icoden >= ICODESEGSIZE/2) { if (debugging(DEBUG_CG | DEBUG_STORE)) cc_msg("Force new block (ICODE segment overflow)\n"); blkflags_(block_header) |= BLKREXPORTED; /* mark block as exporting! */ start_new_basic_block(nextlabel()); } /* The above arranges that icoden will be zero (following the call to */ /* start_new_basic_block() -> emitbranch() -> finishcode()) if it had */ /* originally been huge, and thus that I will not attempt an embarassingly */ /* large copy up into the new segment allocated here. */ { Icode *p = (Icode *) BindAlloc(ICODESEGSIZE*sizeof(Icode)); if (icoden != 0) { memcpy(p, currentblock, (size_t)(icoden*sizeof(Icode))); freeicodeblock(currentblock, icoden); } currentblock = p; icodetop = &p[ICODESEGSIZE]; if (debugging(DEBUG_CG)) cc_msg("New ICODE segment allocated\n"); cgstate.icode_cur += icoden * sizeof(Icode); /* wasted */ } } if (debugging(DEBUG_CG)) print_jopcode(ic); currentblock[icoden++] = *ic; cgstate.icode_cur += sizeof(Icode); if (isproccall_(ic->op) && ic->op != J_OPSYSK) { if (blkflags_(block_header) & BLKCALL) blkflags_(block_header) |= BLK2CALL; blkflags_(block_header) |= BLKCALL; /* see tail recursion optimisation comment below */ if ((ic->op == J_CALLR && (config & CONFIG_INDIRECT_SETJMP)) || (ic->op == J_CALLK && bindsym_(ic->r3.b) == setjmpsym)) { blkflags_(block_header) |= BLKSETJMP; if (feature & FEATURE_UNIX_STYLE_LONGJMP) /* We need this information early (to be able to turn off CSE), * but can't do branch_chain (where it is otherwise set) before * loop_optimise, because that turns some empty blocks into * non-empty ones. */ procflags |= BLKSETJMP; } } /* special ways to end a block */ if (ic->op == J_CASEBRANCH || ic->op == J_THUNKTABLE || ic->op == J_TYPECASE) { deadcode = 1; finishblock(); blkflags_(block_header) |= BLKSWITCH; blktable_(block_header) = ic->r2.lnn; blktabsize_(block_header) = ic->r3.i; } } /* AM believes that remove_noops logically fits here now. */ #ifndef TARGET_IS_NULL bool is_compare(J_OPCODE op) { J_OPCODE realop = op & J_TABLE_BITS; return (realop == J_CMPK || realop == J_CMPR || realop == J_CMPFR || realop == J_CMPDR || realop == J_CMPFK || realop == J_CMPDK || j_is_check(realop)); } static Icode fg_pending; static void show_pending_push(void) { /* Already tested that fg_pending.op == J_PUSHM */ show_inst (&fg_pending); fg_pending.op = J_NOOP, fg_pending.r3.i = 0; } static void expand_jop_macro(const Icode *const icode) { Icode ic = *icode; #ifdef TARGET_NOT_YET_J_ALIGNMENT /* removed soon */ ic.op &= ~J_ALIGNMENT; #endif if (debugging(DEBUG_CG)) print_jopcode(&ic); if (target_stack_moves_once) { /* * TARGET_STACK_MOVES_ONCE is believed to be OK when used in combination * with NARGREGS==0, and in that case it drops SP once at the start of a * procedure and lifts it on exit. If NARGREGS>0 all goes well when only * integer and pointer args are used. However double and structure args * are handled by temporarily pushing them onto the stack and then popping * them into the argument registers. While this is going on SP is not * where the MOVES_ONCE code expects it to be. Again these temporary * movements are normally local and can cause no hassle - but it seems * possible that CSE optimisation and cross-jumping might sometimes * rearrange code in a way that in effect distributes the local stack * movement across several basic blocks. At present this would break * the compiler, so with MOVES_ONCE and NARGREGS>0 it is suggested that * CSE and crossjumping be disabled for the while. Work is in hand to * fix this problem by moving the offending args into registers directly * rather than via the stack. Meanwhile a warning is generated if any * such local stack motion gets generated, and if the warning is not seen * all is well. */ /* @@@ BEWARE: assumption here that fg_pending==J_NOOP. */ /* Turn a PUSHx into a STRK, but only if the push did not */ /* involve dropping the stack when NARGREGS>0. */ /* E.g. struct { double d[3]; } x; ... f(x) ... with NARGREGS=4. */ J_OPCODE newop; switch (ic.op & J_TABLE_BITS) { case J_PUSHR: newop = J_STRK+J_ALIGN4; goto converted; case J_PUSHD: newop = J_STRDK+J_ALIGN8; goto converted; case J_PUSHF: newop = J_STRFK+J_ALIGN4; goto converted; case J_PUSHL: newop = J_STRLK+J_ALIGN8; goto converted; converted: if ((unsigned32)ic.r3.i < 4*NARGREGS) cc_warn(warn_untrustable, currentfunction.symstr); /* syserr() */ else /* @@@ (AM) BEWARE: do not trust this code if NARGREGS>0 since */ /* it makes assumptions easily invalidated by crossjump/cse. */ /* NB PUSHx codes are only used in function calls. */ { /* Forge a Binder sufficient for local_base/address. */ static Binder forgery; bindaddr_(&forgery) = BINDADDR_LOC | (greatest_stackdepth - (ic.r3.i - 4*NARGREGS)); /* @@@ "op & ~J_DEADBITS" was innocent effect of old code. Check?!! */ /* Also (only TARGET_STACK_MOVES_ONCE) J_STRK gets no J_ALIGNMENT. */ show_mem_inst(newop | (ic.op&J_DEAD_R1), ic.r1.r, &forgery); return; } /* @@@ (AM) BEWARE: do not trust this code if NARGREGS>0 since */ /* it makes assumptions easily invalidated by crossjump/cse. */ /* NB PUSHx codes are only used in function calls. */ default: break; } } #ifndef EXPERIMENTAL_68000 if ((ic.op & J_TABLE_BITS) == J_PUSHR) { ic.op = J_PUSHM; ic.r3.i = regbit(register_number(ic.r1.r)); ic.r1.r = ic.r2.r = GAP; } #endif /* Now, a (mini-)jopcode peepholer... ************************ */ /* Currently this just amalgamates J_PUSHR's, but J_SETSP's are next. */ /* See the BEWARE for TARGET_STACK_MOVES_ONCE above. */ if (ic.op == J_PUSHM) /* && (pending==J_NOOP || pending==J_PUSHM) */ { #ifdef TARGET_HAS_RISING_STACK /* The following check is that regs are ascending (this */ /* relies on the current code in cg.c). */ if (fg_pending.r3.i & -ic.r3.i) syserr(syserr_expand_pushr); #else /* The following check is that regs are descending (this */ /* relies on the current code in cg.c). */ if (ic.r3.i & -fg_pending.r3.i) syserr(syserr_expand_pushr); #endif fg_pending.op = J_PUSHM, fg_pending.r3.i |= ic.r3.i; if (ic.r3.i == #ifdef TARGET_HAS_RISING_STACK regbit(R_A1 + NARGREGS - 1) #else regbit(R_A1) #endif ) show_pending_push(); return; } if (fg_pending.op == J_PUSHM) show_pending_push(); /* end of peepholer ************************ */ switch (ic.op & J_TABLE_BITS) { case J_SETSP: if (target_stack_moves_once) return; /* Ignore. @@@ temporary placing here. */ break; #ifndef TARGET_HAS_SIGN_EXTEND case J_EXTEND: # ifdef TARGET_LACKS_SIGNED_SHIFT /* This trick could also be useful for loading signed chars on machines */ /* (like ARM) with load-byte with zero-extend, since the ANDK could */ /* be lost in the load-byte and the SUBK might fold with another const. */ { int32 msb = (ic.r3.i == 2 ? (int32)0x8000 : 0x80); ic.r3.i = (msb << 1) - 1; show_inst3(J_ANDK, ic.r1, ic.r2, ic.r3); ic.r3.i = msb; show_inst3(J_EORK, ic.r1, ic.r1, ic.r3); show_inst3(J_SUBK, ic.r1, ic.r1, ic.r3); } # else ic.r3.i = ic.r3.i == 2 ? 16: 24; show_inst3(J_SHLK, ic.r1, ic.r2, ic.r3); show_inst3(J_SHRK+J_SIGNED, ic.r1, ic.r1, ic.r3); # endif return; #endif /* The rest of this 'switch' deals with JOPCODE operators which are */ /* macro-expanded to others on every conceivable machine. */ /* N.B. the code below is slowly moving into remove_noops() */ /* The next few groups of cases should not be here - see remove_noops */ case J_LDRV: case J_STRV: case J_LDRLV:case J_STRLV: case J_LDRFV:case J_STRFV: case J_LDRDV:case J_STRDV: { Binder *bb = ic.r3.b; if (bindxx_(bb) != GAP) syserr(syserr_remove_noop_failed); ic.op = loads_r1(ic.op) ? J_XtoY(ic.op&~J_DEADBITS, J_LDRV, J_LDRK) : J_XtoY(ic.op&~J_DEADBITS, J_STRV, J_STRK) | (ic.op&J_DEAD_R1), /* J_ALIGNMENT preserved */ show_mem_inst(ic.op, ic.r1.r, bb); } return; case J_LDRV1:case J_LDRLV1:case J_LDRFV1:case J_LDRDV1: { Binder *bb = ic.r3.b; if (!isany_realreg_(register_number(ic.r1.r))) syserr(syserr_remove_noop_failed2); if ((bindaddr_(bb) & BINDADDR_MASK)!=BINDADDR_ARG) /* DEAD? */ syserr(syserr_bad_bindaddr); ic.op = J_XtoY(ic.op&~J_DEADBITS, J_LDRV1, J_LDRK), /* J_ALIGNMENT preserved */ show_mem_inst(ic.op, ic.r1.r, bb); } return; case J_LDRBVK:case J_STRBVK: case J_LDRWVK:case J_STRWVK: case J_LDRVK: case J_STRVK: case J_LDRFVK:case J_STRFVK: case J_LDRDVK:case J_STRDVK: case J_LDRLVK:case J_STRLVK: show_mem_inst1(J_subvk(ic.op), ic.r1.r, ic.r3.b, ic.r2.i); return; case J_ADCONV: show_mem_inst(J_ADDK, ic.r1.r, ic.r3.b); return; /* Here (in the case that string literals are to be writable, we remove */ /* J_STRING opcodes in favour of J_ADCON. */ case J_STRING: if (feature & FEATURE_WR_STR_LITS) /* * Pcc-mode - string lits writable in the data segment. */ { int32 offset = data_size(); /* The literal's about to be */ /* put at this offset ... */ vg_genstring(ic.r3.s, stringlength(ic.r3.s)+1, 0); /* The following call is unexpectedly important... */ /* vg_genstring() does not post-align, and other genXXX() fns */ /* do not pre-align, so death is inevitable if we omit it. */ /* It also plays its part in optimising string constants to word */ /* boundaries which improves performance on many machines (not just RISC) */ padstatic(alignof_toplevel_static); /* since datasegment is defined, it will have been obj_symref'd */ ic.op = J_ADCON; ic.r2.i = offset; ic.r3.sym = bindsym_(datasegment); show_inst(&ic); return; } ic.r2.i = 0; break; #ifdef TARGET_FP_LITS_FROM_MEMORY /* * In this case I want floating point string literals to go in the data * segment. Really I would still like equal constants to be able to share, * and also I would like CSE to be able to consolidate separate expressions * using constants (which might sometimes render the original constants * unnecessary. I note that mapping ADCONF/D onto just ADCON here seems to * lose information (in the data seg) that the data assembled is floating * point. */ case J_ADCOND: { int32 offset = data.size; gendcE(8, ic.r3.f); padstatic(alignof_toplevel_static); ic.op = J_ADCON; ic.r2.i = offset; ic.r3.sym = bindsym_(datasegment); show_inst(&ic); return; } case J_ADCONF: { int32 offset = data.size; gendcE(4, ic.r3.f); padstatic(alignof_toplevel_static); ic.op = J_ADCON; ic.r2.i = offset; ic.r3.sym = bindsym_(datasegment); show_inst(&ic); return; } #endif /* normalise some Binder's to Symstr's for xxxgen.c */ case J_ADCON: { Binder *bb = ic.r3.b; Symstr *name = bindsym_(bb); int32 offset = 0; { #ifdef TARGET_HAS_BSS if ((bindstg_(bb) & u_bss) && bindaddr_(bb) != BINDADDR_UNSET) { name = bindsym_(bsssegment); offset = bindaddr_(bb); } else #endif #ifdef CONST_DATA_IN_CODE if (bindstg_(bb) & u_constdata) { name = bindsym_(constdatasegment); offset = bindaddr_(bb); } else #endif if ((bindstg_(bb) & b_fnconst+bitofstg_(s_static)+u_loctype) == bitofstg_(s_static)) /* static variables get referenced relative to a static base */ /* extdef variables can be referenced that way, but here it seems nicer */ /* (and certainly it is no more expensive) to use the external symbol. */ { name = bindsym_(datasegment); offset = bindaddr_(bb); } } /* Announce to the linker the flavour (code/data) of the symbol. */ (void)obj_symref(name, (bindstg_(bb) & b_fnconst ? xr_code : xr_data) | (bindstg_(bb) & bitofstg_(s_weak) ? xr_weak : 0), 0); /* The next line of code is probably dying given the obj_symref() above. */ { #ifdef TARGET_CALL_USES_DESCRIPTOR if (bindstg_(bb) & b_fnconst) { /* WGD: pass static/extern flag in r2 */ ic.r2.i = bindstg_(bb) & bitofstg_(s_static); ic.r3.sym = name; ic.op = J_FNCON; } else #endif { ic.r2.i = offset; ic.r3.sym = name; } } } break; #ifndef TARGET_FP_ARGS_IN_FP_REGS case J_ENTER: ic.r3.i = k_argwords_(ic.r3.i); break; #endif case J_TAILCALLK: case J_CALLK: /* /* @@@ BUG here: 1. if m is a local static data binder, then it does */ /* not get defined in cfe.c.vargen (to avoid clashes and make sure */ /* store does not vanish under out feet). Thus this code should */ /* resolve to codesegment+nnn. However, unlike the ADCON case above */ /* there is no room for the nnn. */ /* 2. Moreover, the current (Dec 88) a.out formatter does not treat */ /* X_PCreloc branches to data segment correctly -- see AM comments. */ /* (This explains acorn's curious code in arm/mcdep.c). */ /* One fix is just to syserr(), or to fix into a CALLR. But beware */ /* that back ends do not support TAILCALLR yet (ANSI/register use). */ { ic.r3.sym = bindsym_(ic.r3.b); #if 0 /* /* The following code should never be needed: open_compilable in cg.c should ensure there are no calls left to memcpyfn etc (translating to real... if necessary). If it is needed, open_compilable should be fixed. */ if (ic.r3.sym == bindsym_(exb_(arg1_(sim.memcpyfn)))) ic.r3.sym = bindsym_(exb_(arg1_(sim.realmemcpyfn))); if (ic.r3.sym == bindsym_(exb_(arg1_(sim.memsetfn)))) ic.r3.sym = bindsym_(exb_(arg1_(sim.realmemsetfn))); #endif /* There used to be code here to do obj_symref() for the target, to */ /* avoid the need for each backend to do it. It's been retired, because */ /* the backend may be able to optimise the call away (and so want to */ /* avoid the reference) */ } break; #ifdef TARGET_HAS_DATA_VTABLES case J_WORD_ADCON: ic.r3.sym = bindsym_(ic.r3.b); break; #endif #ifdef TARGET_LACKS_RIGHTSHIFT /* then map constant right shifts here to leftright, expr ones done in cg.c */ case J_SHRK: ic.r3.i = -ic.r3.i; ic.op ^= J_SHRK^J_SHLK; break; #endif /* TARGET_LACKS_RIGHTSHIFT */ case J_NOOP: syserr(syserr_remove_noop_failed); return; } show_inst(&ic); } static void show_branch_instruction(J_OPCODE op, LabelNumber *m) { Icode ic; INIT_IC(ic,op); ic.r3.l = m; expand_jop_macro(&ic); } /* more of the debugger */ static void dbg_scope1(BindListList *newbl, BindListList *old) { IGNORE(newbl); IGNORE(old); /* avoid warnings when dbg_scope is FALSE */ if (dbg_scope(newbl, old)) { Icode ic; INIT_IC(ic, J_INFOSCOPE); ic.r3.i = 0; /* request code location where scope started or ended */ expand_jop_macro(&ic); } } static BlockHead *prevblock; static void show_basic_block(BlockHead *p, uint32 cond) { Icode *b = blkcode_(p); int32 len = blklength_(p); int32 b1; if (usrdbg(DBG_VAR)) dbg_scope1(blkdebenv_(p), current_env2), current_env2 = blkdebenv_(p); /* The BLKCODED bit allows me to display blocks out of their natural order */ /* @@@ but it may later cause trouble when DBG_VAR is on. */ /* /* AM: fix to suppress the spurious J_LABEL/J_STACK before J_ENTRY. */ blkflags_(p) |= BLKCODED; if (prevblock == NULL || blkusedfrom_(p) == NULL || blkusedfrom_(p)->blklstcdr != NULL || blkusedfrom_(p)->blklstcar != prevblock || (blkflags_(prevblock) & BLKSWITCH)) { Icode ic; INIT_IC (ic, J_LABEL); ic.r3.l = blklab_(p); expand_jop_macro(&ic); /* label of block */ if (!target_stack_moves_once) { ic.op = J_STACK; ic.r3.i = blkstacki_(p); expand_jop_macro(&ic); /* env. of block */ } } for (b1=0; b1<len; b1++) { Icode ic = b [b1]; uint32 cmpcond; switch (ic.op & J_TABLE_BITS) { case J_CMPK: case J_CMPR: case J_CMPFK: case J_CMPFR: case J_CMPDK: case J_CMPDR: cmpcond = ic.op & Q_MASK; if (cmpcond != Q_UNDEF && (cmpcond & ~Q_UBIT) != Q_UKN) { if (cond != Q_UKN) ic.op = (ic.op & ~Q_MASK) | cond; else ic.op = (ic.op & ~(Q_MASK & ~Q_UBIT)) | cond; } } expand_jop_macro(&ic); } prevblock = p; } static bool same_instruction(Icode *c1, Icode *c2) { /*Two instructions are deemed */ /* to match if they are identical when virtual registers have been */ /* converted to real register numbers wherever they are needed. The */ /* instructions that use pseudo-virtual registers to cope with items */ /* lifted out of loops etc have to match even more exactly, thus the */ /* tests here are conservative (and hence safe!). */ if (c1->op == c2->op && c1->flags == c2->flags) { int same = 0; /* The next fragment of code scares me somewhat - I need to see if the */ /* two instructions being considered will be treated identically after */ /* macro-expansion, where macro-expansion includes the replacement of */ /* virtual register identifiers by real register numbers. */ /* As more code moves from expand_jop_macro() to remove_noops this */ /* will ease. */ /* Note that remove_noops() has removed any possible loop invariant */ /* suggestions either by smashing to a RR operation or by */ /* removing the (pseudo_reads_r1/2) potential invariant register field. */ if (uses_r1(c1->op)) same += register_number(c1->r1.r) == register_number(c2->r1.r); else same += c1->r1.i == c2->r1.i; if (uses_r2(c1->op)) same += register_number(c1->r2.r) == register_number(c2->r2.r); else same += c1->r2.i == c2->r2.i; if (uses_r3(c1->op)) same += register_number(c1->r3.r) == register_number(c2->r3.r); else same += c1->r3.i == c2->r3.i; if (uses_r4(c1->op)) same += register_number(c1->r4.r) == register_number(c2->r4.r); else same += c1->r4.i == c2->r4.i; return same == 4 ? YES : NO; } return NO; } #endif /* TARGET_IS_NULL */ #define is_empty_block(b) (blklength_(b) == 0) /* remove_noops tidied */ /* N.B. BLKEMPTY and BLKALIVE are disjoint. */ /* BLKEMPTY performs a similar role to BLKALIVE: it flags that the */ /* block has been seen, BUT that it is not really alive. */ /* Note that self referential empty blocks have BLKALIVE set instead. */ static bool branch_chain_exit_label(LabelNumber *lab, int stage) { return is_exit_label(lab) || (stage == 2 && lab == way_out); } static LabelNumber *branch_emptychain(LabelNumber *lab, int stage) /* When we get an empty block we must flag it so (BLKEMPTY) */ /* and change its blknext_() pointer to where it ULTIMATELY */ /* goes. Note that empty blocks are never BLKALIVE except */ /* when they have a tight cycle which BLKBUSY detects. */ { LabelNumber *lab2 = lab, *lab3; /* skip to end of branch chain of empty basic blocks */ if (usrdbg(DBG_VAR+DBG_LINE) && !usrdbg(DBG_OPT_DEAD)) return lab; while (!branch_chain_exit_label(lab2, stage)) { BlockHead *b = lab2->block; /* Treat a block as empty if it does not have a conditional */ /* exit & it has no code (not overkill: three-way-branches). */ if (blkflags_(b) & BLK2EXIT || !is_empty_block(b) || (blkflags_(b) & (BLKBUSY|BLKALIVE|BLKEMPTY))) break; blkflags_(b) |= BLKBUSY; lab2 = blknext_(b); } /* the next line deals with the case that two empty chains have */ /* a common tail: lab3 is the real end of the branch chain. */ lab3 = lab2; if (!branch_chain_exit_label(lab3, stage)) { BlockHead *b = lab3->block; if (blkflags_(b) & BLKEMPTY) lab3 = blknext_(b); } /* now remove empty blocks (c.f. indirection nodes) */ while (lab != lab2) { BlockHead *b = lab->block; if (debugging(DEBUG_CG)) cc_msg("empty block: L%ld -> L%ld\n", (long)lab_name_(lab), (long)lab_xname_(lab3)); blkflags_(b) |= BLKEMPTY; blkflags_(b) &= ~BLKBUSY; /* only for tidyness */ lab = blknext_(b); blknext_(b) = lab3; /* smash it in */ } return lab3; /* the real place to go to */ } static LabelNumber *branch_chain(LabelNumber *lab, int stage) /* scan the flowgraph (a) marking bit BLKALIVE in blkflags_ of blocks */ /* that can be reached, and (b) converting any destination addresses in */ /* block exits to avoid chains of branches. */ /* When called on label n, if label n references a branch instruction */ /* this function returns the label number of the destination of the jump */ /* */ /* This code now uses pointer-reversal since otherwise it can use up a */ /* great deal of stack. */ { BlockHead *b, *back_pointer = NULL; for (;;) { for (;;) /* Here to descend via lab */ { lab = branch_emptychain(lab, stage); if (branch_chain_exit_label(lab, stage)) { if (lab == RetImplLab && !implicit_return_ok) implicit_return_ok = 1, cc_warn(flowgraf_warn_implicit_return); if (stage == 1) lab = way_out; break; /* exit: do not chain further */ } b = lab->block; if (blkflags_(b) & BLKALIVE) break; /* visited already */ blkflags_(b) |= BLKALIVE; #ifdef TARGET_HAS_TAILCALL /* set up the BLKSETJMP bit early enough for TAILCALL */ /* optimisation. refblock() sets up the other bits. */ procflags |= blkflags_(b) & BLKSETJMP; #endif if (blkflags_(b) & BLKSWITCH) { LabelNumber **v = blktable_(b); int32 i, n = blktabsize_(b); /* For the moment I will leave this next line as a recursive call */ for (i=0; i<n; i++) v[i] = branch_chain(v[i], stage); break; } blkflags_(b) = (blkflags_(b) & ~(BLKP2|BLKP3)) | BLKP2; lab = blknext_(b); blkbackp_(b) = back_pointer; /* share */ back_pointer = b; } for (;;) /* here to ascend */ { if (back_pointer==NULL) return lab; b = back_pointer; switch (blkflags_(b) & (BLKP2|BLKP3)) { default: syserr(syserr_branch_backptr); case BLKP2: back_pointer = blkbackp_(b); blknext_(b) = lab; /* share */ if (blkflags_(b) & BLK2EXIT) { lab = blknext1_(b); blkbackp1_(b) = back_pointer; /* share */ blkflags_(b) = (blkflags_(b) & ~(BLKP2|BLKP3)) | BLKP3; back_pointer = b; break; } lab = blklab_(b); continue; case BLKP3: back_pointer = blkbackp1_(b); blknext1_(b) = lab; /* share */ /* Optimise away the conditional exit if both exits from this block go */ /* to the same place. */ if (blknext_(b) == blknext1_(b) || (branch_chain_exit_label(blknext_(b), stage) && branch_chain_exit_label(blknext1_(b), stage) )) { blkflags_(b) &= ~(BLK2EXIT|Q_MASK); if (!(blkflags_(b) & BLKCCEXPORTED) && is_compare(blkcode_(b)[blklength_(b)-1].op)) if (--blklength_(b) == 0 && lab != blklab_(b)) { BlockHead *b1 = top_block; LabelNumber *l = blklab_(b); /* Empty predecessors of b must have their successor altered to blknext_(b), or a subsequent block with successor one of them will get forwarded to b not blknext_(b). This rewriting makes it safe to mark b BLKEMPTY below. */ for (; b1 != NULL; b1 = blkdown_(b1)) { if (blknext_(b1) == l) blknext_(b1) = lab; if ((blkflags_(b1) & BLK2EXIT) && blknext1_(b1) == l) blknext1_(b1) = lab; } blkflags_(b) = (blkflags_(b) & ~BLKALIVE) | BLKEMPTY; continue; } } lab = blklab_(b); continue; } break; /* so that break inside the switch = break in for */ } } } /* shouldn't the next line have BLK0EXIT? or is that done elsewhere? */ #define block_single_entryexit(b) \ (block_single_exit(b) && block_single_entry(b)) #define block_single_entry(b) \ (blkusedfrom_(b) == NULL || blkusedfrom_(b)->blklstcdr == NULL) #define block_single_exit(b) \ (!(blkflags_(b) & (BLK2EXIT | BLKSWITCH))) #define block_coded(b) (blkflags_(b) & BLKCODED) static int32 adjust_stack_size(int32 stack_size, Icode *code) { switch (code->op & J_TABLE_BITS) { /* This code seems distinctly grotty... */ case J_SETSP: if (stack_size != code->r2.i) syserr(syserr_zip_blocks, stack_size, code->r2.i); return code->r3.i; case J_PUSHD: case J_PUSHL: return stack_size + 8; /* alignof_toplevel_auto==8 is a euphemism for TARGET_IS_ADENART, else 4. */ case J_PUSHR: case J_PUSHF: return stack_size + alignof_toplevel_auto; /* AM: use 4 (or sizeof_long?) on next lines in case sizeof_int==2. */ /* (Oct 89) the following lines' case is under re-organisation. */ default: return stack_size; } } static int32 adjusted_stack_size(int32 stack_size, Icode *code, int32 n) { int32 i; if (!target_stack_moves_once) for (i = 0; i < n; i++) stack_size = adjust_stack_size(stack_size, &code[i]); return stack_size; } #ifdef TARGET_HAS_COND_EXEC #define set_cond_execution(cond) \ { Icode ic; INIT_IC(ic, (J_CONDEXEC|(cond))) \ ic.r3.i = 0; expand_jop_macro(&ic); } /* A block is not usable with conditional execution if if ends with a */ /* conditional branch (or switch), or if it is shared between the */ /* path in the code where a condition code will be tested and any */ /* other route through the code. */ #define conditionalizable(b, fl, maxl) \ (block_single_entryexit(b) ? block_preserves_cc(b, fl, maxl) : Bpcc_No) #define cc_ignorecmp 1 #define cc_includelast 2 #define Bpcc_No 255 static int CondMax_Ordinary, CondMax_Loop; static int block_preserves_cc(BlockHead *b, int fl, int maxl) /* True if the block does not contain any instructions that would cause */ /* trouble with conditional execution & if the block is also short */ /* (Ignorecmp is set only if the block is known to be two-exit) */ { int n = 0; Icode *c = blkcode_(b); int32 i, len = blklength_(b); if (fl & cc_ignorecmp) { len--; n++; } for (i = 0; i < len; i++) { switch (c[i].op & J_TABLE_BITS) { case J_SAVE: return Bpcc_No; case J_VSTORE: case J_USE: continue; /* these expand into nothing */ #ifdef TARGET_HAS_BLOCKMOVE #ifdef TARGET_IS_ARM_OR_THUMB case J_MOVC: case J_CLRC: /* Some cases get expanded into a loop ... These I want to reject even as the last op in a block. */ if (alterscc(&c[i])) return Bpcc_No; /* increment instruction count by 3 */ n += 2; break; #endif #endif case J_NOOP: /* remove_noops has normalised noops to J_NOOP */ syserr(syserr_remove_noop_failed); continue; default: if (((fl & (cc_ignorecmp|cc_includelast)) || i+1 < len) && alterscc(&c[i])) return Bpcc_No; } if (++n > maxl) return Bpcc_No; } return n; } static void show_conditional_block(int32 cond, BlockHead *p, bool showbranch) { /* Show a block with conditional execution enabled */ set_cond_execution(cond); show_basic_block(p, Q_AL); if (!(blkflags_(p) & BLK0EXIT) && showbranch) { LabelNumber *l = blknext_(p); show_branch_instruction(J_B, l == way_out ? RETLAB : l); } prevblock = NULL; set_cond_execution(Q_AL); } #define EQ_COND(x) (((x) | Q_UBIT) == Q_UEQ || ((x) | Q_UBIT) == Q_UNE) static void show_blockchain(BlockHead *b, BlockList *bl, int32 cond) { /* Two surprising things are done here to stop the ARM peepholer making incorrect transformations: the cond field in comparisons may be set to Q_UKN to prevent its being changed in one place (but not consistently) a CONDEXEC jopcode is output before each block to stop all but the last comparison being optimised out. */ show_basic_block(b, Q_UKN); set_cond_execution(cond); for (; bl != NULL; bl = bl->blklstcdr) { b = bl->blklstcar; cond = blkflags_(b) & Q_MASK; if (!EQ_COND(cond) || bl->blklstcdr != NULL) cond = Q_UKN; show_basic_block(bl->blklstcar, cond); if (bl->blklstcdr != NULL) set_cond_execution(Q_NEGATE(blkflags_(b) & Q_MASK)); } } static void pr_blocklist(BlockList *bl) { for (; bl != NULL; bl = bl->blklstcdr) cc_msg(" %ld", lab_name_(blklab_(bl->blklstcar))); } typedef struct CommonInst CommonInst; struct CommonInst { CommonInst *cdr; int32 n1, n2; }; static CommonInst *common_insts(BlockHead *b1, BlockHead *b2) { CommonInst *c = NULL, **cp = &c; Icode *c1 = blkcode_(b1), *c2 = blkcode_(b2); int32 l1 = blklength_(b1), l2 = blklength_(b2); int32 n1, n2 = 0; for (n1 = 0; n1 < l1; n1++) { int32 p2; for (p2 = n2; p2 < l2; p2++) if (same_instruction(&c1[n1], &c2[p2]) && !alterscc(&c1[n1]) && !is_compare(c1[n1].op)) { CommonInst *ci = (CommonInst *)SynAlloc(sizeof(*ci)); cdr_(ci) = NULL; ci->n1 = n1; ci->n2 = p2; *cp = ci; cp = &cdr_(ci); n2 = p2+1; break; } } return c; } static void show_block_pair(int32 cond, BlockHead *b1, BlockHead *b2, CommonInst *c) { Icode *c1 = blkcode_(b1), *c2 = blkcode_(b2); int32 l1 = blklength_(b1), l2 = blklength_(b2); int32 s1 = blkstacki_(b1), s2 = blkstacki_(b2); int32 n1, n2; int32 p1 = 0, p2 = 0; do { if (c == NULL) { n1 = l1; n2 = l2; } else { n1 = c->n1; n2 = c->n2; c = cdr_(c); } if (p1 != n1) { set_cond_execution(cond); if (!target_stack_moves_once && s1 != s2) { Icode ic; INIT_IC(ic, J_STACK); ic.r3.i = s1; expand_jop_macro(&ic); } for (; p1 < n1; p1++, c1++) { s1 = adjust_stack_size(s1, c1); expand_jop_macro(c1); } } if (p2 != n2) { set_cond_execution(Q_NEGATE(cond)); if (!target_stack_moves_once && s1 != s2) { Icode ic; INIT_IC(ic, J_STACK); ic.r3.i = s2; expand_jop_macro(&ic); } for (; p2 < n2; p2++, c2++) { s2 = adjust_stack_size(s2, c2); expand_jop_macro(c2); } } if (n1 < l1) { set_cond_execution(Q_AL+Q_UBIT); s1 = adjust_stack_size(s1, c1); s2 = adjust_stack_size(s2, c2); expand_jop_macro(c1); c1++; c2++; p1++, p2++; } } while (p1 < l1 || p2 < l2); blkflags_(b1) |= BLKCODED; blkflags_(b2) |= BLKCODED; set_cond_execution(Q_AL); } static bool successor_inline(BlockHead *b) { LabelNumber *next = blknext_(b); BlockHead *b1; BlockList *bl; if (next == way_out) return NO; b1 = next->block; if (block_coded(b1)) return NO; /* b1 will be coded inline after b if its only predecessors which */ /* have not yet been coded are b and b1 itself */ for (bl = blkusedfrom_(b1); bl != NULL; bl = bl->blklstcdr) { BlockHead *b2 = bl->blklstcar; if (b2 != b && b2 != b1 && !block_coded(b2)) { /* or probably if it is the first non-empty successor of b */ b2 = blkdown_(b); for (; b2 != NULL; b2 = blkdown_(b2)) if (!(blkflags_(b2) & BLKEMPTY)) return b2 == b1; } } return YES; } #endif #ifndef TARGET_IS_NULL static void show_n(int32 n, Icode *c, int32 s) { int32 i; IGNORE(s); for (i = 0; i < n; i++, c++) expand_jop_macro(c); } #define BLKLIFTABLE BLKP2 static LabelNumber *use_cond_field(BlockHead *p) { /* Decide if I can afford to use conditional execution. To do so I need: */ /* */ /* A A A A */ /* / \ | \ | \ | \__(return) */ /* B C | C | C | */ /* \ / | / | \__(return) | */ /* D D D D */ /* */ /* where B and C are short blocks that do not disturb the condition */ /* codes which are not reached from elsewhere. */ /* A here may be a single block, or a sequence of 2-exit blocks with a */ /* common successor (reached with the same condition code), with blocks */ /* in the sequence single-entry and not disturbing condition codes */ /* (except by the comparison at their end). */ /* If either successor block for A has been displayed already I do not */ /* need to use conditional execution. */ /* Block p has now not yet been displayed. */ int32 cond = blkflags_(p) & Q_MASK, lifted = blkflags_(p) & BLKLIFTABLE; LabelNumber *next = blknext_(p), *next1 = blknext1_(p); BlockHead *b = 0, *b1 = 0; int32 next1_arcs = 1; #ifdef TARGET_HAS_COND_EXEC # define show_head(p, cond) if (next1_arcs == 1) show_basic_block(p, cond) #else # define show_head(p, cond) show_basic_block(p, cond) #endif if (cond == Q_AL) syserr(syserr_no_main_exit); if (next != way_out) b = next->block; if (next1 != way_out) b1 = next1->block; /* if (b == 0 && b1 == 0) syserr(syserr_two_returns); */ blkflags_(p) |= BLKCODED; /* a bit of a hack -- see show_basic_block */ #ifdef TARGET_HAS_COND_EXEC /* Look for a sequence of 2-exit blocks with a common successor */ if (!usrdbg(DBG_VAR+DBG_LINE)) { int32 cond2 = 0; LabelNumber *commonexit = NULL; BlockHead *bh = NULL; if (b1 != NULL && !block_coded(b1) && block_single_entry(b1) && (blkflags_(b1) & BLK2EXIT) && block_preserves_cc(b1, cc_ignorecmp, CondMax_Ordinary) != Bpcc_No) { if ((blknext_(b1) == next && Q_implies(blkflags_(b1), cond)) || (blknext1_(b1) == next && Q_implies(Q_NEGATE(blkflags_(b1)), cond))) { commonexit = next; bh = b1; } } if (b != NULL && !block_coded(b) && block_single_entry(b) && (blkflags_(b) & BLK2EXIT) && block_preserves_cc(b, cc_ignorecmp, CondMax_Ordinary) != Bpcc_No) { if ((blknext1_(b) == next1 && Q_implies(Q_NEGATE(blkflags_(b)), Q_NEGATE(cond))) || (blknext_(b) == next1 && Q_implies(blkflags_(b), Q_NEGATE(cond)))) { commonexit = next1; bh = b; cond = Q_NEGATE(cond); } } if (commonexit != NULL) { BlockList *blockchain = NULL; int total_instr = 0; if (blknext_(bh) == commonexit) cond2 = blkflags_(bh); else cond2 = Q_NEGATE(blkflags_(bh)); for (;;) { int num_instr = block_preserves_cc(bh, cc_ignorecmp, CondMax_Ordinary); total_instr += num_instr; if (block_coded(bh) || !block_single_entry(bh) || num_instr == Bpcc_No || (blkflags_(bh) & BLKLIFTABLE) != lifted || total_instr > CondMax_Ordinary) break; if (blknext1_(bh) == commonexit && Q_implies(Q_NEGATE(blkflags_(bh)), cond2)) { next = blknext_(bh); cond2 = Q_NEGATE(blkflags_(bh)); } else if (blknext_(bh) == commonexit && Q_implies(blkflags_(bh), cond2)) { LabelNumber *tmp = blknext1_(bh); next = blknext1_(bh); cond2 = blkflags_(bh); /* Swap next and next1 in order to simplify showblockchain. This is OK * since the condition is inverted too. */ blknext1_(bh) = blknext_(bh); blknext_(bh) = tmp; blkflags_(bh) = Q_NEGATE(blkflags_(bh)); } else break; next1 = commonexit; blockchain = mkBlockList(blockchain, bh); if (next == way_out) break; bh = next->block; } blockchain = (BlockList *)dreverse((List *)blockchain); next1_arcs = length((List *)blockchain)+1; if (debugging(DEBUG_CG)) { cc_msg("Conditional chain %ld", lab_name_(blklab_(p))); pr_blocklist(blockchain); cc_msg(" cond1 %lx cond2 %lx common successor %ld other successor %ld\n", cond, cond2, lab_name_(next1), lab_name_(next)); if (next1 != way_out) { cc_msg("Predecessors of common successor:"); pr_blocklist(blkusedfrom_(next1->block)); cc_msg("\n"); } } show_blockchain(p, blockchain, cond & Q_MASK); set_cond_execution(Q_AL); cond = Q_NEGATE(cond2 & Q_MASK); /* condition for next basic block */ if (next == next1) /* I think this should now never happen */ return next; b = (next == way_out) ? 0 : next->block; b1 = (next1 == way_out) ? 0 : next1->block; } } #endif { Icode *commonp = NULL; int32 ncommon = 0; int32 s = 0; if (b != 0 && b1 != 0 && !block_coded(b) && !block_coded(b1) && block_single_entry(b) && length((List *)blkusedfrom_(b1)) == next1_arcs) { int32 l1 = blklength_(b), l2 = blklength_(b1); Icode *c1 = blkcode_(b), *c2 = blkcode_(b1); commonp = c1; if (l1 > l2) l1 = l2; if (!target_stack_moves_once) s = blkstacki_(b); if (target_stack_moves_once || s == blkstacki_(b1)) for (ncommon = 0; ncommon < l1; ncommon++, c1++, c2++) if (!same_instruction(c1, c2) || alterscc(c1) || is_compare(c1->op)) break; blklength_(b) -= ncommon; blklength_(b1) -= ncommon; blkcode_(b) += ncommon; blkcode_(b1) += ncommon; blkstacki_(b) = blkstacki_(b1) = adjusted_stack_size(s, commonp, ncommon); } /* backward branches have priority over conditional execution */ if (b != 0 && block_coded(b)) { if (b1 == 0 || !block_coded(b1) || blknest_(b) > blknest_(b1)) { show_head(p, Q_NEGATE(cond)); show_branch_instruction(J_B + Q_NEGATE(cond), next); return (next1 == way_out) ? RETLAB : next1; } } if (b1 != 0 && block_coded(b1)) { show_head(p, cond); show_branch_instruction(J_B + cond, next1); return (next == way_out) ? RETLAB : next; } #ifdef TARGET_HAS_COND_EXEC if (!usrdbg(DBG_VAR+DBG_LINE)) { int condb = Bpcc_No, lcondb = Bpcc_No, condb1 = Bpcc_No, lcondb1 = Bpcc_No; if (b != 0 && !block_coded(b)) { condb = lcondb = conditionalizable(b, cc_includelast, CondMax_Loop); if (condb == Bpcc_No) lcondb = conditionalizable(b, 0, CondMax_Loop); } if (b1 != 0 && !block_coded(b1) && block_single_exit(b1) && length((List *)blkusedfrom_(b1)) == next1_arcs) { condb1 = lcondb1 = block_preserves_cc(b1, cc_includelast, CondMax_Loop); if (condb1 == Bpcc_No) lcondb1 = block_preserves_cc(b1, 0, CondMax_Loop); } if (debugging(DEBUG_CG)) cc_msg("block %ld: next %ld (%d,%d) next1 %ld (%d,%d)\n", lab_xname_(blklab_(p)), lab_xname_(next), condb, lcondb, lab_xname_(next1), condb1, lcondb1); if (condb <= CondMax_Ordinary && condb1 <= CondMax_Ordinary && blknext_(b) == blknext_(b1)) { CommonInst *c = common_insts(b1, b); show_head(p, cond); show_n(ncommon, commonp, s); show_block_pair(cond, b1, b, c); return blknext_(b) != way_out ? blknext_(b) : (blkflags_(b) & blkflags_(b1) & BLK0EXIT) ? NOTALAB : RETLAB; } { bool show_b_cond = NO, show_b1_cond = NO, include_branch = YES; if (lcondb <= CondMax_Ordinary && blknext_(b) == next1) show_b_cond = YES, include_branch = NO; else if (lcondb1 <= CondMax_Ordinary && blknext_(b1) == next) show_b1_cond = YES, include_branch = NO; else if (condb <= CondMax_Loop && condb1 <= CondMax_Loop && blknest_(b) != blknest_(b1)) { if (debugging(DEBUG_CG)) cc_msg("nesting(b) %ld, nesting(b1) %ld\n", blknest_(b), blknest_(b1)); if (blknest_(b) > blknest_(b1)) show_b_cond = YES; else show_b1_cond = YES; } else if (condb <= CondMax_Ordinary && !successor_inline(b)) show_b_cond = YES; else if (condb1 <= CondMax_Ordinary && !successor_inline(b1)) show_b1_cond = YES; if (show_b_cond) { show_head(p, Q_NEGATE(cond)); show_n(ncommon, commonp, s); show_conditional_block(Q_NEGATE(cond), b, include_branch); return next1 == way_out ? RETLAB : next1; } if (show_b1_cond) { show_head(p, cond); show_n(ncommon, commonp, s); show_conditional_block(cond, b1, include_branch); return next == way_out ? RETLAB : next; } } } #endif if (b == 0) { show_head(p, Q_NEGATE(cond)); show_branch_instruction(J_B + Q_NEGATE(cond), RETLAB); return (next1 == way_out) ? RETLAB : next1; } if (b1 == 0) { show_head(p, cond); show_branch_instruction(J_B + cond, RETLAB); return (next == way_out) ? RETLAB : next; } if ((blkflags_(b) & BLKLIFTABLE) == lifted) { if ((blkflags_(b1) & BLKLIFTABLE) != lifted) { show_head(p, cond); show_n(ncommon, commonp, s); show_branch_instruction(J_B + cond, next1); return next; } } else if ((blkflags_(b1) & BLKLIFTABLE) == lifted) { show_head(p, Q_NEGATE(cond)); show_n(ncommon, commonp, s); show_branch_instruction(J_B + Q_NEGATE(cond), next); return next1; } #ifdef TARGET_HAS_SCCK /* The following code checks for two blocks which each have a single */ /* MOVK to the same register and the same successor block. */ /* Possible wish list: 1. SCCR to set r1 to 0 or r3, or do this by */ /* (SCCK -1; AND) if r1!=r3. 2. A macro for target_SCCK_able(n)?. */ if (block_single_entryexit(b) && block_single_entryexit(b1) && blknext_(b) == blknext_(b1) && blklength_(b) == 1 && blklength_(b1) == 1) { Icode *c = blkcode_(b), *c1 = blkcode_(b1); /* The next test: really remove_noops() should remove J_DEADBITS for */ /* loopopt vars which are removed. Also note that equality is that of */ /* virtregs, not real regs, but this is OK since both vregs are live. */ if ((c->op & ~J_DEAD_R2) == J_MOVK && (c1->op & ~J_DEAD_R2) == J_MOVK && c->r1.r == c1->r1.r) { Icode ic; if (c->r3.i == 0) { INIT_IC (ic, J_SCCK+cond); ic.r1 = c->r1; ic.r3 = c1->r3; show_head(p, cond); expand_jop_macro(&ic); } else if (c1->r3.i == 0) { INIT_IC (ic, J_SCCK+Q_NEGATE(cond)); ic.r1 = c->r1; ic.r3 = c->r3; show_head(p, Q_NEGATE(cond)); expand_jop_macro(&ic); } /* This hits cases like x?4:5. It probably saves space (BC;MOVK;B;MOVK) */ /* vs (SCC;ADDK) and often time too. */ else { INIT_IC (ic, J_SCCK+cond); show_head(p, cond); ic.r1 = c->r1; ic.r3 = c1->r3.i - c->r3.i; expand_jop_macro(&ic); ic.op = J_ADDK; ic.r1 = ic.r2 = c->r1; ic.r3 = c->r3; expand_jop_macro(&ic); } /* The next line is unfortunate: we have to do this to avoid the */ /* block getting spuriously displayed again later. It therefore */ /* requires the block_single_entryexit() condition. */ blkflags_(b) |= BLKCODED, blkflags_(b1) |= BLKCODED; return blknext_(b) == way_out ? RETLAB : blknext_(b); } /* Other cases worth searching for? */ } #endif /* * Hack by RCC 24/02/88. If both the destinations are not yet coded, * and one of them is the block we would code next, it can pay to do * the unconditional branch to the earlier one. * * There ought to be a quicker way to find out which of the * destinations is likely to be coded first. */ { BlockHead *x = b; /* unconditional branch destination */ do { x = blkdown_(x); if (x == NULL) /* conditional dest is after uncond dest: swap */ { show_head(p, Q_NEGATE(cond)); show_n(ncommon, commonp, s); show_branch_instruction(J_B + Q_NEGATE(cond), next); return (is_exit_label(next1)) ? RETLAB : next1; } } while (x != b1); } /* Here we drop through to the ordinary simple case */ if (blknext_(b1) == next && ncommon == 0) { show_head(p, Q_NEGATE(cond)); show_branch_instruction(J_B + Q_NEGATE(cond), next); return next1; } show_head(p, cond); show_n(ncommon, commonp, s); show_branch_instruction(J_B + cond, next1); return next; } } #endif /* TARGET_IS_NULL */ static void refblock(LabelNumber *ll, BlockHead *from, BlockList *reuse) { if (!is_exit_label(ll)) { BlockList *bl; procflags |= blkflags_(ll->block); /* I make, in the blkusedfrom_() entry in b, a list of all blocks that */ /* reference it. This list will be used when cross-jump optimizing. */ /* NB the top block gets a NULL in its used-from list. I will only allow */ /* an ancestor to appear once in blkusedfrom_() even if there are many */ /* routes (e.g. because of switchon tables) from one block to another. */ for (bl = blkusedfrom_(ll->block); bl != NULL; bl = bl->blklstcdr) if (bl->blklstcar == from) return; if (reuse == NULL) reuse = (BlockList*) BindAlloc(sizeof(BlockList)); reuse->blklstcar = from; reuse->blklstcdr = blkusedfrom_(ll->block); blkusedfrom_(ll->block) = reuse; } /* else syserr("refblock"); really happens -- why? */ } #ifndef TARGET_IS_NULL static BlockList *unrefblock(BlockHead *ll, BlockHead *from) /* At present block ll has from recorded as one of its ancestors - kill this */ /* Return the dead cell for refblock(). */ { BlockList **lvbl = &(blkusedfrom_(ll)); BlockList *bl; while ((bl = *lvbl) != NULL) if (bl->blklstcar == from) { *lvbl = bl->blklstcdr; return bl; } else lvbl = &(bl->blklstcdr); syserr(syserr_unrefblock); return 0; } #endif static void setstackoffset(Binder *b) { /* real stack variable -- change scope to stack offset */ bindstg_(b) &= ~b_bindaddrlist, bindaddr_(b) = BINDADDR_LOC | size_of_binders(bindbl_(b)); } static int32 remove_noops(Icode *c, int32 len) { int32 i; /* besides normalising noops to J_NOOP, the following code also turns */ /* J_SETSPGOTO into J_SETSP - essentially a 2nd pass for goto/labels. */ /* It also turns the addresses of locals to 'stack' form from */ /* environment form, thus completing auto and register allocation. */ /* Ultimately we should remove all _STACKREF jopcodes here too. ??? */ /* J_NOOP's are now completely removed. */ for (i=0;i<len;i++) { J_OPCODE op = c[i].op; if (uses_stack(op)) { Binder *bb = c[i].r3.b; if (bindstg_(bb) & b_bindaddrlist) setstackoffset(bb); else if (bindstg_(bb) & b_pseudonym) { Binder *b = bindsuper_(bb)->binder; if (bindstg_(b) & b_bindaddrlist) setstackoffset(b); bindstg_(bb) &= ~b_pseudonym; bindaddr_(bb) = bindaddr_(b); } if (target_stack_moves_once && (bindaddr_(bb) & BINDADDR_MASK) == BINDADDR_NEWARG) { /* Convert an 'actual in new frame' address into a local. */ /* AM, Nov89: this code is somewhat in flux. */ unsigned32 m = bindaddr_(bb) & ~BINDADDR_MASK; /* @@@ see health warning in expand_jop_macro() if NARGREGS != 0. */ if (m < 4*NARGREGS) cc_warn(warn_untrustable, currentfunction.symstr); /* syserr() */ bindaddr_(bb) = BINDADDR_LOC | (greatest_stackdepth - (m - 4*NARGREGS)); } } switch (op & J_TABLE_BITS) { #if defined(ARM_INLINE_ASSEMBLER) || defined(THUMB_INLINE_ASSEMBLER) case J_BL: Inline_RealUse(c[i].r1.b); break; #endif case J_CALLK: Inline_RealUse(c[i].r3.b); /* and fall through */ case J_OPSYSK: /* The 'call can be optimised out' info has now passed its 'use by' date */ case J_CALLR: c[i].r2.i &= ~K_PURE; break; case J_SETSPGOTO: c[i].r2.i = size_of_binders(c[i].r2.bl); { /* The block this branch is to may have disappeared (because it was * empty). If so, the scan to turn bind lists to frame sizes won't * have processed it. We COULD look for SETSPGOTOs in branch_chain, * but that seems like overkill. Instead, blocks which have had * their bind lists converted to a frame size are marked. */ BlockHead *b = (c[i].r3.l)->block; c[i].r3.i = (blkflags_(b) & BLKSTACKI) ? blkstacki_(b) : size_of_binders(blkstack_(b)); } c[i].op = J_SETSP; i--; break; /* retry */ /*case J_SETSPENV:*/ /* already removed */ case J_SETSP: if (c[i].r2.i == c[i].r3.i) c[i].op = J_NOOP; break; case J_LDRV: case J_LDRLV: case J_LDRFV: case J_LDRDV: case J_STRV: case J_STRLV: case J_STRFV: case J_STRDV: { VRegnum r1 = c[i].r1.r; Binder *bb = c[i].r3.b; VRegnum r3 = bindxx_(bb); if (r3 != GAP && isany_realreg_(register_number(r3))) { if (register_number(r1) == register_number(r3)) c[i].op = J_NOOP; else if (loads_r1(op)) { /* LDRV can have J_DEAD_R3 set */ c[i].op = J_XtoY(op&~(J_ALIGNMENT|J_BASEALIGN4), J_LDRV, J_MOVR); c[i].r1.r = r1; c[i].r2.r = GAP; c[i].r3.r = r3; } else { c [i].op = J_XtoY(op&~(J_DEADBITS|J_ALIGNMENT|J_BASEALIGN4), J_STRV, J_MOVR) | (op & J_DEAD_R1 ? J_DEAD_R3 : 0); c[i].r1.r = r3; c[i].r2.r = GAP; c[i].r3.r = r1; /* but STRxV may have J_DEAD_R1, which we need to take care not to discard in turning it into a MOV. */ } } else bindxx_(bb) = GAP; } break; case J_LDRV1: case J_LDRLV1: case J_LDRFV1:case J_LDRDV1: /* as LDRV but always uses the stack value. Used at head of fn */ /* Should only be used to load from +ve offset from FP. */ /* Except that leaf procedures may not have set up FP! */ { VRegnum r1 = c[i].r1.r; if (!isany_realreg_(register_number(r1))) c[i].op = J_NOOP; /* Ignore unless this var got a real reg */ } break; case J_CMPK: /* I.e. the pseudo_uses_r1() ops */ /* Note that if the r1 field holds a real register then the opcode */ /* should be treated as a comparison against that. */ { VRegnum r1 = c[i].r1.r; VRegnum r2 = c[i].r2.r; /* Fix up deadbits (WGD) */ J_OPCODE newop = (op&~(J_DEAD_R1|J_DEAD_R3)) ^ (J_CMPK ^ J_CMPR); if (op&J_DEAD_R1) newop |= J_DEAD_R3; if (r1!=GAP && isany_realreg_(register_number(r1))) { c[i].op = newop; c[i].r1.r = GAP; c[i].r2.r = r2; c[i].r3.r = r1; } else { c[i].r1.r = GAP;/* normalise for cross jumping */ c[i].op &= ~J_DEAD_R1; } } break; case J_STRING: if (feature & FEATURE_WR_STR_LITS) procflags |= PROC_USESADCONS; break; case J_CASEBRANCH: procflags |= PROC_CASEBRANCH; break; case J_ADCOND: case J_ADCONF: case J_ADCONLL: #ifdef TARGET_FP_LITS_FROM_MEMORY procflags |= PROC_USESADCONS; #endif goto MaybeLoopOptRef; /* the next three cases deal with lifting adcons/constants out of loops */ case J_ADCON: { Binder *b = c[i].r3.b; if (bindstg_(b) & b_fnconst) Inline_RealUse(b); if (!(bindstg_(b) & u_constdata)) procflags |= PROC_USESADCONS; } /* and fall through */ MaybeLoopOptRef: case J_ADCONV: case J_MOVK: /* I.e. the pseudo_uses_r2() ops */ /* r1 may still be a virtual register (corresponding to an optimisation */ /* that has been spilled because of lack of real registers). In that */ /* case I can just ignore this instruction. */ { VRegnum r1 = c[i].r1.r; if (isany_realreg_(register_number(r1))) { VRegnum r2 = c[i].r2.r; J_OPCODE newop = (op&J_DEAD_R2) ? J_MOVR|J_DEAD_R3 : J_MOVR; /* The following funny treatment of MOVK helps loop optimisation. */ /* If the r2 field is a real register (neither GAP nor an unallocated */ /* virtual register) I can turn this into a MOVR r1,r2 instruction. */ /* AM: (because loopopt.c has inserted a real register) */ if (r2!=GAP && isany_realreg_(register_number(r2))) { if (register_number(r1) != register_number(r2)) { c[i].op = newop; c[i].r1.r = r1; c[i].r2.r = GAP; c[i].r3.r = r2; } else c[i].op = J_NOOP; } else c[i].r2.r = GAP;/* normalise for cross jumping */ } else c[i].op = J_NOOP; c[i].op &= ~J_DEAD_R2; } break; /* AM: there seems no rationale behind which insts have the realreg test! */ case J_MOVR: case J_MOVDR: case J_MOVFR: #ifdef TARGET_IS_ARM /* see regalloc.c, armgen.c */ case J_MOVFDR: /* see regalloc.c, armgen.c */ #endif /* optimize away moves from a register to itself. */ /* Also lose moves into virtual registers (which may be a side- */ /* effect of the optimiser trying to allocate local vars to regs */ if (!isany_realreg_(register_number(c[i].r1.r)) || register_number(c[i].r1.r)==register_number(c[i].r3.r)) c[i].op = J_NOOP; break; case J_MOVIFR: case J_MOVIDR: if (!isany_realreg_(register_number(c[i].r1.r))) c[i].op = J_NOOP; break; case J_INIT: case J_INITF: case J_INITD: /* These will be left if there is a potentially uninitialized variable */ case J_NOOP: /* Flatten condition mask if there was one */ #ifndef TARGET_GEN_NEEDS_VOLATILE_INFO case J_USE: case J_USEF: case J_USED: case J_VSTORE:/* @@@ AM thinks VSTORE is a bit in a JOP store, not an opcode */ #endif /* These help ensure that references to volatile things are not */ /* optimized out of existence */ /* The local code generator needs them for similar reasons, so not */ /* optimised out */ c[i].op = J_NOOP; break; default: break; } } { int32 n; for (n = i = 0; i < len; i++) /* * The next line exhibits a degree of extreme (unreasonable) caution - it * tests i!=n to prevent a structure assignment between overlapping structs * even in the case thet the overlap is total. ANSI would permit the test * to be missed out but we are super-conservative! */ if (c[i].op != J_NOOP) { if (i != n) c[n] = c[i]; n++; } return n; } } #ifndef TARGET_IS_NULL /* Cross jumping optimisation routines: note that cross jumping is here */ /* implemented as a rooted (in way_out) tree isomorphism problem. */ /* The tree is the backward chains of blocks in blkusedfrom_(). */ /* J_TAILCALLKs (blocks marked with BLK0EXIT) are also predecessors of */ /* way_out, so now handled properly. */ /* This means that (inter alia) it can never identify loops. */ /* The full graph isomorphism problem is much more expensive and probably */ /* does not gain significantly more in real code. We do not intend to */ /* change this implementation in the near future! */ /* Note that handling conditional exits (i.e. DAG isomorphism) is */ /* probably not much harder -- see comments below "only merge if..." */ static bool identify_blocks(BlockHead *x1, BlockHead *x2, BlockHead *q) { /* blocks x1 and x2 have identical contents - redirect all references to */ /* x2 so that they point to x1. q is the only successor of both x1 and x2 */ /* x2 is not the top block (i.e. the place where the procedure will be */ /* entered), and so that is all right, isn't it. */ BlockList *x2src = blkusedfrom_(x2); LabelNumber *l1 = blklab_(x1), *l2 = blklab_(x2); bool maybenewemptyblock = YES; /* first delete x2 from the ancestors of q and kill x2 then swing the */ /* chain of ancestors of x2 to x1. */ unrefblock(q, x2); blkflags_(x2) &= ~BLKALIVE; blkusedfrom_(x2) = (BlockList*) DUFF_ADDR; /* checks! */ blkcode_(x2) = (Icode*) DUFF_ADDR; /* checks! */ while (x2src != NULL) { BlockList *rplac = x2src; BlockHead *p = x2src->blklstcar; x2src = x2src->blklstcdr; refblock(l1, p, rplac); /* re-use cell rplac */ if (blkflags_(p) & BLKSWITCH) { int32 i; LabelNumber **tab = blktable_(p); for (i = 0; i < blktabsize_(p); i++) if (tab[i] == l2) tab[i] = l1; } else { /* AM: blknext_() is only valid if !BLK0EXIT & !BLKSWITCH */ /* NB blkflags_(p) cannot have BLK0EXIT and be an ancestor! */ if (blknext_(p) == l2) blknext_(p) = l1; /* redirect main exit */ if (blkflags_(p) & BLK2EXIT) { if (blknext1_(p) == l2) blknext1_(p) = l1; if (blknext_(p) == blknext1_(p)) maybenewemptyblock = YES; } } } return maybenewemptyblock; } static void truncate_block(BlockHead *x2, int32 i2, BlockHead *x1, BlockHead *p) { /* Here block x2 must be truncated to have new length i2, and its exit */ /* must be rewritten as going to x1. */ /* Due to the calls to truncate_block, we know that x2 has a single */ /* successor (p) and so we only have to swing one pointer x2-->p to x1-->p */ /* However, note that p may have multiple ancestors. */ blklength_(x2) = i2; blknext_(x2) = blklab_(x1); blkflags_(x2) &= ~BLK0EXIT; refblock(blklab_(x1), x2, unrefblock(p, x2)); } static void zip_blocks(BlockHead *x1, int32 i1, BlockHead *x2, int32 i2, BlockHead *p) { BlockHead *newbh; LabelNumber *lab = nextlabel(); lab->block = newbh = newblock(lab, NULL); blkstacki_(newbh) = adjusted_stack_size(blkstacki_(x1), blkcode_(x1), i1); blklength_(newbh) = blklength_(x1) - i1; blkcode_(newbh) = &(blkcode_(x1)[i1]); blknext_(newbh) = blklab_(p); blkdebenv_(newbh) = blkdebenv_(x1); /* maybe */ /* The next line is a slight lie -- e.g. not BLKCALL but does not matter */ blkflags_(newbh) = BLKALIVE | BLKSTACKI | (blkflags_(x1) & BLK0EXIT); blklength_(x1) = i1; blknext_(x1) = lab; blkflags_(x1) &= ~BLK0EXIT; blklength_(x2) = i2; blknext_(x2) = lab; blkflags_(x2) &= ~BLK0EXIT; refblock(lab, x1, unrefblock(p, x1)); refblock(lab, x2, unrefblock(p, x2)); refblock(blklab_(p), newbh, 0); } static bool cross_jump_optimize(void) { BlockHead *p; bool another_pass_needed; bool maybenewemptyblocks = NO; if (!crossjump_enabled || usrdbg(DBG_LINE+DBG_VAR)) return NO; do { another_pass_needed = NO; for (p = top_block; p != NULL; p = blkdown_(p)) if (blkflags_(p) & BLKALIVE) { BlockList *predecessors; BlockList *p1, *p2; restart_scanning_block_p: predecessors = blkusedfrom_(p); for (p1 = predecessors; p1!=NULL; p1 = p1->blklstcdr) for (p2 = p1->blklstcdr; p2!=NULL; p2 = p2->blklstcdr) { BlockHead *x1 = p1->blklstcar, *x2 = p2->blklstcar; if (x1 != x2 && /* probably never happens, but be careful */ x1 != NULL && /* null block has nothing in common ... */ x2 != NULL && /* ... with anything */ /* (null block is ancestor of top_block) */ /* only merge if parents' exits were simple */ (blkflags_(x1) & (BLKSWITCH | BLK2EXIT)) == 0 && (blkflags_(x2) & (BLKSWITCH | BLK2EXIT)) == 0) { int32 ncommon = 0; int32 i1 = blklength_(x1), i2 = blklength_(x2); Icode *c1 = blkcode_(x1), *c2 = blkcode_(x2); /* Here I scan two ancestors of p from the tail-end looking for */ /* equivalent instructions. I only do this if the ancestors both */ /* have just simple exits (no branch tables or conditional jumps). */ /* J_NOOP's have already been removed. */ for (; i1 > 0 && i2 > 0; i1--, i2--, ncommon++) if (!same_instruction(&c1[i1-1], &c2[i2-1])) break; if (ncommon != 0) { if (i1 == 0) { if (i2 == 0) /* At present the top block can not be an exact match for any other block */ /* because it (and it alone) as an ENTER opcode in it. However I act with */ /* caution here in case things change in the future. */ { maybenewemptyblocks = (x2 != top_block) ? identify_blocks(x1, x2, p) : identify_blocks(x2, x1, p); another_pass_needed = YES; } else { truncate_block(x2, i2, x1, p); another_pass_needed = YES; } } else if (i2 == 0) { truncate_block(x1, i1, x2, p); another_pass_needed = YES; } else { zip_blocks(x1, i1, x2, i2, p); another_pass_needed = YES; /* ????? needed in allcases? */ } /* The above procedures may well alter the chaining in blkusedfrom_(p), */ /* the ancestor list for p, so to */ /* keep things as simple as I can (albeit with some loss of speed, but */ /* that only when optimisations are actually being found), I leap right */ /* out from the middle of a load of nested loops here and start scanning */ /* the ancestors of p all over again. I think that pretty well any other */ /* construction here will really be a stylistically ugly as the goto that */ /* I use - maybe I could demand that identify_blocks() etc guaranteed not */ /* to have bad interactions with the iteration over ancestor-pairs, but */ /* that seems like the wilfull design of fragile code. */ goto restart_scanning_block_p; } } } } } while (another_pass_needed); if (debugging(DEBUG_CG)) { cc_msg("After crossjump optimisation (branch-chain %srequested)", maybenewemptyblocks ? "" : "not "); flowgraf_print("", YES); } return maybenewemptyblocks; } #endif /* TARGET_IS_NULL */ static void kill_unreachable_blocks(void) { BlockHead *b = top_block; blkflags_(b) &= ~BLKALIVE; /* top_block MUST have been alive */ while (b != bottom_block) { BlockHead *next = blkdown_(b); int32 ff = blkflags_(next); /* only bottom_block has empty down */ if (ff & BLKALIVE) { blkflags_(next) = ff & ~BLKALIVE; b = next; } else if (usrdbg(DBG_LINE+DBG_VAR) && !usrdbg(DBG_OPT_DEAD)) b = next; else if (next == bottom_block) /* bottom_block was unreachable */ { blkdown_(b) = NULL; bottom_block = b; } else /* patch out a dead block */ { next = blkdown_(next); blkdown_(b) = next; blkup_(next) = b; } } } /* exported ... */ void lose_dead_code(void) { /* exported to cg.c to call before register allocation */ /* cf branch_chain in flowgraf.c, which will be needed later */ /* AM: think about amalgamating this with branch chain() */ (void)branch_chain(blklab_(top_block), 0); kill_unreachable_blocks(); /* (just to unset BLKALIVE if usrdbg(..)) */ } #ifdef TARGET_HAS_SAVE /* If the target local codegenerator has separable entry to function (J_ENTER) * and save callee-save registers & setup frame (J_SAVE) operations, try to * move the J_SAVE into the body of the function past conditional exits (to give * faster fast exit paths). This is done after register allocation, so it may * fail when better allocation would allow it to succeed. */ typedef struct RAList RAList; struct RAList { RAList *cdr; /* RealRegister */ IPtr r1, r2; /* int32 */ IPtr argregdead; }; #define mkRAList(cdr, r1, r2, dead) (RAList *)syn_list4(cdr, r1, r2, dead) #define BlockList_NDelete(b, bl) ((BlockList *)generic_ndelete((IPtr)b, (List *)bl)) static BlockList *BlockList_Insert(BlockHead *b, BlockList *bl) { return (generic_member((IPtr)b, (List *)bl)) ? bl : mkBlockList(bl, b); } static BlockList *BlockList_Union(BlockList *bl1, BlockList *bl2) { for (; bl2 != NULL; bl2 = bl2->blklstcdr) bl1 = BlockList_Insert(bl2->blklstcar, bl1); return bl1; } static BlockList *BlockList_Difference(BlockList *bl1, BlockList *bl2) { for (; bl2 != NULL; bl2 = bl2->blklstcdr) bl1 = BlockList_NDelete(bl2->blklstcar, bl1); return bl1; } static RealRegister ArgRegister(RealRegister r, RAList *ra) { r = register_number(r); for (; ra != NULL; ra = cdr_(ra)) if (r == ra->r1) return ra->r2; return r; } static RealRegister VarRegister(RealRegister r, RAList *ra) { r = register_number(r); for (; ra != NULL; ra = cdr_(ra)) if (r == ra->r2) return ra->argregdead ? ra->r1 : r; return r; } static BlockHead *ts_blockbetween(BlockHead *before, BlockHead *after) { /* Insert a block between <before> and <after>, copying information from * <before>. Keep blkusedfrom_ fields up to date (insertblockbetween doesn't * because it's also used from CSE before the fields are set up). */ BlockHead *b = insertblockbetween(before, after, YES); blkstacki_(b) = blkstacki_(before); blkdebenv_(b) = blkdebenv_(before); blkexenv_(b) = blkexenv_(before); blkflags_(b) = blkflags_(before); refblock(blklab_(after), b, unrefblock(after, before)); refblock(blklab_(b), before, NULL); return b; } static void try_shrinkwrap(void) { BlockHead *top = top_block, *next = blknext_(top)->block; BlockList *lifted = NULL; int32 argdesc; RAList *copies = NULL; bool changed = NO, oktolift = YES; BlockHead *saveblock = ts_blockbetween(top, next); { /* Introduce the SAVE jopcode, and set up a translation between argument * registers and the VRegisters to which they've been moved. */ Icode *newic = (Icode *)BindAlloc(sizeof(Icode)); Icode *ic = blkcode_(top); int32 n = blklength_(top); *newic = *ic; ic->op = J_SAVE; argdesc = ic->r3.i; blkcode_(saveblock) = ic; blklength_(saveblock) = n; blkcode_(top) = newic; blklength_(top) = 1; for (; --n >= 0; ic++) if ((ic->op & J_TABLE_BITS) == J_MOVR) copies = mkRAList(copies, register_number(ic->r1.r), register_number(ic->r3.r), ic->op & J_DEAD_R3); } if (!(procauxflags & bitoffnaux_(s_irq)) && !(var_cc_private_flags & 262144) && !usrdbg(DBG_ANY) && block_single_entry(next)) { /* Attempt to find a set of blocks after <saveblock> which can be moved * before it. The set must contain at least one return (or there's no point * to the motion), may have predecessors only in the set plus <saveblock>, * and may have successors only in the set plus returns plus one other * block (which will become the successor of <saveblock>). Blocks in the set * may contain no calls, nor write any callee-save register nor read any * register set up in <saveblock> (except those which are copies of argument * registers). In addition, blocks which are not single-exit with successor * way_out may write no argument register. */ BlockHead *p = top; RealRegSet maynotwrite, maynotread, argregset, resregset, calleesaveregset; Icode *ic = blkcode_(saveblock); int32 i, n = blklength_(saveblock); memclr(&maynotread, sizeof(RealRegSet)); memclr(&calleesaveregset, sizeof(RealRegSet)); memclr(&argregset, sizeof(RealRegSet)); memclr(&resregset, sizeof(RealRegSet)); for (i = 0; i < k_intregs_(argdesc); i++) augment_RealRegSet(&argregset, R_P1+i); for (i = 0; i < k_fltregs_(argdesc); i++) augment_RealRegSet(&argregset, R_FP1+i); for (i = 0; i < NVARREGS; i++) augment_RealRegSet(&calleesaveregset, R_V1+i); for (i = 0; i < NFLTVARREGS; i++) augment_RealRegSet(&calleesaveregset, R_FV1+i); #ifdef TARGET_IS_ARM /* Not preserved by J_SAVE for some calling standards. Holds value on function entry for reentrant APCS. FixedRegisterUse should tell us this. */ if (config & CONFIG_REENTRANT_CODE) augment_RealRegSet(&calleesaveregset, R_IP); #endif #ifndef TARGET_STACKS_LINK augment_RealRegSet(&calleesaveregset, R_LR); #endif if (currentfunction.baseresultreg != GAP) { augment_RealRegSet(&resregset, currentfunction.baseresultreg); for (i = 1; i < currentfunction.nresultregs; i++) augment_RealRegSet(&resregset, currentfunction.baseresultreg+i); } for (; --n >= 0; ic++) { /* Registers set in <saveblock> won't be accessible to code moved before it. * I think these can actually only be registers to which arguments are * copied, so this is redundant (they'll be translated back to the argument * register numbers via the <copies> list), but this code is cautious in case * anything else gets appended to the block. */ if (loads_r1(ic->op)) augment_RealRegSet(&maynotread, register_number(ic->r1.r)); if (loads_r2(ic->op)) augment_RealRegSet(&maynotread, register_number(ic->r2.r)); if (loads_r1(ic->op) && member_RealRegSet(&resregset, register_number(ic->r1.r))) { oktolift = NO; break; } if (loads_r2(ic->op) && member_RealRegSet(&resregset, register_number(ic->r2.r))) { oktolift = NO; break; } } for (; p != NULL; p = blkdown_(p)) blkflags_(p) &= ~BLKLIFTABLE; if (oktolift) for (p = next; p != NULL; p = blkdown_(p)) { if (blkflags_(p) & (BLKCALL | BLKSWITCH)) { break; } else if (p != way_out->block && (blkflags_(p) & BLKALIVE)) { /* Ignore blocks removed by cross-jumping (not BLKALIVE). Cross-jumping * also may add blocks after the way_out block, hence the explicit test * for it (it is the only block for which blknext_() doesn't label a real * block). */ bool terminal = !(blkflags_(p) & BLK2EXIT) && blknext_(p) == way_out; RealRegSet mnr = maynotread; if (terminal) maynotwrite = calleesaveregset; else union_RealRegSet(&maynotwrite, &argregset, &calleesaveregset); ic = blkcode_(p); n = blklength_(p); for (; --n >= 0; ic++) { J_OPCODE op = ic->op; VRegInt r1 = ic->r1, r2 = ic->r2, r3 = ic->r3, r4 = ic->r4; RealRegSet corrupt; RealRegUse reg; if ((op == J_TAILCALLK || op == J_TAILCALLR) && k_argwords_(r2.i) > 0) /* The arguments may come either from code in blocks being considered * for lifting, or from copies performed on entry (which if the block * is lifted, won't be executed). To handle this properly, we need to * able to distinguish the two cases and in the latter replicate the * moves here. It's a lot of work to do this in general, so our first * attempt is not to bother. */ break; RealRegisterUse(ic, &reg); union_RealRegSet(&corrupt, &reg.c_in, &reg.c_out); if (uses_r1(op)) r1.r = ArgRegister(r1.r, copies); if (uses_r2(op)) r2.r = ArgRegister(r2.r, copies); if (uses_r3(op)) r3.r = ArgRegister(r3.r, copies); if (uses_r4(op)) r4.r = ArgRegister(r4.r, copies); if (uses_stack(op) || intersect_RealRegSet(&corrupt, &maynotwrite, &corrupt) || (loads_r1(op) && member_RealRegSet(&maynotwrite, r1.r)) || (loads_r2(op) && member_RealRegSet(&maynotwrite, r2.r)) || (reads_r1(op) && member_RealRegSet(&mnr, r1.r)) || (reads_r2(op) && member_RealRegSet(&mnr, r2.r)) || (reads_r3(op) && member_RealRegSet(&mnr, r3.r)) || (reads_r4(op) && member_RealRegSet(&mnr, r4.r))) break; if (terminal) { /* exit paths are allowed to write result registers, but once written * they may not be read (mechanism defect: I can't distinguish between * reading the VReg copy, which definitely isn't allowed, and reading * the value written here, which would be OK. I doubt it matters. */ if (loads_r1(op) && member_RealRegSet(&argregset, r1.r)) augment_RealRegSet(&mnr, r1.r); if (loads_r2(op) && member_RealRegSet(&argregset, r2.r)) augment_RealRegSet(&mnr, r2.r); } } if (n >= 0) break; blkflags_(p) |= BLKLIFTABLE; } } if (p != NULL) { /* (p == NULL means the SAVE is going to have no effect, so there's no sense * trying to move code before it) */ BlockList *successors = NULL, *predecessors = NULL, *liftable = NULL; bool atleastoneexit = NO; for (p = next; p != NULL; p = blkdown_(p)) if (blkflags_(p) & BLKLIFTABLE) { liftable = BlockList_Insert(p, liftable); if (blknext_(p) == way_out) atleastoneexit = YES; else successors = BlockList_Insert(blknext_(p)->block, successors); if (blkflags_(p) & BLK2EXIT) { if (blknext1_(p) == way_out) atleastoneexit = YES; else successors = BlockList_Insert(blknext1_(p)->block, successors); } predecessors = BlockList_Union(predecessors, blkusedfrom_(p)); } predecessors = BlockList_Difference(predecessors, liftable); successors = BlockList_Difference(successors, liftable); if (atleastoneexit && predecessors != NULL && predecessors->blklstcdr == NULL && predecessors->blklstcar == saveblock && /* really, <predecessors> must include <saveblock>, so the checks * besides that its length is 1 are redundant */ successors != NULL && successors->blklstcdr == NULL) { /* The set <liftable> can safely be moved before <saveblock>, with all * occurrences of callee-save registers replaced by the corresponding * argument register. */ BlockList *bl; BlockHead *insertbefore = successors->blklstcar; LabelNumber *l_saveblock = blklab_(saveblock), *l_insertbefore = blklab_(insertbefore), *l_inserted = blklab_(next); int32 s1 = blkstacki_(next), s2 = blkstacki_(insertbefore); lifted = liftable; blknext_(top) = blklab_(next); refblock(l_inserted, top, unrefblock(saveblock, top)); blknext_(saveblock) = l_insertbefore; refblock(l_insertbefore, saveblock, unrefblock(next, saveblock)); for (bl = liftable; bl != NULL; bl = bl->blklstcdr) { BlockHead *b = bl->blklstcar; Icode *ic_in = blkcode_(b), *ic_out = ic_in; n = blklength_(b); blkstacki_(b) = 0; for (; --n >= 0; ic_in++) { J_OPCODE op = ic_in->op; if (ic_in != ic_out) *ic_out = *ic_in; if (reads_r1(op)) ic_out->r1.r = ArgRegister(ic_out->r1.r, copies); if (reads_r2(op)) ic_out->r2.r = ArgRegister(ic_out->r2.r, copies); if (reads_r3(op)) ic_out->r3.r = ArgRegister(ic_out->r3.r, copies); if (reads_r4(op)) ic_out->r4.r = ArgRegister(ic_out->r4.r, copies); if (op != J_SETSP) ic_out++; else blklength_(b)--; } if (blknext_(b) == l_insertbefore) { blknext_(b) = l_saveblock; refblock(l_saveblock, b, unrefblock(insertbefore, b)); } if ((blkflags_(b) & BLK2EXIT) && blknext1_(b) == l_insertbefore) { blknext1_(b) = l_saveblock; refblock(l_saveblock, b, unrefblock(insertbefore, b)); } } if (s1 != s2) { BlockHead *b = ts_blockbetween(saveblock, insertbefore); Icode *ic = (Icode *)BindAlloc(sizeof(Icode)); INIT_IC(*ic, J_SETSP); ic->r2.i = s1; ic->r3.i = s2; blkstacki_(b) = s1; blklength_(b) = 1; blkcode_(b) = ic; } changed = YES; } } if (lifted == NULL) for (p = next; p != NULL; p = blkdown_(p)) blkflags_(p) &= ~BLKLIFTABLE; else blkflags_(top_block) |= BLKLIFTABLE; } /* Now follows code to turn direct tail recursion into a loop. Of course, the * call has already turned into a tailcall, but we can do better by omitting * the need to restore saved registers from the frame here and by branching to * after the save instruction. We may be able to do better still by writing * arguments to VRegisters not the argument registers and skipping the copy * from argument to VRegister on entry. This could be done as source-to-source * translation, but this would miss calls which become tail recursive only by * dead code elimination, and would preclude shifting fast exit code before * the save. * Code moved before the save must be duplicated here, so we limit severely * what it can be (just one block permitted: a number of jopcodes might be * more sensible). */ if (!(var_cc_private_flags & 524288) && #ifdef TARGET_FP_ARGS_IN_FP_REGS k_fltregs_(argdesc) == 0 && #endif length((List *)copies) == k_argwords_(argdesc) && (lifted == NULL || lifted->blklstcdr == NULL)) { /* First create places for tail-recursion branches to go to: one just after * the SAVE jopcode, and one after all copying of argument registers to * VRegisters which leave the argument register dead. For the second case, * the copies need to be reordered in general. (The two destinations are * tailreclab_argsinaregs and tailreclab_argsinvregs; the second may be * null). */ int32 nargs = k_argwords_(argdesc); BlockList *exits = blkusedfrom_(way_out->block); LabelNumber *tailreclab_argsinaregs = NULL, *tailreclab_argsinvregs = NULL; BlockHead *inserted = lifted == NULL ? NULL : lifted->blklstcar; BlockHead *next = blknext_(saveblock)->block; if (blklength_(saveblock) == 1) tailreclab_argsinaregs = blklab_(next); else { BlockHead *p = ts_blockbetween(saveblock, next); Icode *ic = blkcode_(saveblock); int32 n = blklength_(saveblock); tailreclab_argsinaregs = blklab_(p); blkcode_(p) = ++ic; blklength_(p) = --n; blklength_(saveblock) = 1; { int32 ndead = 0; RAList *cp = copies; for (; cp != NULL; cp = cdr_(cp)) if (cp->argregdead) ndead++; if (ndead > 0) { if (ndead == n) tailreclab_argsinvregs = blklab_(next); else { BlockHead *q = ts_blockbetween(p, next); tailreclab_argsinvregs = blklab_(q); { int32 i, j; for (cp = copies, i = j = n; --i >= 0; ) { if ((ic[i].op & J_TABLE_BITS) == J_MOVR && register_number(ic[i].r1.r) == cp->r1 && ic[i].r3.r == cp->r2) { if (!cp->argregdead) { if (--j != i) ic[j] = ic[i]; } cp = cdr_(cp); } else if (--j != i) ic[j] = ic[i]; } copies = (RAList *)dreverse((List *)copies); for (cp = copies, i = 0; cp != NULL; cp = cdr_(cp)) if (cp->argregdead) { ic[i].op = J_MOVR + J_DEAD_R3; ic[i].r1.r = cp->r1; ic[i].r2.r = GAP; ic[i].r3.r = cp->r2; i++; } blkcode_(q) = ic + ndead; blklength_(q) = n - ndead; blklength_(p) = ndead; nargs = ndead; } } } } } for (; exits != NULL; exits = exits->blklstcdr) { BlockHead *b = exits->blklstcar; Icode *ic = blkcode_(b); int32 i, n = blklength_(b); if (n > 0 && (ic[n-1].op & J_TABLE_BITS) == J_TAILCALLK && bindsym_(ic[n-1].r3.b) == currentfunction.symstr) { LabelNumber **nextp; LabelNumber *dest = tailreclab_argsinaregs; blklength_(b) = --n; unrefblock(way_out->block, b); blkflags_(b) &= ~BLK0EXIT; changed = YES; if (inserted == NULL) nextp = &blknext_(b); else { BlockHead *q = insertblockbetween(b, way_out->block, YES); size_t size = (size_t)blklength_(inserted) * sizeof(Icode); Icode *ic = (Icode *)BindAlloc(size); memcpy(ic, blkcode_(inserted), size); blklength_(q) = blklength_(inserted); blkcode_(q) = ic; blkflags_(q) = blkflags_(inserted); blkstacki_(q) = blkstacki_(inserted); blkdebenv_(q) = blkdebenv_(inserted); blkexenv_(q) = blkexenv_(inserted); if (blknext_(inserted) == way_out) { blknext_(q) = way_out; nextp = &blknext1_(q); } else { blknext1_(q) = way_out; nextp = &blknext_(q); } refblock(blklab_(q), b, NULL); refblock(way_out, q, NULL); b = q; } if (tailreclab_argsinvregs != NULL) { RealRegSet maynotread, mnr; RAList *ra; int32 na = nargs; memclr(&maynotread, sizeof(RealRegSet)); for (ra = copies; ra != NULL; ra = cdr_(ra)) if (ra->argregdead) augment_RealRegSet(&maynotread, ra->r1); mnr = maynotread; for (i = n; --i >= 0 && na > 0; ) { J_OPCODE op = ic[i].op & J_TABLE_BITS; VRegInt r1 = ic[i].r1, r2 = ic[i].r2, r3 = ic[i].r3, r4 = ic[i].r4; if (uses_r1(op)) r1.r = register_number(r1.r); if (uses_r2(op)) r2.r = register_number(r2.r); if (uses_r3(op)) r3.r = register_number(r3.r); if (uses_r4(op)) r4.r = register_number(r4.r); /* The code below only recognizes simple 2 and 3 opnd instructions. * This is mainly because RealRegisterUse & Corrupt are not used, * and in many cases substitution may not be legal (LDM with writeback, * MUL with clashes etc). * Anyway, it will be easier to do this before register allocation... */ if (op == J_MOVR || op == J_ADDR || op == J_ADDK || op == J_SUBR) { /* loads_r1 = true */ r1.r = VarRegister(r1.r, copies); if (delete_RealRegSet(&maynotread, r1.r)) na--; } else break; /* fix of bug - do not cross calls etc. */ if ((reads_r1(op) && member_RealRegSet(&maynotread, r1.r)) || (reads_r2(op) && member_RealRegSet(&maynotread, r2.r)) || (reads_r3(op) && member_RealRegSet(&maynotread, r3.r)) || (reads_r4(op) && member_RealRegSet(&maynotread, r4.r))) break; } if (na == 0) { for (; --n, nargs > 0; ) { J_OPCODE op = ic[n].op; VRegInt r1 = ic[n].r1, r2 = ic[n].r2, r3 = ic[n].r3, r4 = ic[n].r4; if (uses_r1(op)) r1.r = VarRegister(r1.r, copies); if (uses_r2(op)) r2.r = VarRegister(r2.r, copies); if (uses_r3(op)) r3.r = VarRegister(r3.r, copies); if (uses_r4(op)) r4.r = VarRegister(r4.r, copies); if (loads_r1(op) && delete_RealRegSet(&mnr, r1.r)) { ic[n].r1 = r1; nargs--; } if (loads_r2(op) && delete_RealRegSet(&mnr, r2.r)) { ic[n].r2 = r2; nargs--; } if (reads_r1(op) && member_RealRegSet(&mnr, r1.r)) ic[n].r1 = r1; if (reads_r2(op) && member_RealRegSet(&mnr, r2.r)) ic[n].r2 = r2; if (reads_r3(op) && member_RealRegSet(&mnr, r3.r)) ic[n].r3 = r3; if (reads_r4(op) && member_RealRegSet(&mnr, r4.r)) ic[n].r4 = r4; } dest = tailreclab_argsinvregs; if (inserted != NULL) { ic = blkcode_(b), n = blklength_(b); for (; --n >= 0; ) { J_OPCODE op = ic[n].op; if (uses_r1(op)) ic[n].r1.r = VarRegister(ic[n].r1.r, copies); if (uses_r2(op)) ic[n].r2.r = VarRegister(ic[n].r2.r, copies); if (uses_r3(op)) ic[n].r3.r = VarRegister(ic[n].r3.r, copies); if (uses_r4(op)) ic[n].r4.r = VarRegister(ic[n].r4.r, copies); } } } } *nextp = dest; refblock(dest, b, NULL); } } } if (debugging(DEBUG_CG) && changed) flowgraf_print("After shrinkwrap", YES); } #endif /* These functions support generation of tables for exception handling: */ ExceptionEnv *last_exenv_started; /*only swing this mechanism into action when the exception environment changes*/ int prev_codep; /*records codep_at_exenv_start */ List* handler_entries; /*builds up a list of incompile exception handler entries */ static void add_exhandler_entry(int word) { DataInit *newtail, *oldtail = get_exhandler_ht(NO); newtail = (DataInit *)global_list5(SU_Data, (DataInit *)0, 1, LIT_NUMBER, 4, word); if (oldtail == NULL) set_exhandler_ht(YES, newtail); /*initialise head*/ else oldtail->datacdr = newtail; set_exhandler_ht(NO, newtail); set_exhandler_size(exhandler_size()+4); } static void add_extable_entry(int word) { DataInit *newtail, *oldtail = get_extable_ht(NO); newtail = (DataInit *)global_list5(SU_Data, (DataInit *)0, 1, LIT_NUMBER, 4, word); if (oldtail == NULL) set_extable_ht(YES, newtail); /*initialise head*/ else oldtail->datacdr = newtail; set_extable_ht(NO, newtail); set_extable_size(extable_size()+4); } static void localcg_startfn(void) { last_exenv_started=NULL; prev_codep=0;/*doesn't need initialising*/ handler_entries=NULL; } #define cons(car,cdr) (binder_cons2((cdr),(car))) /* called at the end of each fn, to coalesce and flush * exception tables as necessary */ static void output_thisfn_handler_entries(List* h_entries, int lastone) { if (h_entries==NULL) return; output_thisfn_handler_entries((List*) car_(h_entries), 0); /*recurse, filling up stack; would be better to reverse list explicitly*/ { List* tl=(List*) cdr_(h_entries); int destru, handler, offset, range_len, ensp_offset; destru=car_(tl); tl=cdr_(tl); handler=car_(tl); tl=cdr_(tl); offset=car_(tl); tl=cdr_(tl); range_len=car_(tl); ensp_offset=(int) cdr_(tl); /*dotted-list*/ if (lastone) offset|= 0x80000000; /* high bit set to mark the end */ if (debugging(DEBUG_CG)) { if (destru==0) printf("Error: unresolved handlerblock offset to L%d\n", 0xffffL&((LabelNumber*)handler)->name); printf("Offset=%8X range-len=%8X %s=%8X %s=%8X\n", offset, range_len, (destru==1) ? "en/SP-OFFSET" : "EN/sp-offset", ensp_offset, (destru==1) ? "DEST/handler" : "dest/HANDLER", handler); if (ensp_offset!=0) printf("should en/sp_offset really be non-zero?\n"), ensp_offset=0; } if (destru==0) return; add_exhandler_entry(offset); add_exhandler_entry(range_len); add_exhandler_entry(ensp_offset); add_exhandler_entry(handler); } } static void add_handler_entry(int destru, int handler, int prev_codep, int range_len, int ensp_offset) { if (range_len!=0) handler_entries= cons(handler_entries, cons(destru, cons(handler, cons(prev_codep, cons(range_len, ensp_offset))))); } static void output_exenv(ExceptionEnv *e) { int ensp_offset, handler, range_len = (int) codep - prev_codep; if (e==NULL) return; if (e->type==ex_destructor) { Binder* b =e->handlers.destructee; /* if ( bindstg_(b) | onstack) ; give error about not being on stack*/ ensp_offset = bindaddr_(b) & ~BINDADDR_LOC; /*offset of obj from SP. OK*/ ensp_offset = - ensp_offset; handler=1; /* address of destructor function, can only determine it symbolically at this time, needs fixing up by linker*/ add_handler_entry(1, handler, prev_codep, range_len, ensp_offset); } else /* e->type must be ex_handler, ie this is a 'try' block. */ { LabelNumber *l = e->handlers.henv.handlerblock; HandlerList *hl = e->handlers.henv.handlerlist; LabelNumber **table = blktable_(lab_block_(l)); int i; for(i=0;i<blktabsize_(lab_block_(l));i++) /* multiple handler cases: iterate over hl */ { if (debugging(DEBUG_CG)) printf("i=%d hl=%x\n", i, (int)hl); handler = (int) table[i]; ensp_offset=hl->type; /*this is exception number, or 0 for "..." */ hl=hl->cdr; add_handler_entry(0, handler, prev_codep, range_len, ensp_offset); } } if (e->cdr!=NULL) output_exenv (e->cdr);/* must do innermost ones first */ prev_codep = codep; } /*called at start of each block, to see if current block is on list * of blocks of which we need to know codep */ static void walk_handler_entries(List* h_entries, BlockHead *bl) { List* this_h_entry; if (h_entries==NULL) return; this_h_entry=(List*) cdr_(h_entries); /* printf ("this_h_entry=%X car_(this_h_entry)=%X\n", (int)this_h_entry, (int) car_(this_h_entry)); */ if (car_(this_h_entry) == 0)/*destructor-p slot, 0=>unresolved handler*/ { LabelNumber* handlerslot = (LabelNumber*) car_(cdr_(this_h_entry)); if (handlerslot->block == bl)/*handler slot*/ { car_(this_h_entry) = -1;/*destructor-p slot*/ #ifdef TARGET_IS_THUMB car_(cdr_(this_h_entry)) = codep; #else car_(cdr_(this_h_entry)) = codep /*+4=hack*/+4;/*handler slot*/ #endif /* don't return; there may be more than one predecessor of this bl */ } } walk_handler_entries((List*) car_(h_entries), bl); } static void localcg_startblock(BlockHead* bl) { if (bl==NULL) return; /*does this ever happen?*/ if (!(var_cc_private_flags & 128L)) return; walk_handler_entries(handler_entries, bl); if (blkexenv_(bl)==last_exenv_started) return; /* a single exception environment may encompass a range of addresses, so don't deal with it until it has finished */ output_exenv(last_exenv_started); last_exenv_started = blkexenv_(bl); return; } static void localcg_endfn(void) { if (codep == 0) return; /*a function of zero length is not interesting*/ if (!(var_cc_private_flags & 128L)) return; if (exhandler_size()==0) add_exhandler_entry(0xdeadbeef); /*dummy first entry so that index offset is not 0 which looks like null.*/ if (debugging(DEBUG_CG)) printf("FunctionExceptionTable addr=%4X fn-length=%4X exhandler=%4X\n", codebase, codep, exhandler_size()); #ifdef TARGET_IS_THUMB add_extable_entry(1+(int)codebase); #else add_extable_entry(codebase); #endif add_extable_entry(codep); /*codep is the offset of last instruction in the function, which is 4 (or 2 for thumb) less than the instruction length; but the return address of the function will never be right at the end, so this won't affect behaviour of stackwalking code. */ if (handler_entries==NULL) add_extable_entry(0); else add_extable_entry(exhandler_size()); output_exenv (last_exenv_started); output_thisfn_handler_entries(handler_entries, 1); } static LabelNumber *dump_flowgraph(LabelNumber *pending_branch, int32 lifted) { BlockHead *p1; localcg_startfn(); for (p1 = top_block; p1 != NULL; p1 = blkdown_(p1)) { BlockHead *p = p1; if ( ( (blkflags_(p) & BLKALIVE) || (usrdbg(DBG_LINE+DBG_VAR) && !usrdbg(DBG_OPT_DEAD))) && !(blkflags_(p) & BLKCODED) && (blkflags_(p) & BLKLIFTABLE) == lifted) for (;;) { LabelNumber *w = blklab_(p); localcg_startblock(p); if ( (blkflags_(p) & BLKEMPTY) && (!usrdbg(DBG_LINE+DBG_VAR) || usrdbg(DBG_OPT_DEAD))) syserr(syserr_live_empty_block, (long)lab_name_(w)); if (pending_branch != NOTALAB && pending_branch != w) show_branch_instruction(J_B, pending_branch); if (blkflags_(p) & BLKSWITCH) { LabelNumber **v = blktable_(p); int32 i, n = blktabsize_(p); /* Normalise the entries in the switch table */ /* This is done so that the r2 field of J_CASEBRANCH is OK */ for (i=0; i<n; i++) if (v[i] == way_out) v[i] = RETLAB; } if (blkflags_(p) & BLKSWITCH && blklength_(p) == 1 && (blkcode_(p)->op == J_THUNKTABLE)) { LabelNumber **v = blktable_(p); int32 i, n = blktabsize_(p); pending_branch = NOTALAB; for (i=0; i<n; i++) { BlockHead *b = v[i]->block; if (blkcode_(b)[0].op == J_ORG) goto omit_casebranch; } for (i=0; i<n; i++) { BlockHead *b = v[i]->block; Icode *c0 = blkcode_(b), *c1 = c0 + 1; int ptr_adjust_zero; ptr_adjust_zero = (blklength_(b) == 2 && (c0->op & J_TABLE_BITS) == J_ADDK && c0->r1.rr == 0 && c0->r2.rr == 0 && c0->r3.i == 0 && (c1->op & J_TABLE_BITS) == J_TAILCALLK); localcg_startblock(b); #ifdef TARGET_HAS_DATA_VTABLES if (target_has_data_vtables) { Icode ic; if (ptr_adjust_zero) { ic = *c1; ic.op = J_WORD_ADCON; expand_jop_macro(&ic); blkflags_(b) |= BLKCODED; } else { INIT_IC (ic, J_WORD_LABEL); ic.r3.l = v[i]; #ifdef THUMB_CPLUSPLUS c0->op = (c0->op & ~J_TABLE_BITS) | J_THIS_ADJUST; #endif expand_jop_macro(&ic); } } else #endif { if (ptr_adjust_zero) { expand_jop_macro(c1); blkflags_(b) |= BLKCODED; } else #ifdef TARGET_HAS_SWITCH_BRANCHTABLE if (i == (n-1)) pending_branch = v[n-1]; else #endif show_branch_instruction(J_BXX, v[i]); } } blkflags_(p) |= BLKCODED; omit_casebranch:; } else if (blkflags_(p) & BLK2EXIT && blknext_(p) != blknext1_(p)) /* The seemingly odd test for distinct destinations is present here since */ /* cross-jump optimisations can reveal new cases of vacuous tests, and if */ /* I pass such a case down to use_cond_field() the destination block gets */ /* displayed twice (which would be sort of OK except for the fact that */ /* setting its label twice causes trouble). */ pending_branch = use_cond_field(p); else { localcg_startblock(p); show_basic_block(p, Q_AL); if (blkflags_(p) & BLKSWITCH) { LabelNumber **v = blktable_(p); int32 i, n = blktabsize_(p); #ifdef TARGET_HAS_SWITCH_BRANCHTABLE n--; #endif /* drop though to execute last case directly: only if target uses a branch */ /* table of branch instructions!!!!!!!!! */ for (i=0; i<n; i++) { if (v[i]!=RETLAB) localcg_startblock(lab_block_(v[i])); show_branch_instruction(J_BXX, v[i]); } #ifdef TARGET_HAS_SWITCH_BRANCHTABLE pending_branch = v[n]; #else pending_branch = NOTALAB; #endif } #ifdef TARGET_HAS_TAILCALL else if (blkflags_(p) & BLK0EXIT) pending_branch = NOTALAB; #endif else if ( blknext_(p) == way_out || (!(blkflags_(p) & BLKALIVE) && is_exit_label(blknext_(p))) ) pending_branch = RETLAB; else pending_branch = blknext_(p); } /*localcg_endblock(p);*/ if (pending_branch == NOTALAB || pending_branch == RETLAB /* @@@ LDS 21-Sep-89: the following line conspires with cg_loop and emits */ /* better code for while/for loops, saving 1 br-not-taken/iteration. */ || ( (blkflags_(p) & BLKLOOP) && (!usrdbg(DBG_LINE) || usrdbg(DBG_OPT_DEAD)))) break; { BlockList *bl; int flag = 1; BlockHead *prev = p; p = pending_branch->block; /* p is now the destination block for the one I have just displayed. */ /* If it has not already been coded but all its ancestors have (except */ /* itself, if it is its own ancestor) I will display it next. */ if ((blkflags_(p) & BLKCODED) || usrdbg(DBG_VAR)) break; for (bl = blkusedfrom_(p); bl!=NULL; bl=bl->blklstcdr) if (bl->blklstcar != p && !(blkflags_(bl->blklstcar) & BLKCODED)) { flag = 0; break; } if (flag) continue; /* use block p next, do not advance p1 */ if (p == blkdown_(prev)) continue; } break; /* go on to next sequential block */ } } localcg_endfn(); return pending_branch; } void linearize_code(void) { int no_crossjumping = 0; /* before we can tidy up branches to branches we have to find out which */ /* basic blocks are empty (this is non-trivial because e.g. register */ /* allocation may have turned a STRV into a MOV r,r). Ultimately we */ /* should remove all _STACKREF jopcodes, but for now just test by */ /* smashing to NOOPs where relevant. */ { BlockHead *p; unsigned32 n, max_stackdepth = 0; int32 total_code_length = 0; /* Now seems a convenient time to replace blkstack by blkstacki */ /* Also, we now recompute greatest_stackdepth */ for (p = top_block; p != NULL; p = blkdown_(p)) { if (usrdbg(DBG_VAR)) { BindList *bl = blkstack_(p); for ( ; bl!=NULL ; bl = bl->bindlistcdr ) { Binder *b = bl->bindlistcar; if (bindstg_(b) & b_bindaddrlist) { /* The following code extends similar code in */ /* remove_noops by ensuring all variables (not */ /* only referenced ones) are allocated stack */ /* when the debugging tables are produced. */ setstackoffset(b); } } } blkstacki_(p) = n = size_of_binders(blkstack_(p)); if (n > max_stackdepth) max_stackdepth = n; blkflags_(p) |= BLKSTACKI; { int32 i, len = blklength_(p); Icode *c = blkcode_(p); for (i = 0; i < len; i++) if ((c[i].op & J_TABLE_BITS) == J_SETSPENV) { c[i].r2.i = n = size_of_binders(c[i].r2.bl); if (n > max_stackdepth) max_stackdepth = n; c[i].r3.i = n = size_of_binders(c[i].r3.bl); if (n > max_stackdepth) max_stackdepth = n; c[i].op = J_SETSP; } } } greatest_stackdepth = max_stackdepth; if (greatest_stackdepth > 256) procflags |= PROC_BIGSTACK; else procflags &= ~PROC_BIGSTACK; for (p = top_block; p != NULL; p = blkdown_(p)) { /* NB lose_dead_code() means that all these blocks are */ /* really alive, however BLKALIVE has been cleared. */ blklength_(p) = remove_noops(blkcode_(p), blklength_(p)); total_code_length += blklength_(p); } #ifdef TARGET_IS_THUMB /* force LR to be stored for large functions, so that BL may be used for jumps */ if (total_code_length > 1000) augment_RealRegSet(&regmaskvec, R_LR); #endif } /* Remove branches to branches and similar oddities. */ /* N.B. the top_block will never be empty since it contains an ENTER */ /* Also collect list of parents for each block. */ /* Furthermore turn exit-branches into jumps to a single exit block so */ /* that cross-jumping will be able to detect shared code leading thereto */ { BlockHead *b; way_out = nextlabel(); way_out->block = b = newblock(way_out, NULL); blkstacki_(b) = 0; blknext_(b) = RetVoidLab; /* Hmmm - all returns are alike here */ blkflags_(b) |= BLKALIVE | BLKSTACKI; } (void)branch_chain(blklab_(top_block), 1); #ifdef TARGET_HAS_TAILCALL /* Now (after branch-chaining) insert J_TAILCALL instead of J_CALL ... */ /* This transformation is valid if the CALL is immediately followed by a */ /* return, and no variables whose address are taken are in scope and */ /* further no calls to 'setjmp' occur within the procedure at all. */ /* (CONFIG_INDIRECT_SETJMP allows (ANSI-forbidden) J_CALLR to 'setjmp'.) */ /* This is implemented in rather a different way. We can tell that no */ /* non-register locals are present from the immediate return since */ /* this can at worst have come from a squashed SETSP. We need to check */ /* whether any block had a 'setjmp' or an arg address taken too. */ /* sample code that could give trouble if setjmp were called & tail-call */ /* conversion applied... */ /* int f(int x) */ /* { <code that is complicated enough for x to be spilt> */ /* if (setjmp(buff)) p(buff); */ /* else q(x); */ /* } */ /* where p calls longjmp(). Then if x is in the stack-frame of f() the */ /* call to p() can clobber it even though its value is needed for q(x). */ /* Note that if x were a register variable its value would have been safe*/ /* in buff, and if &x were mentioned the tail call would be illegal */ /* otherwise, so it is only if x is spilt for other reasons.... */ /* Note that the destination in a J_TAILCALLR ought not to be one in the */ /* callee-saved set (which will be restored before it is used), but */ /* register allocation saw an ordinary J_CALLR with no such restriction. */ /* The problem is ignored here: backends with TAILCALLR must take */ /* appropriate action themselves. */ if (!(procflags & (BLKSETJMP|PROC_ARGADDR)) && !usrdbg(DBG_ANY) /* No tail call if debugging - too confusing */ && !(var_cc_private_flags & 16L) #ifdef PROFILE_DISABLES_TAILCALL && !profile_option #endif && !(procauxflags & bitoffnaux_(s_irq)) ) { BlockHead *p; int32 len; for (p = top_block; p != NULL; p = blkdown_(p)) if (!(blkflags_(p) & (BLK2EXIT|BLKSWITCH)) && blknext_(p) == way_out && (len = blklength_(p)) > 0) { Icode *b = blkcode_(p); Icode *bend = &b[len-1]; /* AM: note that we do not tailify() J_CALLK/R with K_NOTAILCALL set. */ if (!(bend->r2.i & K_NOTAILCALL) && ( ( (bend->op & J_TABLE_BITS) == J_CALLK #ifdef TARGET_HAS_RECURSIVE_TAILCALL_ONLY && bindsym_(bend->r3.b) == currentfunction.symstr #endif ) /* ECN: Any CALLK marked 'K_THUNK' must be converted to a * TAILCALLK regardless of TARGET_HAS_RECURSIVE_TAILCALL_ONLY */ || ((bend->op & J_TABLE_BITS) == J_CALLK && (bend->r2.i & K_THUNK)) #ifdef TARGET_HAS_TAILCALLR || (bend->op & J_TABLE_BITS)== J_CALLR #endif ) ) { bend->op = tailify_(bend->op); /* J_TAILCALLK/R */ /* flag block as having no exit and 1 less call ... */ blkflags_(p) |= BLK0EXIT; if (!(blkflags_(p) & BLK2CALL)) blkflags_(p) &= ~BLKCALL; } } } #endif /* Now establish reference counts for blocks so that I can see which */ /* ones have more than one entry. */ /* @@@ move this code into branch_chain() now that it is tidied? */ { BlockHead *p; refblock(blklab_(top_block), NULL, 0); /* Reference from outside proc */ for (p = top_block; p != NULL; p = blkdown_(p)) if (blkflags_(p) & BLKALIVE) { if (blkflags_(p) & BLKSWITCH) { LabelNumber **v = blktable_(p); int32 i, n = blktabsize_(p); for (i=0; i<n; i++) refblock(v[i], p, 0); if (blklength_(p) == 1 && blkcode_(p)->op == J_THUNKTABLE) no_crossjumping = 1; } else { /* Blocks with BLK0EXIT (ending with tailcall) */ /* included here (successor is way_out) */ refblock(blknext_(p), p, 0); if (blkflags_(p) & BLK2EXIT) refblock(blknext1_(p), p, 0); } } } blkflags_(top_block) |= BLKALIVE; #ifndef TARGET_IS_NULL /* cross-jump-optimise uses used-from information */ if (!no_crossjumping && cross_jump_optimize()) { BlockHead *p; for (p = top_block; p != NULL; p = blkdown_(p)) blkflags_(p) &= ~BLKALIVE; branch_chain(blklab_(top_block), 2); if (debugging(DEBUG_CG)) flowgraf_print("After branch-chain", YES); } #ifndef TARGET_STACKS_LINK /* See comment in regalloc.c - mark R_LR as allocated if a non-tail call */ /* appears. */ if (procflags & BLKCALL) augment_RealRegSet(&regmaskvec, R_LR); #endif { BlockHead *p; for (p = top_block; p != NULL; p = blkdown_(p)) blkflags_(p) &= ~BLKLIFTABLE; } #ifdef TARGET_HAS_SAVE try_shrinkwrap(); #endif /* Now dump out the flowgraph - note that J_ENTER implicitly */ /* does a 'set_cond_execution(Q_AL)' if TARGET_HAS_COND_EXEC */ /* ???Is doing the next line here what causes the syserr() in refblock() */ blkflags_(way_out->block) |= BLKCODED; /* do not display this block */ /* strictly a lie, but harmless. The more obvious &= ~BLKALIVE fails if */ /* usrdbg(something) */ /* /* AM: The following interface is spurious: xxxgen.c can detect */ /* the J_ENTER. AM leaves it (under threat) until we can inhibit the */ /* J_LABEL and J_STACK which preceed J_ENTER currently. */ localcg_reinit(); { LabelNumber *pending_branch_address; current_env2 = 0; #ifndef TARGET_IS_ARM dbg_enterproc(); #else /* called from armgen (possibly after codeseg_function_name()) */ #endif if (debugging(DEBUG_CG)) cc_msg("\n\nFlattened form:\n\n"); pending_branch_address = dump_flowgraph(NOTALAB, BLKLIFTABLE); pending_branch_address = dump_flowgraph(pending_branch_address, 0); if (pending_branch_address != NOTALAB) show_branch_instruction(J_B, pending_branch_address); if (usrdbg(DBG_VAR)) dbg_scope1(0, current_env2); } { Icode ic; INIT_IC(ic, J_ENDPROC); expand_jop_macro(&ic); } #endif /* TARGET_IS_NULL */ } void flowgraph_reinit(void) { currentblock = icodetop = (Icode *) DUFF_ADDR; /* NB. (currentblock >= icodetop) */ cgstate.icode_cur = cgstate.block_cur = 0; icoden = 0; bottom_block = 0, block_header = (BlockHead*) DUFF_ADDR; deadcode = 1; current_env = 0; holes = NULL; prevblock = NULL; INIT_IC(fg_pending, J_NOOP); fg_pending.r3.i = 0; #ifdef TARGET_HAS_COND_EXEC if (config & CONFIG_OPTIMISE_SPACE) { CondMax_Loop = 10; CondMax_Ordinary = 5; } else { CondMax_Loop = 6; CondMax_Ordinary = 3; } #endif } /* end of mip/flowgraph.c */
stardot/ncc
cfe/simplify.h
<filename>cfe/simplify.h /* * simplify.h, version 3 * Copyright (C) Codemist Ltd, 1988-1992. * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Advanced RISC Machines Ltd., 1990-1992. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _simplify_h #define _simplify_h #ifndef _defs_LOADED # include "defs.h" #endif extern Expr *optimise0(Expr *e); #define cg_optimise0(e) optimise0(e) extern int32 mcrepofexpr(Expr *e); extern int32 mcrepoftype(TypeExpr *t); bool is_same(Expr *a,Expr *b); bool returnsstructinregs_t(TypeExpr *t); bool returnsstructinregs(Expr *fn); /* fields in mcrep result: */ #define MCR_SIZE_MASK 0x007fffff #define MCR_SORT_MASK 0x07000000 #define MCR_ALIGN_DOUBLE 0x00800000 #define MCR_SORT_SHIFT 24 #define MCR_SORT_SIGNED 0x0000000 #define MCR_SORT_UNSIGNED 0x1000000 #define MCR_SORT_FLOATING 0x2000000 #define MCR_SORT_STRUCT 0x3000000 #define MCR_SORT_PLAIN 0x4000000 /* now probably defunct */ /* The next line has the effect of aligning locals to the same boundary */ /* as top-level variables. Note the constant left operand of &&... */ #define padtomcrep(a,r) padsize((a), \ (int32)(alignof_double > alignof_toplevel_auto && ((r) & MCR_ALIGN_DOUBLE) ? \ alignof_double : alignof_toplevel_auto)) #endif /* end of simplify.h */
stardot/ncc
thumb/peephole.c
/* * C compiler file thumb/peephole.c. * Copyright (C) Codemist Ltd, 1988. * Copyright (C) Acorn Computers Ltd., 1988 * Copyright (C) Advanced Risc Machines Ltd., 1991 * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <string.h> #include "globals.h" #include "host.h" #include "options.h" #include "mcdep.h" #include "mcdpriv.h" #include "aeops.h" #include "ops.h" #include "jopcode.h" #include "store.h" #include "errors.h" #include "cg.h" /* for procflags, greatest_stackdepth */ #include "regalloc.h" /* regmask */ #include "simplify.h" /* for MCR_SIZE_MASK */ #define PendingStackSize 30 #define PeepholeWindowSize 10 static PendingOp *pendingstack; static PendingOp *pending; typedef union { int32 i; unsigned32 u; PendingOp *p; } IntOrP; #define p_value_unused(u, a) (!((u)->use & regbit(a))) #define p_value_unchanged(u, a) (!((u)->kill & regbit(a))) #define p_reg_unused(u, a) (!(((u)->use | (u)->kill) & regbit(a))) #define p_psr_unchanged(u) (!((u)->kill & M_PC)) #define p_regset_unused(u, a) (!(((u)->use | (u)->kill) & (a))) #define p_regset_unchanged(u, a) (!((u)->kill & (a))) typedef enum P_OpType { pot_none, pot_and, pot_or, pot_andnot, pot_prop, pot_peep, pot_peep_m, pot_op, pot_op_m, pot_opinset, pot_opinset_m } P_OpType; typedef enum { prt_none, prt_kill, prt_swapr2r3, prt_set, prt_asr, prt_proc } P_ReplaceType; typedef enum { pf_op, pf_peep, pf_r1, pf_r2, pf_r3, pf_r4, pf_dataflow, pf_cond, pf_none } P_Field; typedef struct PeepReplace { /* P_ReplaceType */ unsigned char type; /* P_Field */ unsigned char field; /* P_FieldType */ unsigned char valtype; int32 val; /* we really want val to be something like : union { struct { unsigned char inst; unsigned char field; } field; int32 value; bool (*proc)(PendingOp *, PendingOp **, RegisterUsage *); } val; but that can't be initialised. */ } PeepReplace; #define pr_type_(r) ((P_ReplaceType)((r)->type)) #define pr_field_(r) ((P_Field)((r)->field)) #define pr_valtype_(r) ((P_FieldType)((r)->valtype)) #define pr_val_(r) ((r)->val) typedef bool RProc(PendingOp *, PendingOp **, RegisterUsage *); #define valproc_(p) (rprocs[(p)->val]) typedef enum { pct_none, pct_eq, pct_ne, pct_lt, pct_le, pct_gt, pct_ge, pct_ltu, pct_leu, pct_gtu, pct_geu, pct_proc0, pct_proc1, pct_proc2, pct_negate, pct_or } PC_Type; typedef enum { pft_none, pft_val, pft_exprn, pft_field, pft_inst } P_FieldType; typedef enum PE_Op { peo_proc1, peo_proc2, peo_or, peo_and, peo_eor, peo_add, peo_sub, peo_shr, peo_shl, peo_div, peo_mul, peo_last } PE_Op; typedef bool P1Proc(IntOrP *resp, IntOrP r1); typedef bool P2Proc(IntOrP *resp, IntOrP r1, IntOrP r2); static bool p_log2(IntOrP *resp, IntOrP r1); static bool p_bit(IntOrP *resp, IntOrP r1); static bool p_bitcount(IntOrP *resp, IntOrP r1); static bool p_lsb(IntOrP *resp, IntOrP r1); static bool p_lsbpair(IntOrP *resp, IntOrP r1); static bool p_shift_p(IntOrP *resp, IntOrP r1); static bool p_shift_k(IntOrP *resp, IntOrP r1, IntOrP r2); #define pep_argct_log2 1 #define pep_argct_bit 1 #define pep_argct_bitcount 1 #define pep_argct_lsb 1 #define pep_argct_lsbpair 1 #define pep_argct_shift_p 1 #define pep_argct_shift_k 2 typedef enum PE_Proc { pep_bit, pep_bitcount, pep_lsb, pep_lsbpair, pep_log2, pep_shift_k, pep_shift_p, pep_last } PE_Proc; static P1Proc * const pprocs[pep_last] = { p_bit, p_bitcount, p_lsb, p_lsbpair, p_log2, (P1Proc *)p_shift_k, p_shift_p, }; typedef struct PeepExprn { /* PE_Op */ unsigned char op; /* PE_Proc */ unsigned char fn; /* P_FieldType */ unsigned char f1type, f2type; int32 f1, f2; } PeepExprn; typedef struct PeepConstraint{ /* PC_Type */ unsigned char type; /* PC_Proc */ unsigned char fn; /* P_FieldType */ unsigned char f1type, f2type; int32 f1, f2; /* we really want f1 & f2 to be something like : union { struct { unsigned char inst; unsigned char field; } field; int32 value; }; but that can't be initialised. */ } PeepConstraint; #define pe_op_(c) ((PE_Op)((c)->op)) #define pe_fn_(c) ((PE_Proc)((c)->fn)) #define pc_type_(c) ((PC_Type)((c)->type)) #define pc_fn_(c) ((PC_Proc)((c)->fn)) #define f1type_(c) ((P_FieldType)((c)->f1type)) #define f2type_(c) ((P_FieldType)((c)->f2type)) #define f1_(c) ((c)->f1) #define f2_(c) ((c)->f2) #define inst_(f) ((int)((f)>>8)) #define field_(f) ((P_Field)((f)&255)) #define pexprn_(f) (&peepexprns[f]) typedef enum { pub_r1, pub_r2, pub_r3, pub_r4, pub_r3mask } P_Use; #define pu_r1 (1<<pub_r1) #define pu_r2 (1<<pub_r2) #define pu_r3 (1<<pub_r3) #define pu_r4 (1<<pub_r4) #define pu_r3mask (1<<pub_r3mask) typedef struct PeepOpDef { /* P_OpType */ unsigned char type; unsigned char maynotuse, /* constraints on register fields between the */ maynotkill; /* participants in a peephole */ /* (only used in top level - the PeepOpDef in a PeepOp */ unsigned char setcount; int32 n; } PeepOpDef; typedef struct PeepOp { PeepOpDef p; unsigned char dead; unsigned char replacecount; short replaceix; } PeepOp; #define peepop_(p) ((p)->n) #define peepprop_(p) (peepprops[(p)->n]) #define peepsub1_(p) (peepsubs[((p)->n)>>16]) #define peepsub2_(p) (peepsubs[((p)->n)&0xffff]) #define peepset_(p) (peepsets[((p)->n)&0xffff]) #define peepopi_(p) (peepsets[((p)->n)&0xffff]) #define peepmask_(p) (peepsets[((p)->n)>>16]) #define G_ANY 0xff #define G_STR 1 typedef struct PeepHole { PeepOp const *insts; PeepConstraint const *constraint; unsigned char instcount; unsigned char constraintcount; unsigned char trace; unsigned char gapconstraint; } PeepHole; typedef enum { pcp_notcall, pcp_regset_unused, pcp_regset_unkilled, pcp_notleafproc, pcp_movc_pres_r1r2, pcp_nostackrefsbelow, pcp_difficult_constant, pcp_config } PC_Proc; #define pcp_argct_notcall 1 #define pcp_argct_regset_unused 1 #define pcp_argct_regset_unkilled 1 #define pcp_argct_notleafproc 0 #define pcp_argct_movc_pres_r1r2 2 #define pcp_argct_nostackrefsbelow 2 #define pcp_argct_difficult_constant 1 #define pcp_argct_config 1 typedef int C0Proc(RegisterUsage *); typedef int C1Proc(RegisterUsage *, IntOrP); typedef int C2Proc(RegisterUsage *, IntOrP, IntOrP); #define RETLABV ((int32)RETLAB) #define p_dead_r1 1 #define p_dead_r2 2 #define p_dead_r3 4 static int32 const dead_bits[] = { /* translation from p_dead_xx */ 0, J_DEAD_R1, J_DEAD_R2, J_DEAD_R1+J_DEAD_R2, J_DEAD_R3, J_DEAD_R3+J_DEAD_R1, J_DEAD_R3+J_DEAD_R2, J_DEAD_R3+J_DEAD_R1+J_DEAD_R2 }; #define M_SP regbit(R_SP) #include "peeppat.c" extern int Profiler_Count_Index_Max; extern int Profiler_Count_Index; int Profiler_Count_Index_Max = PeepholeMax; int Profiler_Count_Index; #ifdef ENABLE_LOCALCG static int32 p_count[PeepholeMax+1]; static bool uses_r4_field(J_OPCODE op) { /* but not as a register */ op &= ~J_ALIGNMENT; return op == J_MOVC || op == J_CLRC; } static void a_pr_jopcode_nodeadbits(PendingOp *p) { J_OPCODE op = p->ic.op; if ((op & J_TABLE_BITS) <= J_LAST_JOPCODE) print_jopcode_1(&p->ic); else { char v[20]; unsigned32 attr = a_attributes(op); strcpy(v, a_joptable[(op & J_TABLE_BITS)-J_LAST_JOPCODE-1].name); if (op & J_ALIGNMENT) strcat(v, ((op & J_ALIGNMENT) >> J_ALIGNPOS)*3 + "a1\0a2\0a4\0a8"); cc_msg("%8s%-12s", "", v); if (attr & _a_gap_r1) cc_msg("-, "); else if (attr & _a_regmask_r1) cc_msg("%#lx, ", p->ic.r1.rr); else cc_msg("%ld, ", p->ic.r1.rr); if (attr & _a_call) { cc_msg("%ld(%ld,%ld", k_argwords_(p->ic.r2.rr), k_intregs_(p->ic.r2.rr), k_fltregs_(p->ic.r2.rr)); if (k_resultregs_(p->ic.r2.rr) > 1) cc_msg("=>%ld", k_resultregs_(p->ic.r2.rr)); cc_msg(")"); } else if (attr & _a_gap_r2) cc_msg("-"); else cc_msg("%ld", p->ic.r2.rr); if (attr & _a_regmask_r3) cc_msg(", %#lx", p->ic.r3.i); else cc_msg(", %ld", p->ic.r3.i); } if (uses_r4_field(op)) cc_msg(", %#lx", (long)p->ic.r4.rr); if (p->peep == 0) cc_msg("\n"); else cc_msg(" <%lx>\n", (long)p->peep); } static void pr_patno(int n) { if (n > 0) cc_msg("{%3d} ", n); else cc_msg(" "); } void a_pr_jopcode(PendingOp *p) { cc_msg("%c%c%c", (p->dataflow & J_DEAD_R1 ? '1': '-'), (p->dataflow & J_DEAD_R2 ? '2': '-'), (p->dataflow & J_DEAD_R3 ? '3': '-')); a_pr_jopcode_nodeadbits(p); } static void pr_res(PendingOp *pending, int n) { if (localcg_debug(2)) { cc_msg("%2d> ", pending - pendingstack); pr_patno(n); a_pr_jopcode(pending); } if (pending < pendingstack) syserr("pr_res not in stack"); } static void pr_cur(int n, PendingOp *cur, PendingOp *limit) { if (localcg_debug(2)) { cc_msg(" "); pr_patno(n+1); cc_msg("%16s", ""); cc_msg("%2d: ", limit+1 - &pendingstack[0]); a_pr_jopcode(cur); } } #define count_p(n) (p_count[n]++) #else #define pr_res(a, b) #define pr_cur(n, a, b) #define count_p(n) #endif #define aru_updatekills 1 #define aru_ignorepreuse 2 #define aru_fieldbit_(r) (1<<((r)-pf_r1+2)) #define aru_ignore_r1 (1<<2) #define aru_ignore_r2 (1<<3) #define aru_ignore_r3 (1<<4) #define aru_ignore_r4 (1<<5) static void AccumulateRegisterUse(RegisterUsage *u, PendingOp *c, int flags) { if (a_loads_r1(c)) { if (flags & aru_updatekills) u->def |= regbit(c->ic.r1.rr); } else if (a_reads_r1(c) && !(flags & aru_ignore_r1)) u->use |= regbit(c->ic.r1.rr); if (a_loads_r2(c)) { if (flags & aru_updatekills) u->def |= regbit(c->ic.r2.rr); } else if (a_reads_r2(c) && !(flags & aru_ignore_r2)) { if (!(c->peep & P_PRE && (flags & aru_ignorepreuse))) u->use |= regbit(c->ic.r2.rr); } if (a_uses_r3(c) && !(flags & aru_ignore_r3)) u->use |= regbit(c->ic.r3.i); if (a_uses_r4(c) && !(flags & aru_ignore_r4)) u->use |= regbit(c->ic.r4.rr); if (sets_psr(&c->ic) || ((c->peep & P_CMPZ)) && (flags & aru_updatekills)) u->def |= regbit(R_PSR); if (reads_psr(&c->ic)) u->use |= regbit(R_PSR); if (corrupts_r1(&c->ic) && (flags & aru_updatekills)) u->def |= regbit(c->ic.r1.rr); if (corrupts_r2(&c->ic) && (flags & aru_updatekills)) u->def |= regbit(c->ic.r2.rr); { RealRegUse use; RealRegisterUse(&c->ic, &use); u->use |= use.use.map[0]; if (flags & aru_updatekills) u->def |= use.def.map[0] | use.c_in.map[0] | use.c_out.map[0]; } } static bool NoStackReferencesBelow(PendingOp *p, PendingOp *limit, int32 n) { for (; ++p <= limit; ) { int32 op = p->ic.op & ~J_ALIGNMENT; if ( (a_reads_r2(p) && p->ic.r2.rr == R_SP && (a_uses_r3(p) || p->ic.r3.i < n || op == J_MOVC)) || (a_reads_r1(p) && p->ic.r1.rr == R_SP) || (a_uses_r3(p) && p->ic.r3.i == R_SP && op != J_MOVR) || (op == J_PUSHM || op == J_PUSHD || op == J_PUSHF) ) return NO; } return YES; } #ifdef ENABLE_LOCALCG #define AdjustStackRefs(a,b,c,d) Real__AdjustStackRefs(a,b,c,d) #else #define AdjustStackRefs(a,b,c,d) Real__AdjustStackRefs(a,b,c) #endif /* $$$$$ why are the assumptions this makes valid?? */ static void AdjustStackRefs(PendingOp *p, PendingOp *limit, int32 n, int ix) { for (; p <= limit; p++) if (a_reads_r2(p) && p->ic.r2.rr == R_SP) { p->ic.r3.i -= n; pr_res(p, ix); } else if (a_uses_r3(p) && p->ic.r3.i == R_SP) { p->ic.op = J_ADDK; p->ic.r2.rr = R_SP; p->ic.r3.i = -n; pr_res(p, ix); } } static bool p_log2(IntOrP *resp, IntOrP r1) { resp->i = power_of_two(r1.i); return YES; } static bool p_bit(IntOrP *resp, IntOrP r1) { resp->i = 1L << r1.i; return YES; } static bool p_bitcount(IntOrP *resp, IntOrP r1) { resp->i = 4 * bitcount(r1.i); return YES; } static bool p_lsb(IntOrP *resp, IntOrP r1) { if (r1.i == 0) return NO; resp->i = r1.i & -r1.i; return YES; } static bool p_lsbpair(IntOrP *resp, IntOrP r1) { int32 i1; if (r1.i == 0) return NO; i1 = r1.i & -r1.i; r1.i ^= i1; if (r1.i == 0) return NO; resp->i = i1 | (r1.i & -r1.i); return YES; } /* On arm, this produces a shift code which is later used in eg add r1, r2 , r3 lsl r4. Thumb doesn't have that flexibility so try not to generate them. */ static bool p_shift_p(IntOrP *resp, IntOrP r1) { syserr("p_shift_p called\n"); IGNORE(r1); resp->i = 0; return YES; } /* No scaled addressing on thumb. */ static bool p_shift_k(IntOrP *resp, IntOrP r1, IntOrP r2) { syserr("p_shift_k called\n"); IGNORE(r1); IGNORE(r2); resp->i = 0; return YES; } static int32 opfield(PendingOp *op, P_Field field, int32 *dead) { switch (field) { case pf_op: return op->ic.op; case pf_peep: return op->peep; case pf_r1: *dead = a_uses_r1(op) && (op->dataflow & J_DEAD_R1); return op->ic.r1.rr; case pf_r2: *dead = a_uses_r2(op) && (op->dataflow & J_DEAD_R2); return op->ic.r2.rr; case pf_r3: *dead = a_uses_r3(op) && (op->dataflow & J_DEAD_R3); return op->ic.r3.i; case pf_r4: return op->ic.r4.rr; case pf_dataflow: return op->dataflow; case pf_cond: return op->cond; default: syserr(syserr_peep_bad_field); return 0; } } static void setopfield(PendingOp *op, P_Field field, int32 val, int32 dead) { switch (field) { case pf_op: op->ic.op = val; break; case pf_peep: op->peep = val; break; case pf_r1: op->dataflow &= ~J_DEAD_R1; if (dead) op->dataflow |= J_DEAD_R1; op->ic.r1.rr = val; break; case pf_r2: op->dataflow &= ~J_DEAD_R2; if (dead) op->dataflow |= J_DEAD_R2; op->ic.r2.rr = val; break; case pf_r3: op->dataflow &= ~J_DEAD_R3; if (dead) op->dataflow |= J_DEAD_R3; op->ic.r3.i = val; break; case pf_r4: op->ic.r4.rr = val; break; case pf_dataflow: op->dataflow = val; break; case pf_cond: op->cond = val; break; default: syserr(syserr_peep_bad_field); break; } } static int32 readsfield(const PendingOp *const p, P_Field field) { switch (field) { case pf_r1: return a_reads_r1(p); case pf_r2: return a_reads_r2(p); case pf_r3: return a_uses_r3(p); case pf_r4: return a_uses_r4(p); default: return NO; } } static bool isregfield(PendingOp *op, P_Field field) { return (field == pf_r1 && a_loads_r1(op)) || readsfield(op, field); } static bool ValidField(PendingOp *ops[], P_FieldType type, int32 val, int n, IntOrP *resp, int32 *dead) { switch (type) { case pft_none: resp->i = 0; return YES; case pft_val: resp->i = val; return YES; case pft_field: if (inst_(val) <= n) { resp->i = opfield(ops[inst_(val)], field_(val), dead); return YES; } break; case pft_inst: if (inst_(val) <= n) { resp->p = ops[inst_(val)]; return YES; } break; case pft_exprn: { const PeepExprn *ex = pexprn_(val); int32 ignore; IntOrP r1, r2; if (ValidField(ops, f1type_(ex), f1_(ex), n, &r1, &ignore) && ValidField(ops, f2type_(ex), f2_(ex), n, &r2, &ignore)) switch (pe_op_(ex)) { case peo_add: resp->i = r1.i + r2.i; return YES; case peo_sub: resp->i = r1.i - r2.i; return YES; case peo_or: resp->i = r1.i | r2.i; return YES; case peo_and: resp->i = r1.i & r2.i; return YES; case peo_eor: resp->i = r1.i ^ r2.i; return YES; case peo_shr: resp->i = r1.i >> r2.i; return YES; case peo_shl: resp->i = r1.i << r2.i; return YES; case peo_div: resp->i = r1.i / r2.i; return YES; case peo_mul: resp->i = r1.i * r2.i; return YES; case peo_proc1:return (pprocs[pe_fn_(ex)])(resp, r1); case peo_proc2:return ((P2Proc *)pprocs[pe_fn_(ex)])(resp, r1, r2); } } break; } return NO; } /* This function checks whether a jopcode (after replacement) is still a * valid jopcode. The register usage and the register clashes are * currently checked. */ static bool isvalid_jopcode(PendingOp *p) { char *errmsg = CheckJopcodeP(p, JCHK_MEM | JCHK_REGS); if (localcg_debug(2) && errmsg != NULL) cc_msg("--- Invalid substitution: %s\n", errmsg); return errmsg == NULL; } #define DummyReg 31 #define Op_Altered 1 #define Op_Cant 2 static int UpdateOp(PendingOp *op, PendingOp *ops[], PeepHole const *p, int count, int ix, RegisterUsage *u, bool check_only) { int result = 0; IntOrP val; PeepReplace const *r = &replacements[ix]; for (; --count >= 0; r++) { int32 dead = 0; switch (pr_type_(r)) { case prt_kill: op->ic.op = J_NOOP; op->peep = 0; op->dataflow = 0; result = Op_Altered; break; case prt_proc: if (valproc_(r)(op, ops, u)) result |= Op_Altered; break; case prt_set: ValidField(ops, pr_valtype_(r), pr_val_(r), p->instcount-1, &val, &dead); setopfield(op, pr_field_(r), val.i, dead); result |= Op_Altered; break; case prt_swapr2r3: { RealRegister r2 = op->ic.r2.rr; int32 df = op->dataflow; op->ic.r2.rr = op->ic.r3.i; op->ic.r3.i = r2; df &= ~(J_DEAD_R2 | J_DEAD_R3); if (op->dataflow & J_DEAD_R2) df |= J_DEAD_R3; if (op->dataflow & J_DEAD_R3) df |= J_DEAD_R2; op->dataflow = df; result |= Op_Altered; break; } case prt_asr: if (!check_only) { ValidField(ops, pr_valtype_(r), pr_val_(r), p->instcount-1, &val, &dead); AdjustStackRefs(op+1, ops[-1], val.i, p-patterns+1); result |= Op_Altered; } break; } } if (!isvalid_jopcode(op)) result |= Op_Cant; if (!check_only && (result & Op_Cant)) syserr("UpdateOp - peephole substitution failed"); return result; } static int notcall(RegisterUsage *u, IntOrP p) { IGNORE(u); return ((p.p->ic.op & J_TABLE_BITS) <= J_LAST_JOPCODE) ? (p.p->ic.op != J_OPSYSK && p.p->ic.op != J_CALLK && p.p->ic.op != J_CALLR && p.p->ic.op != J_TAILCALLR && p.p->ic.op != J_TAILCALLK) : !(a_attributes(p.p->ic.op) & _a_call); } static int notleafproc(RegisterUsage *u) { IGNORE(u); return (procflags & NONLEAF) != 0 && !(pcs_flags & PCS_NOFP) && !(procauxflags & bitoffnaux_(s_irq)); } static int regset_unused(RegisterUsage *u, IntOrP p) { return !((u->use | u->def) & p.i); } static int regset_unkilled(RegisterUsage *u, IntOrP p) { return !(u->def & p.i); } static int movc_pres_r1r2(RegisterUsage *u, IntOrP p1, IntOrP p2) { IGNORE(u); return movc_preserving_r1r2(p1.p, p2.i != 0); } static int difficult_constant(RegisterUsage *u, IntOrP p) { IGNORE(u); IGNORE(p); /* $$$$$ on ARM, see if a constant will fit into a 12 bit immediate field and return it or -1 if it won't */ /* return eightbits(p.i) < 0; */ syserr("difficult_constant called"); return 1; } static int config_set(RegisterUsage *u, IntOrP p) { IGNORE(u); return (config & p.i) == p.i; } static C0Proc * const cprocs[] = { (C0Proc *)notcall, (C0Proc *)regset_unused, (C0Proc *)regset_unkilled, (C0Proc *)notleafproc, (C0Proc *)movc_pres_r1r2, 0, /* NoStackRefsBelow */ (C0Proc *)difficult_constant, (C0Proc *)config_set }; static bool MatchOp(PeepOpDef const *p, PendingOp *op) { J_OPCODE opc = op->ic.op; switch (p->type) { default: syserr(syserr_peep_bad_optype); return NO; case pot_and: return MatchOp(&peepsub1_(p), op) && MatchOp(&peepsub2_(p), op); case pot_or: return MatchOp(&peepsub1_(p), op) || MatchOp(&peepsub2_(p), op); case pot_andnot: return MatchOp(&peepsub1_(p), op) && !MatchOp(&peepsub2_(p), op); case pot_prop: return (bool)((peepprop_(p))(op)); case pot_peep: opc = op->peep; case pot_op: return opc == peepop_(p); case pot_peep_m: opc = op->peep; case pot_op_m: return (opc & peepmask_(p)) == peepopi_(p); case pot_opinset_m: opc &= peepmask_(p); case pot_opinset: { int i; int32 const *setp = &peepset_(p); for (i = 0; i < p->setcount; i++) if (opc == setp[i]) return YES; } return NO; } } static int32 UseConstraint(PendingOp *op, int constraint) { int32 res = 0; int n = pu_r1; for (; constraint != 0 && n <= pu_r3mask; n <<= 1) if (constraint & n) { constraint ^= n; switch (n) { case pu_r1: res |= regbit(op->ic.r1.rr); break; case pu_r2: res |= regbit(op->ic.r2.rr); break; case pu_r3: res |= regbit(op->ic.r3.i); break; case pu_r4: if (a_uses_r4(op)) res |= regbit(op->ic.r4.rr); break; case pu_r3mask: res |= op->ic.r3.i; } } if (constraint != 0) syserr(syserr_bad_useconstraint); return res; } static bool SatisfiedConstraint( PendingOp * ops[], PeepHole const *ph, int n, RegisterUsage *u, int i, bool okifinvalid) { #define tracing(p) (localcg_debug(2) && (p)->trace) #define CFailI2(op) \ { if (tracing(ph)) \ cc_msg("constraint %d fails: !(%ld %s %ld)\n", \ i+1, (long)f1.i, op, (long)f2.i); \ return NO; \ } PeepConstraint const *c = &ph->constraint[i]; int32 ignore; IntOrP f1, f2; if (!ValidField(ops, f1type_(c), f1_(c), n, &f1, &ignore) || !ValidField(ops, f2type_(c), f2_(c), n, &f2, &ignore)) return okifinvalid; switch (pc_type_(c)) { case pct_eq: if (f1.i == f2.i) return YES; CFailI2("=="); case pct_ne: if (f1.i != f2.i) return YES; CFailI2("!="); case pct_lt: if (f1.i < f2.i) return YES; CFailI2("<"); case pct_le: if (f1.i <= f2.i) return YES; CFailI2("<="); case pct_gt: if (f1.i > f2.i) return YES; CFailI2(">"); case pct_ge: if (f1.i >= f2.i) return YES; CFailI2(">="); case pct_ltu: if (f1.u < f2.u) return YES; CFailI2("<u"); case pct_leu: if (f1.u <= f2.u) return YES; CFailI2("<=u"); case pct_gtu: if (f1.u > f2.u) return YES; CFailI2(">u"); case pct_geu: if (f1.u >= f2.u) return YES; CFailI2(">=u"); case pct_negate: return !SatisfiedConstraint(ops, ph, n, u, (int)f1.i, !okifinvalid); case pct_or: return SatisfiedConstraint(ops, ph, n, u, (int)f1.i, okifinvalid) || SatisfiedConstraint(ops, ph, n, u, (int)f2.i, okifinvalid); case pct_proc0:if (((C0Proc *)cprocs[pc_fn_(c)])(u)) return YES; if (tracing(ph)) cc_msg("constraint %d fails\n", i); return NO; case pct_proc1:if (((C1Proc *)cprocs[pc_fn_(c)])(u, f1)) return YES; if (tracing(ph)) cc_msg("constraint %d fails\n", i); return NO; case pct_proc2:if (pc_fn_(c) != pcp_nostackrefsbelow) { if (((C2Proc *)cprocs[pc_fn_(c)])(u, f1, f2)) return YES; if (tracing(ph)) cc_msg("constraint %d fails\n", i); } else { if (NoStackReferencesBelow(f1.p, ops[-1], f2.i)) return YES; if (tracing(ph)) cc_msg("constraint %d fails: stack references in (%d, %d) below %ld\n", i, f1.p-pendingstack, ops[-1]-pendingstack, (long)f2.i); } return NO; } return YES; } static int FieldsToIgnore(PeepHole const *ph, int inst, int flags) { int n = ph->constraintcount; PeepConstraint const *pc = ph->constraint; for (; --n >= 0; pc++) { if (pc->type == pct_eq) { if (f1type_(pc) == pft_field && inst_(f1_(pc)) == inst) { P_Field field = field_(f1_(pc)); if (pf_r1 <= field && field <= pf_r4) flags |= aru_fieldbit_(field); } if (f2type_(pc) == pft_field && inst_(f2_(pc)) == inst) { P_Field field = field_(f2_(pc)); if (pf_r1 <= field && field <= pf_r4) flags |= aru_fieldbit_(field); } } } return flags; } static bool MayMatch(PendingOp *ops[], PeepOp const peepops[], PeepHole const *ph, int n, RegisterUsage *u) { int i; if (!MatchOp(&peepops[n].p, ops[n]) || (ops[n]->dataflow & dead_bits[peepops[n].dead]) != dead_bits[peepops[n].dead]) return NO; if (tracing(ph)) { cc_msg("%d: match %d ", ph - patterns+1, n); if (n != 0) cc_msg("at %d ", ops[n] - pendingstack); } for (i = 0; i < ph->constraintcount; i++) if (!SatisfiedConstraint(ops, ph, n, u, i, YES)) return NO; if (n+1 == ph->instcount) { RealRegUse reg; RegisterUsage maynot, ucopy; ucopy = *u; maynot.use = 0; RealRegisterUse(&ops[n]->ic, &reg); maynot.def = reg.c_out.map[0]; /* this takes the corrupts with outputs into account */ for (i = 0; i <= n; i++) { PeepOp const *p = &peepops[i]; PendingOp o; o = *(ops[i]); if (UpdateOp(&o, ops, ph, p->replacecount, p->replaceix, u, YES) & Op_Cant) return NO; if (tracing(ph)) { cc_msg("updated: "); a_pr_jopcode_nodeadbits(&o); } if (i == 0) AccumulateRegisterUse(&ucopy, &o, FieldsToIgnore(ph, 0, aru_ignorepreuse)); maynot.use |= UseConstraint(ops[i], peepops[i].p.maynotuse); maynot.def |= UseConstraint(ops[i], peepops[i].p.maynotkill); } if ((ucopy.use & maynot.use) || (ucopy.def & maynot.def)) { if (tracing(ph)) cc_msg("use constraint failure: ucopy <%lx %lx> maynot <%lx %lx>\n", (long)ucopy.use, (long)ucopy.def, (long)maynot.use, (long)maynot.def); return NO; } } if (tracing(ph)) cc_msg("constraints ok\n"); return YES; } static void flush_pending(int leave) { PendingOp *p = &pendingstack[0]; for (; p <= pending-leave; p++) if (p->ic.op != J_NOOP) show_inst_direct(p); if (leave == 0) { pending = &pendingstack[0]; pending->ic.op = J_NOOP; } else { int i; for (i = 0; i < leave; i++) { pendingstack[i] = pending[i-leave+1]; pr_res(&pendingstack[i], 0); } pending = &pendingstack[leave-1]; } } static bool InterferingStore(PendingOp *cur, PendingOp *prev) { #if 0 bool r; cc_msg("%08x: InterferingStore, op = %08x, r1 = %d, r2 = %d, m = %d", codebase + codep, prev->ic.op, prev->ic.r1.rr, prev->ic.r2.rr, prev->ic.m.i); #endif if ((prev->ic.op & ~J_ALIGNMENT) == J_STRK && prev->ic.r2.rr == cur->ic.r2.rr && prev->ic.r3.i != cur->ic.r3.i) { #if 0 cc_msg(" -> NO\n"); #endif return NO; } #if 0 r = a_modifies_mem(prev->ic.op) != 0; cc_msg(" -> %d\n", r); return r; #else return a_modifies_mem(prev) != 0; #endif } static void KillDeadBits(PendingOp **ops, int depth, RealRegister r, int ix) { PendingOp *limit = ops[depth]; PendingOp *p = ops[0]; for (; p >= limit; p--) { if (a_reads_r1(p) && p->ic.r1.rr == r && (p->dataflow & J_DEAD_R1)) { p->dataflow &= ~J_DEAD_R1; break; } if (a_uses_r2(p) && p->ic.r2.rr == r && (p->dataflow & J_DEAD_R2)) { p->dataflow &= ~J_DEAD_R2; break; } if (a_uses_r3(p) && (RealRegister)p->ic.r3.i == r && (p->dataflow & J_DEAD_R3)) { p->dataflow &= ~J_DEAD_R3; break; } } if (p >= limit) pr_res(p, ix+1); } static PendingOp *peephole_jopcode(int pat, PendingOp *limit, PendingOp *cur, bool toplevel) { PendingOp *ops[MaxInst+1]; PeepOp const *peepops; RegisterUsage use; PendingOp dummy[MaxInst]; int peepcount; int const *peepv; int peepix = 0; /* shut up compiler */ int depth, second; PeepHole const *curpeep; ops[1] = cur; retry: ops[0] = limit; peepcount = peepholeperop[cur->ic.op & J_TABLE_BITS].i; peepv = peepholeperop[cur->ic.op & J_TABLE_BITS].peepv; pr_cur(pat, cur, limit); for (pat = 0; pat < peepcount; pat++) { PendingOp *prev; int matched = 0; peepix = peepv[pat]; curpeep = &patterns[peepix]; Profiler_Count_Index = peepix; peepops = curpeep->insts; use.def = use.use = 0; depth = 0; for (;;) { RealRegUse reg; if (peepops[depth].p.type == pot_none) { if (!toplevel) goto next_pattern; ++depth; ops[depth] = &dummy[depth-matched-1]; dummy[depth-matched-1].ic.op = J_NOOP; dummy[depth-matched-1].peep = 0; dummy[depth-matched-1].dataflow = 0; } else { if (matched++ != 0) break; if (!MayMatch(ops+1, peepops, curpeep, depth, &use)) goto next_pattern; ops[++depth] = cur; } RealRegisterUse(&ops[depth]->ic, &reg); use.def = reg.c_in.map[0]; /* record the corrupt inputs of the first instr */ if (curpeep->instcount == depth) { second = depth; goto peephole_found; } } second = depth; for (prev = limit; pending - prev < PeepholeWindowSize; prev--) { (ops+1)[depth] = prev; if (MayMatch(ops+1, peepops, curpeep, depth, &use)) { if (++depth == curpeep->instcount) goto peephole_found; if (depth == MaxInst) syserr(syserr_bad_maxinst); } else if (curpeep->gapconstraint == G_ANY || /* ops required to be adjacent */ ((curpeep->gapconstraint & G_STR) && InterferingStore(cur, prev)) || (prev->ic.op & ~Q_MASK) == J_CONDEXEC /* allowed only if matched in pattern */) break; if (prev == pendingstack) /* run out of ops */ break; AccumulateRegisterUse(&use, prev, aru_updatekills); } next_pattern:; } goto no_peephole_found; peephole_found: { PendingOp opcopy[MaxInst]; PendingOp *opp[MaxInst+1]; int d; #ifdef ENABLE_LOCALCG p_count[peepix]++; #endif if (depth > second) for (d = 0; d < depth; d++) { if (peepops[d].p.maynotkill & pu_r1) KillDeadBits(ops, depth, (ops+1)[d]->ic.r1.rr, peepix); if (peepops[d].p.maynotkill & pu_r2) KillDeadBits(ops, depth, (ops+1)[d]->ic.r2.rr, peepix); if (peepops[d].p.maynotkill & pu_r3) KillDeadBits(ops, depth, (ops+1)[d]->ic.r3.i, peepix); } opp[0] = ops[0]; for (d = 1; d <= depth; d++) { opcopy[d-1] = *ops[d]; opp[d] = &opcopy[d-1]; } for (d = depth; --d >= 0; ) { PendingOp *op = (ops+1)[d]; if (UpdateOp(op, opp+1, curpeep, peepops[d].replacecount, peepops[d].replaceix, &use, NO) & Op_Altered) { if (d == 0) { if (op->ic.op != J_NOOP) { pat = peepix; goto retry; } } else if (d < second) { /* new op being added to top of pending stack. If it's not the only one, we must take care to maintain the 'always one slot free' guarantee. The call to flush_pending will invalidate any pointers to pendingstack we are holding, but we're not going to look at them again (since the loop on d is from lowest upward) */ if (op->ic.op != J_NOOP) limit = peephole_jopcode(peepix, limit, op, NO); if (d > 0 && limit == &pendingstack[PendingStackSize-1]) { pending++; flush_pending(PeepholeWindowSize+2); limit = pending; } } else if (op->ic.op != J_NOOP && op != &pendingstack[0]) { PendingOp temp; temp = *op; op->ic.op = J_NOOP; op->peep = 0; op->dataflow = 0; (void)peephole_jopcode(peepix, op-1, &temp, NO); } else { pr_res(op, peepix+1); } } else if (tracing(curpeep)) { cc_msg("unchanged "); pr_res(op, peepix+1); } } } no_peephole_found: if (cur->ic.op != J_NOOP) { if (limit < pendingstack || limit->ic.op != J_NOOP) limit++; if (limit >= &pendingstack[PendingStackSize]) syserr(syserr_pendingstack_overflow); *limit = *cur; pr_res(limit, pat == peepcount ? 0 : peepix+1); } Profiler_Count_Index = 0; return limit; } /* Exported routines... */ /* The peepholer: */ void peephole_op(PendingOp *cur, bool flush) { if (var_cc_private_flags & 8L) { #ifdef ACDEBUG2 print_jopcode(cur->ic); #endif show_inst_direct(cur); } else { pending = peephole_jopcode(-1, pending, cur, YES); if (flush) flush_pending(0); else if (pending == &pendingstack[PendingStackSize-1]) flush_pending(PeepholeWindowSize+2); } } void peephole_reinit(void) { pendingstack = (PendingOp *)SynAlloc(PendingStackSize * sizeof(PendingOp)); pending = &pendingstack[0]; pending->ic.op = J_NOOP; } void peephole_init(void) { #ifdef ENABLE_LOCALCG int i; for (i = 0; i <= PeepholeMax; i++) p_count[i] = 0; #endif } void peephole_tidy(void) { #ifdef ENABLE_LOCALCG if (localcg_debug(1) || debugging(DEBUG_STORE)) { int i; for (i = 0; i <= PeepholeMax; i++) if (p_count[i] != 0) cc_msg("{%3d}%6ld\n", i+1, p_count[i]); } #endif }
stardot/ncc
util/striphdr.c
/* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ /* * C compiler support file StripHdrs.c * Copyright (C) Codemist Ltd, 1987. * Copyright (C) Acorn Computers Ltd., 1988 * SPDX-Licence-Identifier: Apache-2.0 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stddef.h> #include <time.h> #define MAXPATHS 10 #define MAXEXCEPTIONS 10 #define MAXFILENAMESZ 256 #define MAXLINELEN 256 static char *headers = ""; static char *viafile = 0; static lastchar = 0; static npaths = 0; static int nerrors = 0; static char *paths[MAXPATHS]; static char file_name[MAXFILENAMESZ]; static void outch(ch, fh) int ch; FILE *fh; { if (lastchar==ch) return; if (lastchar=='\n') { /*putc('\n', fh);*/ lastchar = ' '; } else lastchar = 0; switch (ch) { case '\\': case '\'': case '\"': fprintf(fh, "%c", ch); return; case '\n': fprintf(fh, "\n"); lastchar = '\n'; return; case ' ': lastchar = ' '; default: putc(ch, fh); return; } } /* The following are states in a machine that detects & deletes comments */ #define NORMAL 0x0 #define STRING 0x1 #define CHAR 0x2 #define STRBACK 0x3 #define CHARBACK 0x4 #define SLASH 0x5 #define COMMENT 0x6 #define STAR 0x7 static FILE *path_open(name, mode) char *name, *mode; { FILE *f; int j; for (j = 0; j < npaths; ++j) { strcpy(file_name, paths[j]); strcat(file_name, name); f = fopen(file_name, mode); if (f != NULL) return f; } return NULL; } static void copy_header(fh, name) FILE *fh; char *name; { FILE *fh1; int ch, state = NORMAL; char year[32]; time_t now; char ansi_name[256]; fh1 = path_open(name, "r"); if (fh1==NULL) { fprintf(stderr, "Unable to read input file %s\n", name); ++nerrors; return; } strcpy(ansi_name,headers); strcat(ansi_name, name); fprintf(stderr, "StripHdrs: Copying %s as %s\n", file_name, ansi_name); now = time(NULL); strftime(year, sizeof(year), "%Y", localtime(&now)); fprintf(fh, "\ /* %s.h\n\ * Copyright (C) Acorn Computers Ltd., %s\n\ * Copyright (C) Codemist Ltd., %s\n\ */\n", name, year, year); lastchar = '\n'; while ((ch=getc(fh1))!=EOF) { switch (state) { case NORMAL: switch (ch) { case '\'': outch(ch, fh); state = CHAR; break; case '\"': outch(ch, fh); state = STRING; break; case '/': state = SLASH; break; default: outch(ch, fh); break; } break; case STRING: switch (ch) { case '\"': outch(ch, fh); state = NORMAL; break; case '\\': outch(ch, fh); state = STRBACK;break; default: outch(ch, fh); break; } break; case CHAR: switch (ch) { case '\'': outch(ch, fh); state = NORMAL; break; case '\\': outch(ch, fh); state = CHARBACK;break; default: outch(ch, fh); break; } break; case STRBACK: outch(ch, fh); state = STRING; break; case CHARBACK: outch(ch, fh); state = CHAR; break; case SLASH: switch (ch) { case '*': state = COMMENT;break; case '\'': outch('/', fh); outch(ch, fh); state = CHAR; break; case '\"': outch('/', fh); outch(ch, fh); state = STRING; break; default: outch('/', fh); outch(ch, fh); state = NORMAL; break; } break; case COMMENT: if (ch == '*') state = STAR; break; case STAR: switch (ch) { case '/': state = NORMAL; break; case '*': break; default: state = COMMENT;break; } break; default: fprintf(stderr, "\nBad state %d\n", state); exit(1); } } if (state!=NORMAL || lastchar!='\n') { fprintf(stderr, "\nUnexpected end of file in %s?\n", file_name); ++nerrors; } fclose(fh1); } int main(argc, argv) int argc; char *argv[]; { int j; char *arg; FILE *fh, *vf; char stripped_file[256]; char hdrfile[256]; nerrors = npaths = 0; for (j = 1; j < argc; ++j) { arg = argv[j]; if (arg[0] == '-') { switch (arg[1]) { case 'h': case 'H': break; case 'i': case 'I': if (npaths >= MAXPATHS) { fprintf(stderr, "StripHdrs: Too many paths - only %u allowed\n", MAXPATHS); exit(1); } else { arg += 2; if (*arg == 0) arg = argv[++j]; paths[npaths++] = arg; } break; case 'o': case 'O': arg += 2; if (*arg == 0) arg = argv[++j]; headers = arg; break; case 'f': case 'F': arg += 2; if (*arg == 0) arg = argv[++j]; viafile = arg; default: break; } } } fprintf(stderr, "StripHdrs: Creating %s...\n", headers); if (nerrors == 0) { for (j = 1; j < argc; ++j) { arg = argv[j]; strcpy(stripped_file,headers); strcat(stripped_file,arg); if (arg[0] != '-') { fh = fopen(stripped_file, "w"); copy_header(fh, arg); fclose(fh); } } if (viafile != 0) { vf = fopen (viafile, "r"); while ((fgets(hdrfile, 256, vf))!=0) { hdrfile[strlen(hdrfile)-1] = '\0'; strcpy(stripped_file,headers); strcat(stripped_file,hdrfile); fh = fopen(stripped_file, "w"); copy_header(fh, hdrfile); fclose(fh); } fclose(vf); } } if (nerrors == 0) fprintf(stderr, "StripHdrs: Finished\n"); else { fclose(fh); fprintf(stderr,"\nStripHdrs: %s is junk because of errors\n\n",headers); exit(1); } return 0; }
stardot/ncc
mip/drivhelp.h
/* * drivhelp.c -- help text for Norcroft C/FORTRAN compiler, version 1b. * Copyright (C) Codemist Ltd., 1989. * Copyright (C) Acorn Computers Ltd., 1989. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ /* The help text here is not what is wanted on non-Acorn machines, and */ /* is also not what is wanted for a Lint system. */ /* parameterisation here seems in the process of getting out of hand! */ static msg_t driver_help_text[] = { #ifdef msg_driver_help /* to allow options.h to define */ msg_driver_help, #else #ifndef TARGET_IS_UNIX /* Arthur and Brazil -help text */ #ifdef PASCAL /*ECN*/ help_usage, help_main_options, help_blank, help_list, /* -list */ help_iso, /* -iso */ help_blank, help_dont_link, /* -c */ help_leave_comments, /* -C */ help_predefine, /* -D<symbol> */ help_preprocess_pascal, /* -E */ help_compiler_features, /* -F<options> */ help_runtime_checks, /* -R<options> */ help_debug, /* -g<options> */ help_include_I, /* -I<directory> */ help_include_J, /* -J<directory> */ help_libraries, /* -L<libs> */ help_output, /* -o<file> */ help_profile, /* -P<options> */ help_output_assembler, /* -S */ help_preundefine, /* -U<symbol> */ help_disable_warnings, /* -W<options> */ #else #ifndef FORTRAN help_usage, help_main_options, help_blank, help_list, /* -list */ help_pcc, /* -pcc */ help_blank, help_dont_link, /* -c */ help_leave_comments, /* -C */ help_predefine, /* -D<symbol> */ help_preprocess_c, /* -E */ help_compiler_features, /* -F<options> */ help_debug, /* -g<options> */ help_include_I, /* -I<directory> */ help_include_J, /* -J<directory> */ help_libraries, /* -L<libs> */ help_output, /* -o<file> */ help_profile, /* -P<options> */ help_output_assembler, /* -S */ help_preundefine, /* -U<symbol> */ help_disable_warnings, /* -W<options> */ #else /* FORTRAN */ help_usage, help_main_options, help_blank, help_f66, /* -f66 */ help_list, /* -list */ help_blank, help_dont_link, /* -c */ help_leave_comments, /* -C */ help_predefine, /* -D<symbol> */ help_preprocess_fortran, /* -E */ help_compiler_features, /* -F<options> */ help_debug, /* -g<options> */ help_include_I, /* -I<directory> */ help_include_J, /* -I<directory> */ help_libraries, /* -L<libs> */ help_output, /* -o<file> */ help_profile, /* -P<options> */ help_output_assembler, /* -S */ help_preundefine, /* -U<symbol> */ help_disable_warnings, /* -W<options> */ #endif /* FORTRAN */ #endif /* PASCAL */ #else /* TARGET_IS_UNIX */ #ifdef PASCAL /*ECN*/ #define msg_driver_help , help_blank, help_usage, help_main_options, help_blank, help_iso, /* -iso */ help_dont_link_invoke, /* -c */ help_leave_comments, /* -C */ help_predefine_pp, /* -D<symbol> */ help_preprocess_pascal, /* -E */ help_compiler_features, /* -F */ help_debug_noopt, /* -g */ help_include_I, /* -I<directory> */ help_list, /* -list */ help_makefile, /* -M<options> */ help_output_space, /* -o <file> */ help_optimised, /* -O */ help_profile_lc, /* -p<options> */ help_readonly_strings, /* -R */ help_generate_assembler, /* -S */ help_preundefine_pp, /* -U<symbol> */ help_disable_warnings_lc, /* -w<options> */ #else #ifndef FORTRAN #define msg_driver_help , help_blank, help_usage, help_main_options, help_blank, help_ansi, /* -ansi */ help_pcc_bsd, /* -pcc */ help_dont_link_invoke, /* -c */ help_leave_comments, /* -C */ help_predefine_pp, /* -D<symbol> */ help_preprocess_c, /* -E */ help_compiler_features, /* -F<options> */ help_debug_noopt, /* -g */ help_include_I, /* -I<directory> */ help_list, /* -list */ help_makefile, /* -M<options> */ help_output_space, /* -o <file> */ help_optimised, /* -O */ help_profile_lc, /* -p<options> */ help_readonly_strings, /* -R */ help_generate_assembler, /* -S */ help_preundefine_pp, /* -U<symbol> */ help_disable_warnings_lc, /* -w<options> */ #else /* FORTRAN */ #define msg_driver_help , help_bsd_f77, help_usage, help_main_options, help_blank, help_dont_link_invoke, /* -c */ help_f66, /* -f66 */ help_debug_noopt, /* -g */ help_16bit_ints, /* -i2 */ help_list, /* -list */ help_onetrip, /* -onetrip */ help_output_space, /* -o <file> */ help_optimised, /* -O */ help_profile_lc, /* -p<options> */ help_readonly_strings_lc, /* -r */ help_strict, /* -strict */ help_generate_assembler, /* -S */ help_dont_downcase, /* -U */ help_disable_warnings_lc, /* -w<options> */ #endif /* FORTRAN */ #endif /* PASCAL */ #endif /* TARGET_IS_UNIX */ #endif /* msg_driver_help */ NULL }; /* end of mip/drivhelp.h */
stardot/ncc
mip/cg.c
<gh_stars>0 /* * C compiler file cg.c * Copyright (C) Codemist Ltd, 1988. * Copyright (C) Acorn Computers Ltd., 1988. * Copyright 1991-1997 Advanced Risc Machines Limited. All rights reserved * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 119 * Checkin $Date$ * Revising $Author$ */ /* AM memo: remove smashes to tree for long-term safety (e.g. find s_neg) */ /* AM memo: bug in cse/deadcode kills fp voided div. */ /* AM Mar 89: Add s_wstring (treated here as s_string). Memo: later add */ /* J_WSTRING similar to J_STRING for cross sex compilation. */ /* AM Nov 88: Remove some (only!!!) magic numbers on mcreps for optional */ /* double alignment. */ /* Memo: tidy up the current_/greatest_stackdepth edifice. */ /* see cg_exprreg() for half developed code to optimise the JOP */ /* code to save space (and possibly time in regalloc). */ /* Note to reader: the order of routines in here is extremely unnatural */ /* (hence the large number of inane 'static' forward references below). */ /* It is so that the largest routine gets compiled first to save */ /* (compile-time) space. Yuk. Undoes rationalisation of 4/12/86. */ /* * ACN Feb 90: rework struct args support and '...' for 88000 etc. * AM aug 87: improve the code for x.a++ etc, following ACN's LDRVK. * ACN aug 87 add 'valof' block extension. Buggy for structs still. * AM 20-jun-87 fix bug in cg_cond on structs. fix fp/int reg confusion * if registers active at cg_fnap. Redo cg_fnargs removing * 50 limit on arg count, and improving code. * AM 26-may-87 redo CASEBRANCH. Re-use store later. * AM 22-apr-87 fix bug in loadzero resulting in f()*0 doing nothing. * AM 27-dec-86 require just 2 free fpregs in cg_expr (why can't one work?) * AM 4-dec-86 put struct/unions of size 4 to regs, fix bug in f().a. * AM 4-dec-86 rationalisation(!) of order - i.e. Cmd stuff here. * AM 3-dec-86 separate 'C' case into s_break and s_endcase. */ #include <stddef.h> #include <stdlib.h> #include <string.h> #include "globals.h" #include "cg.h" #include "store.h" #include "codebuf.h" #include "aeops.h" #include "util.h" #include "xrefs.h" #include "jopcode.h" #include "regalloc.h" #include "regsets.h" #include "cse.h" #include "sr.h" #include "flowgraf.h" #include "mcdep.h" #include "aetree.h" #include "builtin.h" #include "sem.h" /* typeofexpr */ #include "syn.h" #include "simplify.h" /* mcrepofexpr */ #include "bind.h" #include "errors.h" #include "inline.h" #include "inlnasm.h" /* The following lines are in flux, but are here because similar things */ /* are wanted if TARGET_IS_ALPHA. They also highlight the dependency */ /* on alignof_struct==4 of code for struct-return in registers. */ /* MEMCPYREG, MEMCPYQUANTUM now in defaults.h (needed by */ /* returnsstructinregs()) */ #if MEMCPYREG == DBLREG #define J_memcpy(op) ((op&~J_ALIGNMENT) - J_LDRK + (J_LDRDK|J_ALIGN8)) #else #define J_memcpy(op) (op) #endif #define MOVC_ALIGN_MAX alignof_toplevel_auto #define MOVC_ALIGN_MIN alignof_int /* most old code */ #ifdef NEW_J_ALIGN_CODE /* But this isn't quite true for TARGET_IS_ALPHA stack vars... */ # define J_ALIGN4V (alignof_toplevel_auto==8 ? J_ALIGN8 : J_ALIGN4) #else # define J_ALIGN4V J_ALIGN4 #endif /* The next routine is a nasty hack -- see its uses. */ /* It copies a SynAlloc BindList into a BindAlloc one. */ static SynBindList *binderise(SynBindList *l) { SynBindList *f1 = NULL; for (; l != NULL; l = l->bindlistcdr) f1 = (SynBindList *)mkBindList(f1, l->bindlistcar); return (SynBindList *)dreverse((List *)f1); } #define NOTALABEL ((LabelNumber *)DUFF_ADDR) #define NOTINLOOP NOTALABEL #define NOTINSWITCH NOTALABEL static int32 max_icode, max_block; /* statistics (lies, damn lies) */ static Cmd *cg_current_cmd; static int32 current_stackdepth; static BindList *local_binders, *regvar_binders; static Binder *integer_binder, *double_pad_binder; bool has_main; static bool defining_main; static bool cg_infobodyflag; static struct SwitchInfo { BindList *binders; /* 'endcase' may be non-local goto */ LabelNumber *defaultlab, *endcaselab; } switchinfo; static struct LoopInfo { BindList *binders; /* 'break', 'continue' may be non-local goto */ LabelNumber *breaklab, *contlab; } loopinfo; #ifdef EXTENSION_VALOF static struct ValofInfo { BindList *binders; LabelNumber *lab; VRegnum r; } valofinfo; #endif typedef struct CasePair { int32 caseval; LabelNumber *caselab;} CasePair; static VRegnum cg_expr1(Expr *x,bool valneeded); #ifndef ADDRESS_REG_STUFF #define ensure_regtype(r,rsort) (r) #endif #define IsVolatile 1 #define IsUnaligned 2 #define BaseIsWordAligned 4 static VRegnum cg_stind(VRegnum r, Expr *val, Expr *x, const int32 flag, Binder *b, const int32 mcmode, const int32 mclength, bool address, int volatileorunaligned); static VRegnum cg_var(VRegnum r, Binder *b, AEop flag, int32 mcmode, int32 mclength, bool address); static VRegnum reserveregister(RegSort precision); static VRegnum getreservedreg(VRegnum r); static void cg_bindlist(SynBindList *x,bool initflag); static Binder *is_local_adcon(Expr *a); static Expr *take_address(Expr *e); static VRegnum open_compilable(Expr **xp,RegSort rsort,bool valneeded); static VRegnum cg_fnap(Expr *x,VRegnum resreg,bool valneeded); static VRegnum cg_cond (Expr *c,bool valneeded,VRegnum targetreg, LabelNumber *l3,bool structload); static VRegnum cg_cast1(Expr *x1,int32 mclength,int32 mcmode); static VRegnum cg_cast1_(VRegnum r, int32 mclength, int32 mcmode, int32 argrep); static VRegnum cg_addr(Expr *sv,bool valneeded); #ifdef EXTENSION_VALOF static void cg_cmd(Cmd *x); #endif static void structure_assign(Expr *lhs,Expr *rhs,int32 length); static void verify_integer(Expr *x); static VRegnum cg_binary(J_OPCODE op,Expr *a1,Expr *a2,bool commutesp, RegSort fpp); static VRegnum cg_binary_or_fn(J_OPCODE op,TypeExpr *type,Expr *fname, Expr *a1,Expr *a2,bool commutesp); #define iszero(x) is_intzero(x) #define isone(x) is_intone(x) #define isminusone(x) is_intminusone(x) static int32 ispoweroftwo(Expr *x); static VRegnum cg_loadconst(int32 n,Expr *e); static void cg_count(FileLine fl); static void cg_return(Expr *x, bool implicitinvaluefn); static void cg_loop(Expr *init, Expr *pretest, Expr *step, Cmd *body, Expr *posttest); static void cg_test(Expr *x, bool branchtrue, LabelNumber *dest); static void casebranch(VRegnum r, CasePair *v, int32 ncases, LabelNumber *defaultlab); static void cg_case_or_default(LabelNumber *l1); static void cg_condjump(J_OPCODE op,Expr *a1,Expr *a2,RegSort rsort,J_OPCODE cond,LabelNumber *dest); static void emituse(VRegnum r,RegSort rsort); static VRegnum load_integer_structure(Expr *e); static Binder *gentempvar(TypeExpr *t, VRegnum r); static void cg_cond1(Expr *e, bool valneeded, VRegnum targetreg, LabelNumber *l3, bool structload); /* result_variable is an extra first arg. for use with structure returning */ /* functions - private to cg_return and cg_topdecl */ static Binder *result_variable, *result_temporary; static LabelNumber *structretlab; #define lowerbits(n) (((int32)1<<(n))-1) /*************************************************************************/ /* Start of codegeneration proper. */ /*************************************************************************/ static bool ContainsUnalignedSubExpr(Expr *x) { for (;;) switch (h0_(x)) { case s_integer: case s_floatcon: case_s_any_string case s_binder: return NO; /* monadic things... */ case s_content: case s_content4: if (isunaligned_expr(x)) return YES; x = arg1_(x); continue; case s_cast: if (isunaligned_type(type_(x))) return YES; /* fall through */ case s_bitnot: case s_boolnot: case s_monplus: case s_neg: case s_addrof: x = arg1_(x); continue; case s_cond: /* due to the fact that operands from s_cond are never combined */ /* we do not need the complexity of binary operators below. */ return ContainsUnalignedSubExpr(arg1_(x)) || ContainsUnalignedSubExpr(arg2_(x)) || ContainsUnalignedSubExpr(arg3_(x)); case s_assign: case s_displace: case s_andand: case s_oror: case s_equalequal: case s_notequal: case s_greater: case s_greaterequal: case s_less: case s_lessequal: case s_comma: case s_and: case s_plus: case s_minus: case s_leftshift: case s_or: case s_rightshift: case s_xor: case s_times: case s_div: case s_rem: return ContainsUnalignedSubExpr(arg1_(x)) || ContainsUnalignedSubExpr(arg2_(x)); case s_let: x = arg2_(x); continue; case s_fnap: if (ContainsUnalignedSubExpr(arg1_(x))) return YES; { ExprList *l = exprfnargs_(x); for (; l != NULL; l = cdr_(l)) if (ContainsUnalignedSubExpr(exprcar_(l))) return YES; } default: return NO; } } #if defined TARGET_HAS_SCALED_ADDRESSING || defined TARGET_HAS_SCALED_OPS || \ defined TARGET_HAS_SCALED_ADD #ifndef target_shiftop_allowed #define target_shiftop_allowed(n, len, mode, op) target_scalable(n, len) #endif #define unsigned_expression_(x) \ ((mcrepofexpr(x) >> MCR_SORT_SHIFT) == 1) static Expr *ignore_ineffectual_casts(Expr *x) { for (; h0_(x) == s_cast; x = arg1_(x)) { int32 resrep = mcrepofexpr(x), argrep = mcrepofexpr(arg1_(x)); int32 ressort = resrep & MCR_SORT_MASK, argsort = argrep & MCR_SORT_MASK; if (ressort > MCR_SORT_UNSIGNED || argsort > MCR_SORT_UNSIGNED) break; { int32 ressize = resrep & MCR_SIZE_MASK, argsize = argrep & MCR_SIZE_MASK; if (ressort == argsort) { if (ressize < argsize) break; } else if (ressize != argsize || ressize < 4) break; } } return x; } static Expr *shift_op1(Expr *x, int32 n) { if (n==0) syserr(syserr_cg_shift0); while ((n & 1)==0) n >>= 1; if (n==1) return x; return mk_expr2(s_times, te_int, x, mkintconst(te_int, n, 0)); } static Expr *shift_operand(Expr *x) /* if is_shifted() returned true this can be used to extract the operand */ { int32 n; Expr *arg; x = ignore_ineffectual_casts(x); switch (h0_(x)) { case s_rightshift: case s_leftshift: arg = arg2_(x); if (h0_(arg) == s_integer && intval_(arg)==0) return shift_operand(arg1_(x)); return arg1_(x); case s_times: arg = arg1_(x); if (h0_(arg)==s_integer) { n = intval_(arg); if ((n & 1)==0) return shift_op1(arg2_(x), n); } else return shift_op1(arg1_(x), intval_(arg2_(x))); default: syserr(syserr_not_shift); return x; } } static int32 shift_amount(Expr *x) /* if is_shifted() returned true this can be used to extract the shift */ { int32 n; Expr *arg; x = ignore_ineffectual_casts(x); switch (h0_(x)) { case s_rightshift: n = intval_(arg2_(x)); if (n == 0) return shift_amount(arg1_(x)); /* This is a horrid packing scheme */ n = (n & SHIFT_MASK) | SHIFT_RIGHT; if (!unsigned_expression_(arg1_(x))) n |= SHIFT_ARITH; return n; case s_leftshift: arg = arg2_(x); n = intval_(arg); if (n == 0) return shift_amount(arg1_(x)); return n & SHIFT_MASK; case s_times: arg = arg1_(x); if (h0_(arg)==s_integer) { n = intval_(arg); if ((n & 1)==0) return logbase2(n) & SHIFT_MASK; } arg = arg2_(x); if (h0_(arg)==s_integer) { n = intval_(arg); if ((n & 1)==0) return logbase2(n) & SHIFT_MASK; } /* drop through */ default: syserr(syserr_not_shift1); return 0; } } static int32 is_shifted(Expr *x, int32 mclength, int32 signedness, int32 op) /* Predicate to test if an expression is of the form something shifted. */ /* 11-Nov-87: changed to consult target_scalable() for 32016/vax. */ /* Used to decide if scaled indexed addressing is wanted. */ /* * mclength is zero for scaled-op investigation, or 1, 2, 4 or 8 for byte, * short, long or double memory references. It is -1, -2, -4 or -8 for * memory references where the scaled index must be subtracted from the * base value rather than added. mclength is just handed down to a * target specific test for validity. */ { int32 n; Expr *arg; x = ignore_ineffectual_casts(x); switch (h0_(x)) { case s_rightshift: case s_leftshift: arg = arg2_(x); if (h0_(arg)!=s_integer) return 0; n = intval_(arg); if (n == 0) return is_shifted(arg1_(x), mclength, signedness, op); if (n>=0 && n<=31) return target_shiftop_allowed(shift_amount(x), mclength, signedness, op); else return 0; case s_times: /* detect multiplication by 2, 4, 6, ... */ if ((arg = arg1_(x), h0_(arg)) == s_integer || (arg = arg2_(x), h0_(arg)) == s_integer) { n = intval_(arg); if (n!=0 && (n & 1)==0) return target_shiftop_allowed(shift_amount(x), mclength, signedness, op); } return 0; default: return 0; } } #endif /* TARGET_HAS_SCALED_ADDRESSING or _OPS */ /* The code that follows is too simplistic - I need a better estimate of */ /* the complexity of expressions, e.g. an estimate of the number of regs */ /* needed to evaluate something. */ /* values for nastiness() */ #define ISCONST 0x100 /* assumed minimum for nastiness() */ #define ISXCONST 0x101 /* floating, string, (addrof one day -- ask AM) */ #define ISBIND 0x102 #define ISEXPR 0x103 /* ISHARD *MUST BE* the maximum nastiness() can return: */ /* such expressions have function applications in them -- allows 2^10 */ /* terms in an expression (without fn calls) before we have to truncate */ /* to avoid hitting the ISHARD ceiling. See nastiness(). */ #define ISHARD (ISEXPR+10) /* assumed maximum for nastiness() */ static int nastiness(Expr *x) { /* This procedure is used to provide an heuristic that helps me decide */ /* what order to prepare arguments for functions in. It a value between */ /* ISCONST and ISHARD to show if the expression x contains any function */ /* calls (which clobber lots of regs) or otherwise a value estimating */ /* the likely number of registers the expression is liable to take. */ AEop op; int n1, n2, n3, nr; #define max_(a,b) ((a)>=(b) ? (a):(b)) for (;;) switch (op = h0_(x)) { case s_integer: return ISCONST; case s_floatcon: case s_int64con: case_s_any_string return ISXCONST; case s_binder: return ISBIND; /* monadic things... */ case s_content: case s_content4: #if 0 { int32 m = mcrepofexpr(x); if ((m >> MCR_SORT_SHIFT) == 3 && (m & MCR_SIZE_MASK) > 4) return ISHARD; /* big struct */ } #endif if (memory_access_checks) return(ISHARD); case s_cast: case s_bitnot: case s_boolnot: case s_monplus: case s_neg: case s_addrof: x = arg1_(x); continue; case s_cond: /* due to the fact that operands from s_cond are never combined */ /* we do not need the complexity of binary operators below. */ nr = nastiness(arg1_(x)); n2 = nastiness(arg2_(x)); nr = max_(nr,n2); n3 = nastiness(arg3_(x)); nr = max_(nr,n3); return max_(ISEXPR, nr); case s_assign: case s_displace: { int32 m = mcrepofexpr(x); if ((m >> MCR_SORT_SHIFT) == 3 && (m & MCR_SIZE_MASK) > 4) return ISHARD; /* big struct */ } /* drop through */ case s_andand: case s_oror: case s_equalequal: case s_notequal: case s_greater: case s_greaterequal: case s_less: case s_lessequal: case s_comma: case s_and: case s_plus: case s_minus: case s_leftshift: case s_or: case s_rightshift: case s_xor: case s_times: case s_div: case s_rem: n1 = nastiness(arg1_(x)); n2 = nastiness(arg2_(x)); /* A good estimate of the complexity (number of temp registers needed) */ /* n1==n2 ? n1+1 : max(n1,n2), */ /* but modify the middle term so that we never exceed ISHARD, nor */ /* even attain it unless one term is ISHARD (thus ISHARD terms are only */ /* those containing function like things). See cg_fnargs for why. */ nr = n1==n2 ? (n1>=ISHARD-1 ? n1 : n1+1) : max_(n1,n2); #ifndef TARGET_HAS_MULTIPLY /* See if we will need a proc. call on the ARM and similar. */ /* However, this 'better' code seems to compile a slightly 0.01% */ /* bigger compiler than if we omit the conjuncts which check for */ /* (const) multiplies which do not require a function call!!!! */ /* Leave in the 'notionally correct code'. */ if (op == s_times && h0_(arg1_(x)) != s_integer && h0_(arg2_(x)) != s_integer) return ISHARD; #endif #ifndef TARGET_HAS_DIVIDE if ((op == s_div || op == s_rem) && h0_(arg2_(x)) != s_integer) return ISHARD; #endif return max_(ISEXPR, nr); /* always a little bit hard. */ case s_let: x = arg2_(x); continue; default: /* includes s_fnap */ return ISHARD; } #undef max_ } #define unsigned_expression_(x) \ ((mcrepofexpr(x) >> MCR_SORT_SHIFT) == 1) static RegList *usedregs, *usedfpregs; static int32 nusedregs, nusedfpregs, spareregs, sparefpregs, nreservedregs; static BindList *datasegbinders; #define NOT_OPEN_COMPILABLE ((VRegnum)(-2)) /* Temp - real distinguished non-GAP VRegnum wanted */ #define cg_loadzero(e) cg_loadconst(0,e) #ifdef TARGET_HAS_DIVIDE #define cg_divrem(op,type,fname,a1,a2) \ cg_binary(op,a1,a2,0,INTREG) #else #define cg_divrem(op,type,fname,a1,a2) \ cg_binary_or_fn(op,type,fname,a1,a2,0) #endif #define mkArg(x,y) ((Expr*)mkExprList(x,y)) #define mkArgList1(x) ((Expr*)mkExprList(0,x)) #define mkArgList2(x,y) ((Expr*)mkExprList(mkExprList(0,y),x)) #define mkArgList3(x,y,z) ((Expr*)mkExprList(mkExprList(mkExprList(0,z),y),x)) VRegnum cg_exprvoid(Expr *x) { return cg_expr1(x, NO); } VRegnum cg_expr(Expr *x) { return cg_expr1(x, YES); } static VRegnum cg_diadvoid(Expr *x) { cg_expr1(arg1_(x), NO); return cg_expr1(arg2_(x), NO); } static VRegnum cg_multiply(TypeExpr *type, Expr *a1, Expr *a2) { #ifdef TARGET_HAS_MULTIPLY IGNORE(type); return cg_binary(J_MULR, a1, a2, 1, INTREG); #else return cg_binary_or_fn(J_MULR, type, sim.mulfn, a1, a2, 1); #endif } static VRegnum cg_unary_i(J_OPCODE op, RegSort rsort, Expr *x) { VRegnum r, r1; #ifdef TARGET_HAS_SCALED_OPS if (op == J_NOTR && is_shifted(x, 0, 0, 0)) { r1 = cg_expr(shift_operand(x)); r = fgetregister(rsort); emitshift(op, r, GAP, r1, shift_amount(x)); } else #endif { r1 = cg_expr(x); r = fgetregister(rsort); emitreg(op, r, GAP, r1); } bfreeregister(r1); return r; } /* @@@ what about LNGREG? */ static J_OPCODE floatyop(RegSort rsort, J_OPCODE j_i, J_OPCODE j_f, J_OPCODE j_d) { return rsort == DBLREG ? j_d : rsort == FLTREG ? j_f : j_i; } /* Maybe the following routine will subsume cg_expr2 one day. */ static VRegnum cg_exprreg(Expr *x, VRegnum r) /* Used to save (virtual) registers for simple expressions which must */ /* then be moved to a specified register (e.g. cond/fn_arg/fn_result). */ /* Note that targetreg here is only 'reserved' not 'got'. The */ /* caller of cg_cond will getreservedreg() on return to avoid */ /* overestimating temporary register use. */ { switch (h0_(x)) { case s_integer: if (usrdbg(DBG_LINE) && exprfileline_(x) != 0) emitfl(J_INFOLINE, *exprfileline_(x)); emit(J_MOVK, r, GAP, intval_(x)); break; case_s_any_string emitstring(J_STRING, r, exs_(x)->strseg); break; #ifdef EVEN_FINER_DAY case s_binder: ... break; #endif case s_cond: { LabelNumber *l3 = nextlabel(); /* Previous phases of the compiler must have arranged that the two arms */ /* of the condition each have the same mode. In particular they must */ /* either be both integer or both floating point values. This has to */ /* include the possibility of them being voided. Structure values are */ /* not legal here. */ (void)cg_cond(x, 1, r, l3, 0); start_new_basic_block(l3); } break; /* n.b. do not use with with s_addrof due to loadadcon() slaving */ default: { VRegnum r2 = cg_expr1(x, 1); RegSort rsort = vregsort(r2); emitreg(floatyop(rsort, J_MOVR, J_MOVFR, J_MOVDR), r, GAP, r2); bfreeregister(r2); } break; } return r; /* may be useful */ } #ifdef TARGET_HAS_DIVIDE #ifdef TARGET_LACKS_REMAINDER /* Use this if the target has divide but not remainder opcodes */ static VRegnum simulate_remainder(TypeExpr *t, Expr *a1, Expr *a2) { Binder *gen1 = gentempbinder(t); Binder *gen2 = gentempbinder(t); /* { int a1= arg1, a2 = arg2; a1 - (a1/a2)*a2; } */ Expr *x = mk_exprlet(s_let, t, mkSynBindList(mkSynBindList(0, gen1), gen2), mk_expr2(s_comma, t, mk_expr2(s_assign, t, (Expr *)gen1, a1), mk_expr2(s_comma, t, mk_expr2(s_assign, t, (Expr *)gen2, a2), mk_expr2(s_minus, t, (Expr *)gen1, mk_expr2(s_times, t, mk_expr2(s_div, t, (Expr *)gen1, (Expr *)gen2), (Expr *)gen2))))); return cg_expr(x); } #endif #endif #ifdef ADDRESS_REG_STUFF static VRegnum ensure_regtype(VRegnum r, RegSort rsort) { if (vregsort(r) != rsort) { if (rsort == ADDRREG) { VRegnum r1 = fgetregister(rsort); emitreg(J_MOVR, r1, GAP, r); bfreeregister(r); r = r1; } else if (rsort == INTREG); /* do nothing -- AM presumes that this is because the */ /* back end can always use a D as an A but not vice-versa. */ /* Or is it the other way round? */ else syserr(syserr_regtype, (long)rsort); } return r; } #endif #ifdef TARGET_FP_LITS_FROM_MEMORY void emitfloat1(J_OPCODE op, VRegnum r1, VRegnum r2, FloatCon *m) { J_OPCODE op1; VRegnum r99; if (op == J_ADCOND || op == J_ADCONF) { emitfloat(op, r1, r2, m); return; } r99 = fgetregister(ADDRREG); if (op == J_MOVDK) op = J_LDRDK|J_ALIGN8, op1 = J_ADCOND; else if (op == J_MOVFK) op = J_LDRFK|J_ALIGN4, op1 = J_ADCONF; else syserr(syserr_emitfloat1); emitfloat(op1, r99, GAP, m); emit(op, r1, r99, 0); bfreeregister(r99); } #else # define emitfloat1(a,b,c,d) emitfloat(a,b,c,d) #endif static VRegnum cg_loadfpzero(RegSort rsort, Expr *e) { /* void e if !=NULL and return 0 - used for things like f()*0 */ VRegnum r; if (e) (void)cg_exprvoid(e); r = fgetregister(rsort); if (rsort == FLTREG) emitfloat1(J_MOVFK, r, GAP, fc_zero.s); else emitfloat1(J_MOVDK, r, GAP, fc_zero.d); return r; } #ifdef RANGECHECK_SUPPORTED /* It would seem that this routine is a special case of cg_binary_1(). */ static void boundcheck(J_OPCODE op, VRegnum r, Expr *x) { if (x == NULL) /* nothing */; else if (integer_constant(x)) emit(J_RTOK(op), GAP, r, result2); else { VRegnum r1 = cg_expr(x); emitreg(op, GAP, r, r1); bfreeregister(r1); } } #endif /* note that 'valneeded' and 'RegSort rsort' really tell similar stories */ /* Maybe a VOIDREG version of RegSort subsumes both */ static VRegnum cg_expr2(Expr *x, bool valneeded) { AEop op; VRegnum r, r1; int32 mclength = mcrepofexpr(x); int32 mcmode = mclength >> MCR_SORT_SHIFT; RegSort rsort = (mclength &= MCR_SIZE_MASK, (mcmode!=2) ? INTREG : (mclength==4 ? FLTREG : DBLREG)); #ifdef ADDRESS_REG_STUFF if( rsort == INTREG ) { /* Work out further if the result is to be used as an address */ /* If it is the specialise further to an ADDRREG */ TypeExpr *te = princtype(typeofexpr(x)); /* The t_subscript case is to include strings which */ /* have had their implicit '&' removed by simplify(). */ if (h0_(te) == t_content || h0_(te) == t_subscript) rsort = ADDRREG; } #endif /* The next line will not catch cases where loading a one-word struct */ /* occurs improperly if that gets treated as an integer. I have to let */ /* this case slip through since in places I really want to treat such */ /* structs as ints. Anyway all I lose is an internal check that should */ /* never really fail anyway. */ if (mcmode==3 && valneeded) syserr(syserr_struct_val); if (x == 0) { syserr(syserr_missing_expr); return GAP; } op = h0_(x); if (usrdbg(DBG_LINE) && hasfileline_(op) && exprfileline_(x) != 0) emitfl(J_INFOLINE, *exprfileline_(x)); switch (op) { case s_throw: /* simplify.c has inserted a function call as arg1_(x). */ cg_exprvoid(arg1_(x)); /* Should end a basic block (for dead-code loss here). */ return GAP; case s_binder: if (!valneeded && !isvolatile_expr(x)) return GAP; { Binder *b = exb_(x); if ((x = bindconst_(b)) != NULL) { if (LanguageIsCPlusPlus) syserr("bindconst $b got to cg.c", b); return cg_expr2(x, valneeded); } r = ensure_regtype(cg_var(GAP, b, s_content, mcmode, mclength, rsort==ADDRREG), rsort); if (!valneeded) bfreeregister(r), r = GAP; return r; } case s_integer: if (!valneeded) return GAP; #ifdef TARGET_HAS_CONST_R_ZERO if (intval_(x) == 0) return R_ZERO; #endif emit(J_MOVK, r = fgetregister(rsort), GAP, intval_(x)); return r; case s_floatcon: if (!valneeded) return GAP; if (software_floats_enabled && rsort != DBLREG) /* single precision values treated as ints */ { emit(J_MOVK, r = fgetregister(INTREG), GAP, exf_(x)->floatbin.irep[0]); return r; } #ifdef TARGET_HAS_CONST_R_FZERO if (is_fpzero(x)) return R_FZERO; #endif r = fgetregister(rsort); emitfloat1(rsort==DBLREG ? J_MOVDK:J_MOVFK, r, GAP, exf_(x)); return r; case_s_any_string if (!valneeded) return GAP; emitstring(J_STRING, r=fgetregister(ADDRREG), exs_(x)->strseg); return r; #ifdef EXTENSION_VALOF case s_valof: { struct ValofInfo saver; saver = valofinfo; valofinfo.binders = active_binders; valofinfo.lab = nextlabel(); valofinfo.r = reserveregister(rsort); /* Valof blocks will not work (a syserr will occur via cg_addr */ /* or cg_exprreg) for structure results and would need code */ /* here and at s_valof (and cg_addr &c) to make them work. */ cg_cmd(expr1c_(x)); r = getreservedreg(valofinfo.r); /* The next line does nothing much but waste space usually */ /* but is needed in case the valof may (or appear to) have */ /* a route through without a resultis. */ /* See the other uses of J_INIT. */ emitbinder(floatyop(rsort, J_INIT, J_INITF, J_INITD), r, gentempvar(type_(x), r)); start_new_basic_block(valofinfo.lab); valofinfo = saver; return r; } #endif #ifdef RANGECHECK_SUPPORTED case s_rangecheck: /* rangecheck i, l, u: check that l<=i<=u, taking target-dependent action if not. Either l or u may be NULL, meaning don't check. value is i. */ { r = cg_expr2(arg1_(x), YES); boundcheck(J_CHKLR, r, arg2_(x)); boundcheck(J_CHKUR, r, arg3_(x)); return r; } case s_checknot: /* check i, k: check that the value of i is not k, taking target-dependent action if not. */ { r = cg_expr2(arg1_(x), YES); if (integer_constant(arg2_(x))) emit(J_CHKNEK, GAP, r, result2); else if (isintregtype_(rsort)) syserr(syserr_checknot); else { VRegnum r2 = cg_expr2(arg2_(x), YES); emitreg(rsort==FLTREG ? J_CHKNEFR: J_CHKNEDR, GAP, r, r2); bfreeregister(r2); } return r; } #endif case s_let: { BindList *sl = active_binders; int32 d = current_stackdepth; cg_bindlist(exprletbind_(x), 0); r = cg_expr1(arg2_(x), valneeded); emitsetsp(J_SETSPENV, sl); current_stackdepth = d; } return r; case s_fnap: if (mcmode == 3) syserr(syserr_fnret_struct); /* struct-valued functions should now never be seen here: */ /* optimise1 should always have fabricated an assignment */ /* (often to a temporary) which turns the s_fnap (via */ /* structure_assign()) into s_fnapstruct. */ if (resultinflags_fn(x)) { x = mk_expr3(s_cond, te_int, x, mkintconst(te_int, 1, 0), mkintconst(te_int, 0, 0)); return cg_expr1(x, valneeded); } /* drop through */ /* * s_fnapstruct is an artefact introduced when a structure returning * function call is mapped from * v = f(a,b); * onto (void)f(&v,a,b); * so that the converted function application is marked as having been * subjected to this transformation. This is so that cg_fnap can (for * some machines) pass the implicit extra address in some way other than * making it a new first argument. Corresponding special treatment * is needed in function definitions - here that is achieved by inspection * of result_variable (NULL if not used) with funny treatment only * activated if TARGET_STRUCT_RESULT_REGISTER is defined. */ case s_fnapstructvoid: case s_fnapstruct: /* Some functions have special rules re compilation. open_compilable() */ /* returns -2 if it is handed anything other than one of these. */ /* NB open_compilable is now handed a pointer to the fnap expression, */ /* for which it may generate a replacement to be given to cg_fnap */ r = open_compilable(&x, rsort, valneeded); return (r != NOT_OPEN_COMPILABLE) ? r : cg_fnap(x, V_resultreg(rsort), valneeded); case s_cond: { LabelNumber *l3 = nextlabel(); /* Previous phases of the compiler must have arranged that the two arms */ /* of the condition each have the same mode. In particular they must */ /* either be both integer or both floating point values. This has to */ /* include the possibility of them being voided. Structure values are */ /* only legal here if the conditional expression as a whole is voided. */ r = cg_cond(x, valneeded, reserveregister(rsort), l3, 0); start_new_basic_block(l3); return getreservedreg(r); } case s_cast: return cg_cast1(arg1_(x), mclength, mcmode); case s_addrof: return cg_addr(arg1_(x), valneeded); case s_notequal: case s_equalequal: /* (a==b) --> ((a==b) ? 1 : 0) */ case s_greater: /* and similarly for these others. */ case s_greaterequal: case s_less: case s_lessequal: if (!valneeded) return cg_diadvoid(x); /* boolnot is unary, but is treated the same */ case s_boolnot: if (!valneeded) return cg_exprvoid(arg1_(x)); case s_andand: case s_oror: x = mk_expr3(s_cond, te_int, x, lit_one, lit_zero); return cg_expr(x); case s_comma: cg_exprvoid(arg1_(x)); return cg_expr1(arg2_(x), valneeded); case s_init: #ifdef NARROW_FORMALS_REUSE_ARG_BINDER if ( (h0_(arg2_(x)) == s_binder && arg2_(x) == arg1_(x)) || (h0_(arg2_(x)) == s_cast && h0_(arg1_(x)) == s_binder && arg1_(arg2_(x)) == arg1_(x))) { TypeExpr *wt = widen_formaltype(bindtype_(exb_(arg1_(x)))); int32 mcr = mcrepoftype(wt); int32 mcr1 = mcrepofexpr(arg2_(x)); return cg_storein(cg_cast1_(cg_var(GAP, exb_(arg1_(x)), s_content, mcr >> MCR_SORT_SHIFT, mcr & MCR_SIZE_MASK, NO), mcr1 & MCR_SIZE_MASK, mcr1 >> MCR_SORT_SHIFT, mcr), NULL, arg1_(x), s_assign); } #endif op = s_assign; case s_assign: if (mcmode == 3) { if (valneeded) syserr(syserr_structassign_val); else { structure_assign(arg1_(x), arg2_(x), mclength); return GAP; } } goto ass_disp; case s_displace: { Expr *v = arg1_(x), *x3 = arg2_(x); if (valneeded && isintregtype_(rsort) && h0_(x3) == s_plus && is_same(arg1_(x3),v) && integer_constant(arg2_(x3))) { /* a little optimisation... */ int32 n = result2; VRegnum rx = cg_expr(v); VRegnum r1 = fgetregister(ADDRREG); emit(J_ADDK, r1, rx, n); cg_storein(r1, NULL, v, s_assign); bfreeregister(r1); return rx; } } ass_disp: if (nastiness(arg1_(x)) == ISHARD && nastiness(arg2_(x)) != ISHARD) return cg_storein(GAP, arg2_(x), arg1_(x), valneeded ? op : s_assign); else return cg_storein(cg_expr(arg2_(x)), NULL, arg1_(x), valneeded ? op : s_assign); case s_content: case s_content4: { bool volatileorunaligned = isvolatile_expr(x) | (isunaligned_expr(x) << 1); if (!valneeded && !(volatileorunaligned & IsVolatile)) return cg_exprvoid(arg1_(x)); if (op == s_content4) volatileorunaligned |= BaseIsWordAligned; x = arg1_(x); verify_integer(x); if (memory_access_checks) { Expr *fname = mclength==1 ? sim.readcheck1 : mclength==2 ? sim.readcheck2 : sim.readcheck4; x = mk_expr2(s_fnap, typeofexpr(x), fname, mkArgList1(x)); } r = ensure_regtype(cg_stind(GAP, NULL, x, s_content, NULL, mcmode, mclength, rsort==ADDRREG, volatileorunaligned), rsort); if (!valneeded) bfreeregister(r), r = GAP; return r; } case s_monplus: /* Monadic plus does not have to generate any code */ return cg_expr1(arg1_(x), valneeded); case s_neg: if (!valneeded) return cg_exprvoid(arg1_(x)); if (isintregtype_(rsort)) return cg_unary_i(J_NEGR, rsort, arg1_(x)); r1 = cg_expr(arg1_(x)); r = fgetregister(rsort); emitreg((rsort==FLTREG ? J_NEGFR : J_NEGDR), r, GAP, r1); bfreeregister(r1); return r; case s_bitnot: if (!valneeded) return cg_exprvoid(arg1_(x)); verify_integer(x); return cg_unary_i(J_NOTR, rsort, arg1_(x)); case s_times: if (!valneeded) return cg_diadvoid(x); else if (!isintregtype_(rsort)) { if (is_fpzero(arg1_(x))) return cg_loadfpzero(rsort, arg2_(x)); if (is_fpzero(arg2_(x))) return cg_loadfpzero(rsort, arg1_(x)); return(cg_binary(rsort==FLTREG ? J_MULFR : J_MULDR, arg1_(x), arg2_(x), 1, rsort)); } { int32 p; if ((p = ispoweroftwo(arg2_(x))) != 0) /* change to SIGNED shift if mcmode=0 and overflow checked */ return cg_binary(J_SHLR+J_UNSIGNED, arg1_(x), mkintconst(te_int,p,0), 0, rsort); if ((p = ispoweroftwo(arg1_(x))) != 0) /* change to SIGNED shift if mcmode=0 and overflow checked */ return cg_binary(J_SHLR+J_UNSIGNED, arg2_(x), mkintconst(te_int,p,0), 0, rsort); return cg_multiply(type_(x), arg1_(x), arg2_(x)); } case s_plus: if (!valneeded) return cg_diadvoid(x); /* Code that used to be here to turn a+-b into a-b etc now */ /* resides in simplify.c (where it also gets argument of */ /* s_content */ return(cg_binary(isintregtype_(rsort) ? J_ADDR : rsort==FLTREG ? J_ADDFR : J_ADDDR, arg1_(x), arg2_(x), 1, rsort)); case s_minus: if (!valneeded) return cg_diadvoid(x); return(cg_binary(isintregtype_(rsort) ? J_SUBR : rsort==FLTREG ? J_SUBFR : J_SUBDR, arg1_(x), arg2_(x), 0, rsort)); case s_div: /* Even if voiding this I calculate it in case there is a division error */ /* that ought to be reported. */ /* But I arrange that the numerator is voided in this odd case, since */ /* that can save me some effort. */ if (!valneeded) { cg_exprvoid(arg1_(x)); x = mk_expr2(s_div, type_(x), lit_one, arg2_(x)); } if (!isintregtype_(rsort)) /* @@@ AM: tests like the following can probably be hit with a feature */ /* bit within the JOPCODE property table when AM re-arranges them. */ #ifdef TARGET_LACKS_FP_DIVIDE /* N.B. in this version I make (p/q) turn into divide(q,p) since that */ /* seems to make register usage behave better (see cg_binary_or_fn) */ r = cg_expr(mk_expr2(s_fnap, type_(x), rsort==FLTREG ? sim.fdiv : sim.ddiv, mkArgList2(arg2_(x), arg1_(x)))); #else r = cg_binary(rsort==FLTREG ? J_DIVFR : J_DIVDR, arg1_(x), arg2_(x), 0, rsort); #endif /* can't the unsignedness property get in rsort? */ else if (mcmode==1) { int32 p; r = ((p = ispoweroftwo(arg2_(x))) != 0) ? cg_binary(J_SHRR+J_UNSIGNED, arg1_(x), mkintconst(te_int,p,0), 0, rsort) : cg_divrem(J_DIVR+J_UNSIGNED, type_(x), sim.udivfn, arg1_(x), arg2_(x)); } else { #if !defined(TARGET_HAS_DIVIDE) && !defined(TARGET_HAS_NONFORTRAN_DIVIDE) int32 p; if ((p = ispoweroftwo(arg2_(x))) != 0) { /* e.g. (signed) z/8 == (z>=0 ? z:z+7) >> 3 (even MIN_INT) */ /* Do not forge such an expression since (a) we cannot */ /* re-use VRegs as we do below (this saves a resource AND */ /* forces and MOVR first which can often be combined with */ /* the zero test) and (b) profile counting is unwanted here.*/ /* This code may be better as a procedure. */ r = cg_expr(arg1_(x)); #ifdef TARGET_HAS_SCALED_OPS /* even more cunning trick for n/2 ... */ if (p == 1) emitshift(J_ADDR, r, r, r, SHIFT_RIGHT | 31); /* unsigned */ else #endif { LabelNumber *l = nextlabel(); blkflags_(bottom_block) |= BLKREXPORTED; emit(J_CMPK+Q_GE, GAP, r, 0); emitbranch(J_B+Q_GE, l); emit(J_ADDK, r, r, lowerbits(p)); start_new_basic_block(l); } if (p != 31) emit(J_SHRK+J_SIGNED, r, r, p); else emit(J_SHRK+J_UNSIGNED, r, r, p); } else #endif r = cg_divrem(J_DIVR+J_SIGNED, type_(x), sim.divfn, arg1_(x), arg2_(x)); } if (!valneeded) bfreeregister(r), r = GAP; return r; case s_rem: verify_integer(x); if (iszero(arg1_(x))) return cg_loadzero(arg2_(x)); else if (isone(arg2_(x))) return cg_loadzero(arg1_(x)); /* can't the unsignedness property get in rsort? */ else if (mcmode==1) { int32 p; if ((p = ispoweroftwo(arg2_(x))) != 0) return cg_binary(J_ANDR, arg1_(x), mkintconst(te_int,lowerbits(p),0), 0, rsort); #ifdef TARGET_LACKS_REMAINDER return simulate_remainder(type_(x), arg1_(x), arg2_(x)); #else return(cg_divrem(J_REMR+J_UNSIGNED, type_(x), sim.uremfn, arg1_(x), arg2_(x))); #endif } else { #if !defined(TARGET_HAS_DIVIDE) && !defined(TARGET_HAS_NONFORTRAN_DIVIDE) int32 p; if ((p = ispoweroftwo(arg2_(x))) != 0) { /* see above code and comments for s_div too */ /* e.g. (signed) z%8 == (z>=0 ? z&7 : -((-z)&7)) */ VRegnum r = cg_expr(arg1_(x)); LabelNumber *l = nextlabel(), *m = nextlabel(); blkflags_(bottom_block) |= BLKREXPORTED; emit(J_CMPK+Q_GE, GAP, r, 0); emitbranch(J_B+Q_GE, l); if (p != 1) /* marginally better code for % 2 */ emitreg(J_NEGR, r, GAP, r); emit(J_ANDK, r, r, lowerbits(p)); emitreg(J_NEGR, r, GAP, r); emitbranch(J_B+Q_AL, m); start_new_basic_block(l); emit(J_ANDK, r, r, lowerbits(p)); start_new_basic_block(m); return r; } #endif if (isminusone(arg2_(x))) return cg_loadzero(arg1_(x)); /* required by s_div defn */ #ifdef TARGET_LACKS_REMAINDER return simulate_remainder(type_(x), arg1_(x), arg2_(x)); #else return(cg_divrem(J_REMR+J_SIGNED, type_(x), sim.remfn, arg1_(x), arg2_(x))); #endif } case s_leftshift: if (!valneeded) return cg_diadvoid(x); verify_integer(x); if (iszero(arg2_(x))) return(cg_expr(arg1_(x))); else if (iszero(arg1_(x))) return cg_loadzero(arg2_(x)); else return(cg_binary(mcmode==1 ? J_SHLR+J_UNSIGNED : J_SHLR+J_SIGNED, arg1_(x), arg2_(x), 0, rsort)); case s_rightshift: if (!valneeded) return cg_diadvoid(x); verify_integer(x); if (iszero(arg2_(x))) return(cg_expr(arg1_(x))); else if (iszero(arg1_(x))) return cg_loadzero(arg2_(x)); #ifdef TARGET_LACKS_RIGHTSHIFT /* vax, clipper */ else if (!integer_constant(arg2_(x))) { Expr *a2 = arg2_(x); /* The difference between signed and unsigned left shifts shows here */ return cg_binary(mcmode==1 ? J_SHLR+J_UNSIGNED : J_SHLR+J_SIGNED, arg1_(x), mk_expr1(s_neg, typeofexpr(a2), a2), 0, rsort); } #endif /* TARGET_LACKS_RIGHTSHIFT */ /* Note that for right shifts I need to generate different code for */ /* signed and unsigned operations. */ else return cg_binary(mcmode==1 ? J_SHRR+J_UNSIGNED : J_SHRR+J_SIGNED, arg1_(x), arg2_(x), 0, rsort); case s_and: if (!valneeded) return cg_diadvoid(x); verify_integer(x); return cg_binary(J_ANDR, arg1_(x), arg2_(x), 1, rsort); case s_or: if (!valneeded) return cg_diadvoid(x); verify_integer(x); return(cg_binary(J_ORRR, arg1_(x), arg2_(x), 1, rsort)); case s_xor: if (!valneeded) return cg_diadvoid(x); verify_integer(x); return(cg_binary(J_EORR, arg1_(x), arg2_(x), 1, rsort)); default: syserr(syserr_cg_expr, (long)op, op); return GAP; } } /* things for swapping (virtual-) register contexts ... */ static SynBindList *bindlist_for_temps(RegList *regstosave, RegList *fpregstosave) { RegList *p1; SynBindList *things_to_bind = NULL; /* CPLUSPLUS: note that we cannot handle anything in things_to_bind */ /* which has a destructor. */ for (p1=regstosave; p1!=NULL; p1 = p1->rlcdr) { Binder *bb = gentempvar(te_int, GAP); things_to_bind = mkSynBindList(things_to_bind, bb); } for (p1=fpregstosave; p1!=NULL; p1 = p1->rlcdr) { RegSort tt = vregsort(p1->rlcar); Binder *bb = gentempvar(tt==FLTREG ? te_float : te_double, GAP); things_to_bind = mkSynBindList(things_to_bind, bb); } return (SynBindList *)dreverse((List *)things_to_bind); } static void stash_temps(RegList *regstosave, RegList *fpregstosave, SynBindList *p2, J_OPCODE j_i, J_OPCODE j_f, J_OPCODE j_d) { RegList *p1; for (p1=regstosave; p1!=NULL; p1 = p1->rlcdr) { emitbinder(j_i, p1->rlcar, p2->bindlistcar); p2 = p2->bindlistcdr; } for (p1=fpregstosave; p1!=NULL; p1 = p1->rlcdr) { VRegnum r = p1->rlcar; emitbinder((vregsort(r)==FLTREG ? j_f : j_d), r, p2->bindlistcar); p2 = p2->bindlistcdr; } } static RegList *rl_discard(RegList *x) { return (RegList *)discard2((List *)x); } #define toplevel_alignment(b) \ ((bindstg_(b) & bitofstg_(s_auto)) ? alignof_toplevel_auto :\ alignof_toplevel_static) #define expr_alignment(e) \ ((h0_(e) == s_binder) ? toplevel_alignment((Binder *)e) : 1) #define AddUsedReg(r) (usedregs = mkRegList(usedregs, (r)), ++nusedregs) /* The effect of calling flush_arg_usedregs is to set usedregs to 0 */ /* and either dispose of its pointed to list or to pass it on to */ /* someone else who will. @@@ REVIEW? */ static void flush_arg_usedregs(int32 argaddr) { /* 'argaddr' is the stack offset (counting arg1 as 0) of where */ /* the first register (if any) in usedregs is to go. */ argaddr += alignof_toplevel_auto * length((List *)usedregs); for (usedregs = (RegList *)dreverse((List *)usedregs); usedregs != NULL; usedregs = rl_discard(usedregs)) { VRegnum r = usedregs->rlcar; if (!((unsigned32)((r)-R_A1) < (unsigned32)NARGREGS)) syserr(syserr_bad_reg, (long)r); /* @@@ perhaps J_PUSHR should mean "push alignof_toplevel size binder. */ emit(J_PUSHR, r, GAP, argaddr -= alignof_toplevel_auto); active_binders = mkBindList(active_binders, integer_binder); current_stackdepth += alignof_toplevel_auto; } if (usedfpregs!=NULL) syserr(syserr_bad_fp_reg); nusedregs = nusedfpregs = 0; } static void flush_fparg(VRegnum r, int32 rep, int32 argaddr) { if (rep == MCR_SORT_FLOATING + 4) { if (alignof_toplevel_auto==8) syserr("ALPHA flt arg confusion"); /* currently float args are widened to doubles. */ emit(J_PUSHF, r, GAP, argaddr); active_binders = mkBindList(active_binders, integer_binder); } else { emit(J_PUSHD, r, GAP, argaddr); active_binders = mkBindList(active_binders, integer_binder); if (alignof_toplevel_auto != 8) active_binders = mkBindList(active_binders, integer_binder); } current_stackdepth = padtomcrep(current_stackdepth, rep) + padsize(rep & MCR_SIZE_MASK, alignof_toplevel_auto); } /* ECN: Handle case where R_IP is defined to be an arg register */ #if R_IP < NARGREGS #if R_IP != NARGREGS-1 #error "Can't handle this definition of R_IP" #else #define NARGREGS1 3 #endif #else #define NARGREGS1 (NARGREGS==0 ? 1 : NARGREGS) #endif #ifdef TARGET_HAS_RISING_STACK # define FlushPrevArgRegs(arg, n) flush_arg_usedregs((arg)[(n)-1].addr); #else # define FlushPrevArgRegs(arg, n) flush_arg_usedregs((arg)[(n)+1].addr); #endif /* The following typedef is local to cg_fnargs() and cg_fnap() */ typedef struct ArgInfo { Expr *expr; int info; /* nastiness(expr) */ uint8 regoff, /* offset of first argument register from R_A1 */ nreg; /* number of integer argument registers */ int32 rep, /* mcrepof(expr) */ addr; /* stack offset from base of argument list */ } ArgInfo; static void cg_fnargs_stack(ArgInfo arg[], int32 regargs, int32 n, bool firstsplit) /* Evaluate arguments described by arg[regargs] up to arg[n-1] and place */ /* them on the stack. If TARGET_HAS_RISING_STACK, the order is ascending */ /* and a gap is left for those passed in registers. Otherwise, the order */ /* is descending. */ /* However, ensure the stack is always correctly aligned if necessary. */ /* The arguments handled by this function are not necessarily intended */ /* to be passed on the stack - they (or some part of them) may be popped */ /* into integer registers before the call. */ /* This behaviour is BROKEN if STACK_MOVES_ONCE. */ { int32 narg; int32 nargregs1 = NARGREGS1; int32 stackargs = firstsplit ? regargs-1 : regargs; #ifdef TARGET_IS_ARM_OR_THUMB /* this really means "TARGET_IMPLEMENTS_UnalignedLoadMayUse" */ bool unaligned_arg = NO; for (narg = stackargs; narg != n; narg++) if (ContainsUnalignedSubExpr(arg[narg].expr)) { unaligned_arg = YES; break; } if (unaligned_arg) for (; ; nargregs1--) if (!UnalignedLoadMayUse(R_A1+nargregs1-1)) break; #endif #ifdef TARGET_HAS_RISING_STACK for (narg = stackargs; narg != n; narg++ ) { int32 rep = arg[narg].rep; #else for (narg = n; narg != stackargs; ) { int32 rep = arg[--narg].rep; #if (alignof_double > alignof_toplevel_auto) /* pad beyond last int arg --- hmm think */ if (arg[narg].addr + padsize(rep & MCR_SIZE_MASK, alignof_toplevel_auto) != arg[narg+1].addr) { BindList *nb = active_binders; /* @@@ note that the next line of code assumes that */ /* (alignof_double/alignof_int) == 1 or 2. */ nb = mkBindList(nb, integer_binder); current_stackdepth += alignof_toplevel_auto; emitsetsp(J_SETSPENV, nb); } #endif #endif /* TARGET_HAS_RISING_STACK */ /* Major fun is called for here in case an actual argument is something */ /* other than a 32-bit integer-like quantity. */ switch (rep & MCR_SORT_MASK) { default: syserr(syserr_cg_fnarg, (long)rep); break; case MCR_SORT_SIGNED: case MCR_SORT_UNSIGNED: /* Maybe the next use of 'nusedregs' is nasty. */ if (nusedregs == nargregs1 || arg[narg].info == ISHARD) /* The following line avoids silly (n**2) code on fn call. */ FlushPrevArgRegs(arg, narg); { Expr *a = arg[narg].expr; #ifdef TARGET_HAS_RISING_STACK VRegnum argr = R_A1 + nusedregs; #else VRegnum argr = R_A1 + nargregs1-1 - nusedregs; #endif (void)cg_exprreg(a, argr); AddUsedReg(argr); } break; case MCR_SORT_FLOATING: FlushPrevArgRegs(arg, narg); if (!firstsplit || narg != stackargs) { VRegnum r = cg_expr(arg[narg].expr); int32 argaddr = arg[narg].addr; flush_fparg(r, rep, argaddr); bfreeregister(r); break; } /* Otherwise (fp argument split between stack and registers) */ /* fall through to handle as though struct. The argument is */ /* guaranteed by cg_fnargs() to be store-like. */ case MCR_SORT_STRUCT: /* There used to be a check here that the size of the struct */ /* is a multiple of align_of_struct. It's been retired as */ /* inadequate (alignof_struct may be less than sizeof_int); */ /* moreover, we need to handle packed structs */ /* The code guarded by !defined(TARGET_HAS_BLOCKMOVE) below */ /* must take care not to try to handle cases which aren't */ /* adequately aligned. */ if (nusedregs == nargregs1 || arg[narg].info == ISHARD || MEMCPYREG == DBLREG) FlushPrevArgRegs(arg, narg); { int32 start = 0, structsize = rep & MCR_SIZE_MASK; if (firstsplit && narg == stackargs) start = arg[narg].nreg * alignof_toplevel_auto; /* * We now pretend that the ARM has a BLOCKMOVE instruction because that * makes it possible for gen.c to expand blockmoves into sequences of * loads or stores, or maybe procedure calls, exploiting knowledge of * how many registers are free. */ /* ECN: Thumb does not support blockmove for the following as is does not * have a proper set of LDMIA/STMIA instructions for use with SP. * Also, its peepholer does not yet support J_PUSHC. */ #if !defined(TARGET_HAS_BLOCKMOVE) || defined(TARGET_IS_THUMB) /* The following code needs to know struct alignment as well as size: */ if (alignoftype(typeofexpr(arg[narg].expr)) >= MEMCPYQUANTUM && structsize < 5*MEMCPYQUANTUM) /* The case of a (small) structure argument (now guaranteed by simplify */ /* not to involve a function call) can be compiled using a sequence of */ /* PUSH (or PUSHD) operations. */ /* We expect that to be cheaper than the synthetic assignment used in */ /* the more general case below. */ /* This special case code is inhibited if size is not a multiple of 4. */ { Expr *e = take_address(arg[narg].expr); Binder *b = is_local_adcon(e); VRegnum r = GAP; if (b == NULL) { r = cg_expr(e); /* Hmm: I have to do a bfreeregister on r before any flush_arg_usedregs() */ /* This is not dangerous as flow analysis will regard r as alive up to */ /* the last member. */ bfreeregister(r); } #ifdef TARGET_HAS_RISING_STACK structsize = start; while (structsize != (rep & MCR_SIZE_MASK)) #else while (structsize != start) #endif { VRegnum argr; if (nusedregs == nargregs1) flush_arg_usedregs(arg[narg].addr + structsize); #ifdef TARGET_HAS_RISING_STACK argr = R_A1 + nusedregs; #else argr = MEMCPYREG==DBLREG ? R_FA1 : R_A1 + nargregs1-1 - nusedregs; structsize -= MEMCPYQUANTUM; #endif if (b != NULL) emitvk(J_memcpy(J_LDRVK|J_ALIGN4), argr, structsize, b); else emit(J_memcpy(J_LDRK|J_ALIGN4), argr, r, structsize); #ifdef TARGET_HAS_RISING_STACK structsize += MEMCPYQUANTUM; #endif if (MEMCPYREG==DBLREG) flush_fparg(argr, MCR_SORT_FLOATING+sizeof_double, arg[narg].addr+structsize); else AddUsedReg(argr); } /* The bfreeregister(r) above notionally belongs here. */ } else #endif /* The general case of an argument that can involve a function call */ /* returning a structure is dealt with here... (Oct 92: fn can't happen) */ { FlushPrevArgRegs(arg, narg); { TypeExpr *t; #ifdef NEVER /* The following preferable code is beaten by cg_fnargs. */ /* (in the case when a struct spans the reg/memory boundary.). */ Binder *gen = gentempbinder(t); bindstg_(gen) |= b_spilt; /* Forge an address-taken struct variable to fit on the stack in the */ /* usual position for the actual parameter. */ cg_bindlist(mkSynBindList(0, gen), 0); #else /* ALWAYS */ /* We add a number of integer binders to the stack, whose total size is */ /* the same as that of the argument object. But we assign to a */ /* temporary binder of the correct type (not added to the stack). The */ /* address of this binder is made correct by forging its bindbl_() */ /* field to be the same as if it had been added to the stack rather */ /* than the integers. b_unbound in bindstg_() is used to mark precisely */ /* this disgusting situation, so that later dataflow analysis has some */ /* chance. */ Binder *gen; BindList *nb = active_binders; int32 i, size = padsize(structsize-start, alignof_toplevel_auto); current_stackdepth += size; for (i = size; i != 0; i -= alignof_toplevel_auto) nb = mkBindList(nb, integer_binder); t = (start == 0) ? typeofexpr(arg[narg].expr) : mk_typeexpr1(t_subscript, te_char, mkintconst(te_int, size, 0)); gen = gentempvar(t, GAP); if (target_stack_moves_once) { bindstg_(gen) |= b_spilt|b_unbound; /* BEWARE: the next line is in flux (Nov89) and is only OK because */ /* 'gen' never gets to be part of 'active_binders'. */ bindaddr_(gen) = (arg[narg].addr + start) | BINDADDR_NEWARG; } else { bindstg_(gen) |= b_spilt|b_bindaddrlist|b_unbound; bindbl_(gen) = nb; } emitsetsp(J_SETSPENV, nb); #endif if (start == 0) structure_assign((Expr *)gen, arg[narg].expr, structsize); else { Expr *e = mk_expr2(s_plus, ptrtotype_(te_int), take_address(arg[narg].expr), mkintconst(te_int, start, 0)); e = mk_expr2(s_fnap, te_void, sim.memcpyfn, mkArgList3(take_address((Expr *)gen), e, mkintconst(te_int,size,0))); cg_exprvoid(e); } if (usedregs != 0) syserr(syserr_fnarg_struct); } } } break; } /* end of switch */ #if defined(TARGET_HAS_RISING_STACK) && (alignof_double > alignof_toplevel_auto) if (arg[narg].addr + padsize(rep & MCR_SIZE_MASK, alignof_toplevel_auto) != arg[narg+1].addr) { BindList *nb = active_binders; /* @@@ note that the next line of code assumes that */ /* (alignof_double/alignof_int) == 1 or 2. */ nb = mkBindList(nb, integer_binder); current_stackdepth += alignof_toplevel_auto; emitsetsp(J_SETSPENV, nb); } #endif } /* end of for */ flush_arg_usedregs(arg[regargs].addr); } /* ECN: If R_IP < NARGREGS below we must assign the R_IP register to a virtual * register, return this, and perform the assignment to R_IP after we have * calculated the function address (in the case of a fn pointer) as calculating * this address may in itself use R_IP */ /* HCM: On reflection, it appears always to be at least no worse to */ /* evaluate all arguments to virtual registers, then to move them to */ /* the correct argument registers (rather than having a number of */ /* (evaluate to virtual register; move to argument register) pairs. */ #define ArgDeferred(r, fn) ((r) < R_FA1) #if 0 #ifdef TARGET_IS_ARM_OR_THUMB /* this really means "TARGET_IMPLEMENTS_UnalignedLoadMayUse" */ # define ArgDeferred(r, fn) \ ((isunaligned_expr(fn) && UnalignedLoadMayUse(r)) ||\ (R_A1 <= R_IP && R_IP < R_A1+NARGREGS && r == R_IP)) #else # define ArgDeferred(r, fn) 0 #endif #endif /* Structure representing the value of a register argument which has */ /* not been fully evaluated by cg_fnargs_regs(): either it has been */ /* evaluated into a virtual register, not into the physical argument */ /* register (r != GAP), or it has not been evaluated at all (e != NULL)*/ /* : constants only!. */ /* Only one of r and e may be set, of course. */ typedef struct { VRegnum r; Expr *e; } DeferredArg; typedef struct { int32 resultregs; VRegnum specialarg; Expr *fn; uint32 resultrep; uint16 auxflags; /* out ... (of cg_fnargs) */ VRegnum fnreg; SynBindList *fnsave; DeferredArg deferred[NINTREGS-R_A1]; } FnargStruct; static void cg_fnargs_regs(ArgInfo arg[], int32 intregargs, int32 fltregargs, FnargStruct *argstruct, int splitarg) /* Finally do the first NARGREGS (or less) 'int' args to registers: */ /* Do the hardest first to avoid moving easier things around. */ /* Also, save and restore explicitly all function results except the */ /* last to avoid recursive cg_fnap making a quadratic mess of */ /* f() { g(a(),b(),c(),...); } */ /* Oct 92: this code has been extended so that 'intregargs' can also */ /* include struct/fp regs, which are loaded directly (instead of */ /* going through cg_fnargs_stack() and J_POP). Hence (addressable) */ /* float values can be loaded to int regs directly. ***SOON*** */ /* The code behaves as before unless cg_fnargs() takes the opportunity */ /* to increase 'intregargs' from before. */ { BindList *save_binders = active_binders; int32 d = current_stackdepth; int32 regargs = intregargs+fltregargs; /* the +1 in the next lines is for the possible hidden argument. */ VRegnum argregs[NANYARGREGS+1]; /* arg virt regs */ SynBindList *argsaves[NANYARGREGS+1]; /* for previous fn call results */ int hardness; int32 firsthard = -1; { int32 i; for (i = NARGREGS; --i >= 0;) { argstruct->deferred[i].r = GAP; argstruct->deferred[i].e = NULL; } for (i = regargs; --i >= 0; ) { if (arg[i].info == ISHARD) firsthard = i; argsaves[i] = (SynBindList *) DUFF_ADDR, argregs[i] = GAP; } } for (hardness = ISHARD; hardness >= ISCONST; hardness--) { int32 i; #ifdef TARGET_FP_ARGS_IN_FP_REGS #define callregsort(n, f) \ ((n)<(f) ? ((arg[n].rep & MCR_SIZE_MASK)==sizeof_float ? FLTREG : DBLREG)\ : INTREG) #define callreg(n, f) ((n)<(f) ? R_FA1+(n) : \ argstruct->specialarg != GAP && (n)==(f) ? argstruct->specialarg : \ R_A1+arg[n].regoff) #else #define callregsort(n, f) INTREG #define callreg(n, f) (R_A1+arg[n].regoff) #endif for (i = regargs; --i >= 0; ) if (arg[i].info == hardness) { Expr *a = arg[i].expr; int32 repsort = arg[i].rep & MCR_SORT_MASK; if (hardness == ISHARD && i != firsthard && argstruct->fnreg != GAP && argstruct->fnsave == NULL) { SynBindList *b = bindlist_for_temps(usedregs, usedfpregs); /* b should have at most 1 elt */ cg_bindlist(b, 1); if (b->bindlistcdr != NULL) syserr(syserr_cg_fnarg1); emitbinder(J_STRV|J_ALIGN4V, argstruct->fnreg, b->bindlistcar); usedregs = 0; nusedregs = 0; usedfpregs = 0; nusedfpregs = 0; argstruct->fnsave = b; } if (hardness == ISCONST) { VRegnum argr = callreg(i, fltregargs); if (ArgDeferred(argr, argstruct->fn)) argstruct->deferred[argr - R_A1].e = a; else (void)cg_exprreg(a, argr); } else if (i == splitarg || (repsort == MCR_SORT_STRUCT && (alignoftype(typeofexpr(a)) >= MEMCPYQUANTUM || expr_alignment(a) >= MEMCPYQUANTUM))) { if (h0_(a) != s_fnap && h0_(a) != s_let) argregs[i] = cg_expr(take_address(a)); else { TypeExpr *t = typeofexpr(a); Binder *gen = gentempbinder(t); Expr *fnap = NULL; if (h0_(a) == s_fnap) fnap = a; else if (h0_(arg2_(a)) == s_fnap) fnap = arg2_(a); if (fnap == NULL || !returnsstructinregs(arg1_(fnap))) bindstg_(gen) |= b_spilt; /* Forge an address-taken struct variable to fit on the stack in the */ /* usual position for the actual parameter. */ cg_bindlist(mkSynBindList(0, gen), 0); cg_exprvoid(mk_expr2(s_assign, t, (Expr*)gen, a)); arg[i].expr = (Expr *)gen; arg[i].info = ISBIND; } } else /* (we'll get a syserr for structs) */ argregs[i] = cg_expr(a); if (hardness == ISHARD) { SynBindList *b = i == firsthard ? 0 : /* first is easy */ bindlist_for_temps(usedregs, usedfpregs); /* b should have at most 1 elt */ cg_bindlist(b, 1); if (b != 0) { J_OPCODE j_saveop = (repsort == MCR_SORT_STRUCT) ? J_STRV|J_ALIGN4V : (callregsort(i, fltregargs) == FLTREG) ? J_STRFV|J_ALIGN4V : (callregsort(i, fltregargs) == DBLREG || repsort == MCR_SORT_FLOATING) ? J_STRDV|J_ALIGN8 : J_STRV|J_ALIGN4V; if (b->bindlistcdr != NULL) syserr(syserr_cg_fnarg1); emitbinder(j_saveop, argregs[i], b->bindlistcar); usedregs = 0; nusedregs = 0; usedfpregs = 0; nusedfpregs = 0; } argsaves[i] = b; } } } { int32 i; for (i = 0; i < regargs; i++) { SynBindList *b; bool done = arg[i].info == ISCONST; /* we did these above. */ int32 repsort = arg[i].rep & MCR_SORT_MASK; VRegnum realargr = callreg(i, fltregargs); VRegnum argr = realargr; if (!done && ArgDeferred(argr, argstruct->fn)) { VRegnum ar = argregs[i]; if (isany_realreg_(ar) || ar == GAP || vregsort(ar) != INTREG) ar = vregister(INTREG); argr = argstruct->deferred[argr - R_A1].r = ar; } if (repsort == MCR_SORT_STRUCT) { int32 j, limit = arg[i].nreg; for (j = 0; j<limit; j++) if (ArgDeferred(realargr+j, argstruct->fn)) argstruct->deferred[realargr + j - R_A1].r = vregister(INTREG); } /* @@@ This can be usedfpregs? Yes, fix!!! */ /* Unclear the nusedregs/fregs do anything at all here. */ AddUsedReg(argr); if (arg[i].info == ISHARD && (b = argsaves[i]) != 0) { if (b->bindlistcdr != NULL) syserr(syserr_cg_fnarg1); /* Logically, the following code just reloads argregs[i], but we */ /* try to reload from spill directly to arg regs: OK for int->intreg */ /* dble->dblereg, but dble/struct->intreg needs careful code... */ /* The order of tests below follows that in the (!done) case. */ if (repsort == MCR_SORT_STRUCT) emitbinder(J_LDRV|J_ALIGN4V, argregs[i], b->bindlistcar); else if (callregsort(i, fltregargs) == FLTREG) emitbinder(J_LDRFV|J_ALIGN4V, argr, b->bindlistcar), done = 1; else if (callregsort(i, fltregargs) == DBLREG) emitbinder(J_LDRDV|J_ALIGN8, argr, b->bindlistcar), done = 1; else if (repsort == MCR_SORT_FLOATING) emitbinder(J_LDRDV|J_ALIGN8, argregs[i], b->bindlistcar); else { emitbinder(J_LDRV|J_ALIGN4V, argr, b->bindlistcar); done = 1; } (void)freeSynBindList(b); } if (!done && argregs[i] != GAP && (argregs[i] != argr || repsort > MCR_SORT_UNSIGNED)) { /* argregs[i] will be GAP when the actual argument is */ /* a call to an inlined function returning a structure */ /* result in registers */ VRegnum r = argregs[i]; if (repsort == MCR_SORT_STRUCT || i == splitarg) { int32 j, limit = arg[i].nreg; /* The usedregs/nusedregs code needs a better interface! */ int32 load = isunaligned_type(typeofexpr(arg[i].expr)) ? J_LDRK|J_ALIGN1 : J_LDRK|J_ALIGN4; usedregs = usedregs->rlcdr; nusedregs--; for (j = 0; j<limit; j++) { VRegnum thisr = realargr + j; if (ArgDeferred(thisr, argstruct->fn)) thisr = argstruct->deferred[thisr - R_A1].r; AddUsedReg(thisr); emit(load, thisr, r, 4*j); } } else if (callregsort(i, fltregargs) == FLTREG) emitreg(J_MOVFR, argr, GAP, r); else if (callregsort(i, fltregargs) == DBLREG) emitreg(J_MOVDR, argr, GAP, r); #ifdef TARGET_SHARES_INTEGER_AND_FP_REGISTERS else if (repsort == MCR_SORT_FLOATING) /* [am] */ emitreg(vregsort(r) == DBLREG ? J_MOVDR : J_MOVFR, argr, GAP, r); #else else if (arg[i].rep == MCR_SORT_FLOATING + sizeof_float) emitreg(J_MOVFIR, argr, GAP, r); else if (repsort == MCR_SORT_FLOATING) /* [am] */ { VRegnum argr2 = realargr+1; /* We can't defer the loads of the real argunent */ /* registers here (for ARM), because the expansion */ /* of MOVDIR requires r2 > r1, and we have no way */ /* to constrain the result of register allocation. */ argstruct->deferred[realargr - R_A1].r = GAP; argstruct->deferred[argr2 - R_A1].r = GAP; AddUsedReg(argr2); emitreg(J_MOVDIR, realargr, argr2, r); } #endif else emitreg(J_MOVR, argr, GAP, r); bfreeregister(r); } } if (argstruct->fnsave != NULL) { argstruct->fnreg = fgetregister(ADDRREG); emitbinder(J_LDRV|J_ALIGN4V, argstruct->fnreg, argstruct->fnsave->bindlistcar); } emitsetsp(J_SETSPENV, save_binders); current_stackdepth = d; } } #define intregable(rep, e) \ (((rep) & MCR_SORT_MASK) != MCR_SORT_STRUCT \ || alignoftype(typeofexpr(e)) >= alignof_int \ || expr_alignment(e) >= alignof_int) static int32 cg_fnargs(ExprList *a, ArgInfo arg[], int32 n, FnargStruct *argstruct) /* specialarg is non-GAP if there is an implicit extra (first,integer) */ /* arg (e.g. for swi_indirect or 88000 struct return value pointer). */ { int32 intargwords, intregargs = 0, intregwords = 0, fltregargs = 0; int32 splitarg = -1; #ifdef TARGET_HAS_RISING_STACK Binder *arg0; #endif { int32 argoff = 0, narg = 0; SynBindList *newtemps = NULL; Expr *tempinits = NULL; #ifdef TARGET_FP_ARGS_IN_FP_REGS if ((config & CONFIG_FPREGARGS) && !(argstruct->auxflags & f_nofpregargs)) { ExprList *p, *q = NULL; /* Reorder the argument list, by destructively extracting the first */ /* up to NFLTARGREGS float args, and then dropping through to handle */ /* int args. This code needs better TARGET parameterisation. */ /* On the MIPS we only allow LEADING fp args in fp regs. */ /* Moreover such fp args inhibit the corresponding 2 int reg args! */ for (p = a; p != NULL; p = cdr_(p)) { Expr *ae = exprcar_(p); int32 repsort = mcrepofexpr(ae) >> MCR_SORT_SHIFT; if (repsort == 2 && narg < NFLTARGREGS) { arg[narg++].expr = ae; fltregargs++; if (q == NULL) a = cdr_(p); else cdr_(q) = cdr_(p); } else q = p; } } #endif /* The following code determines in which (int)reg an arg is going to */ /* be passed. In general this is the same as determining its address */ /* (see below '.addr') since register alignment of doubles passed in */ /* int regs usually matches that of doubles passed in storage. */ /* It could probably be merged into to the 'argoff' loop. */ if (argstruct->specialarg != GAP) intregwords--; /* intregargs can include specialarg, intregwords never does. */ for (; a != NULL; a = cdr_(a), narg++) { Expr *ae = exprcar_(a); int32 rep = mcrepofexpr(ae); #if alignof_double > alignof_int && !defined(TARGET_IS_SPARC) && \ !defined(TARGET_IS_ALPHA) int32 rbase = padsize(intregwords, rep & MCR_ALIGN_DOUBLE ? 2:1L); #else int32 rbase = intregwords; #endif int32 nreg = padsize((rep & MCR_SIZE_MASK), alignof_toplevel_auto) / alignof_toplevel_auto; int32 rlimit = rbase + nreg; arg[narg].expr = ae; arg[narg].nreg = (uint8)nreg; if (rbase < NARGREGS) { /* Some of the argument can be passed in registers */ bool loadable = intregable(rep, ae); if (rlimit > NARGREGS || !loadable) { Binder *gen; Expr *thisinit; if (!target_stack_moves_once) break; /* if !loadable, ae is a struct with alignment < */ /* alignof_int. Any object on the stack has */ /* alignment >= alignof_int Thus, copying to a temp */ /* is sufficient to allow this argument to be */ /* directly loaded into argument registers. */ /* If loadable, the argument is wider than an intreg */ /* and is to be passed partly in registers and partly*/ /* on the stack. */ if (!loadable || (h0_(ae) != s_binder && nastiness(ae) != ISXCONST)) { gen = gentempbinder(typeofexpr(ae)); newtemps = mkSynBindList(newtemps, gen); thisinit = mk_expr2(s_assign, bindtype_(gen), (Expr *)gen, ae); if (tempinits == NULL) tempinits = thisinit; else tempinits = mk_expr2(s_comma, te_void, thisinit, tempinits); arg[narg].expr = (Expr *)gen; } if (rlimit > NARGREGS) { arg[narg].nreg = (uint8)(NARGREGS - rbase); splitarg = narg; } } intregargs++; intregwords = rlimit; arg[narg].regoff = (uint8)rbase; } else break; } arg[narg].regoff = (uint8)intregwords; /* useful sentinel below? */ for (; a != NULL; a = cdr_(a), narg++) arg[narg].expr = exprcar_(a); if (narg != n) syserr(syserr_cg_argcount); for (narg = 0; narg < n; narg++) { Expr *ae = arg[narg].expr; int32 rep = mcrepofexpr(ae); if (h0_(ae) == s_binder && bindconst_(exb_(ae)) != NULL) { if (LanguageIsCPlusPlus) syserr("bindconst $b got to cg.c", exb_(ae)); ae = arg[narg].expr = bindconst_(exb_(ae)); } argoff = padtomcrep(argoff, rep); arg[narg].info = nastiness(ae); arg[narg].rep = rep; arg[narg].addr = argoff; /* Do not increment 'argoff' for specialarg (hidden argument). */ if (!(narg == fltregargs && argstruct->specialarg != GAP)) argoff += padsize(rep & MCR_SIZE_MASK, alignof_toplevel_auto); } if (newtemps != NULL) { cg_bindlist(newtemps, 0); cg_exprvoid(tempinits); } #if !defined(TARGET_HAS_RISING_STACK) && (alignof_double > alignof_toplevel_auto) /* The next line pads the offset of the last arg exactly in the case */ /* it will be handled by cg_fnargs_stack. If all the args are int-like */ /* and go directly to regs (i.e. <NARGREGS) then we do not have to pad */ /* after the last of an odd number of args. */ if (n != fltregargs+intregargs) argoff = padtomcrep(argoff, bindmcrep_(double_pad_binder)); #endif arg[narg].addr = argoff; /* sentinel for cg_fnargs_stack */ intargwords = (argoff - arg[fltregargs].addr)/alignof_toplevel_auto; /* Note that any hidden arg is not counted in intargwords. */ } #if (alignof_double > alignof_toplevel_auto) || defined(TARGET_IS_ALPHA) /* Pre-align stack to double alignment -- maybe one day */ /* suppress the alignment if there are no double args and the */ /* called proc can be seen to be floating-free and leaf-like. */ /* Note, by considering "f() { int x; g(0.0, &x); }", that this */ /* may waste stack space -- i.e. */ /* [ half of 0.0, half of 0.0, &x, pad, pad, x, f-linkage..] */ /* perhaps double_antipad_binder would help. */ { BindList *nb = active_binders; nb = mkBindList(nb, double_pad_binder); current_stackdepth = padtomcrep(current_stackdepth, bindmcrep_(double_pad_binder)); emitsetsp(J_SETSPENV, nb); } #endif #ifdef TARGET_HAS_RISING_STACK /* Leave gap on stack for those args which are passed in regs, but */ /* only if some are also (possibly unnecessarily) on the stack. */ if (intargwords > intregwords) { BindList *nb = active_binders; int32 i; for (i=0; i<intregargs; i++) { current_stackdepth += alignof_toplevel_auto; if (i==0) { nb = mkBindList(nb, gentempvar(te_int, GAP)); arg0 = nb->bindlistcar; /* needed later!! */ bindstg_(arg0) |= b_spilt; if (target_stack_moves_once) /* BEWARE: the next line is in flux (Nov89) and is only OK because */ /* 'arg0' never gets to be part of 'active_binders'. */ bindaddr_(arg0) = arg[0].addr | BINDADDR_NEWARG; else bindaddr_(arg0) = (current_stackdepth + arg[0].addr) | BINDADDR_LOC; } else nb = mkBindList(nb, integer_binder); } emitsetsp(J_SETSPENV, nb); } #endif cg_fnargs_stack(arg, intregargs+fltregargs, n, splitarg >= 0); if (nastiness(argstruct->fn) == ISHARD) argstruct->fnreg = cg_expr(argstruct->fn); #ifdef TARGET_IS_ARM_OR_THUMB /* this really means "TARGET_IMPLEMENTS_UnalignedLoadMayUse" */ else if (ContainsUnalignedSubExpr(argstruct->fn)) { int i; for (i = 0; i < intregwords; i++) if (UnalignedLoadMayUse(R_A1+i)) { argstruct->fnreg = cg_expr(argstruct->fn); break; } } #endif cg_fnargs_regs(arg, intregargs, fltregargs, argstruct, splitarg); #if (alignof_double > alignof_toplevel_auto) /* The next few lines deal with the trickiness of handling a call like */ /* f(1,2.3) which, if alignof_double==8 (excepting SPARC) can load */ /* regs a1, a3, a4. Keep regalloc happy by undefining a2 explicitly. */ /* Code above ensures we only pad at end of regs if also stack args. */ /* Beware: not tested with alignment AND specialarg != GAP. */ /* @@@ we should probably have done intregargs-- here if specialarg... */ /* @@@ (or used .regoff since very similar to .addr.) */ { int32 i = fltregargs + (argstruct->specialarg==GAP ? 0:1), r = 0; int32 ibase = arg[i].addr; while (intregwords < NARGREGS && ibase + 4*intregwords < arg[fltregargs+intregargs].addr) intregwords++; while (r < intregwords && i < fltregargs+intregargs) if (ibase + 4*r >= arg[i+1].addr) i++; else { if (ibase + 4*r >= arg[i].addr + padsize(arg[i].rep & MCR_SIZE_MASK, alignof_toplevel_auto)) emitbinder(J_INIT, R_A1 + r, 0); r++; } } #endif if (current_stackdepth > greatest_stackdepth) greatest_stackdepth = current_stackdepth; /* Now if some of the first few args were floating there are values on */ /* the stack that I want to have in registers. Ditto structure values. */ { RegList *q = NULL; int32 i; BindList *nb = active_binders; for (i=intregwords; i<intargwords && i<NARGREGS; i++) { VRegnum r = R_A1+i; if (ArgDeferred(r, argstruct->fn)) argstruct->deferred[i].r = r = vregister(INTREG); #ifdef TARGET_HAS_RISING_STACK if (intargwords > NARGREGS) emitvk(J_LDRVK|J_ALIGN4, r, 4*i, arg0); else #endif { q = mkRegList(q, r); /* @@@ The next line explains the contorted alternative */ /* to the #ifdef NEVER code in cg_fnargs_stack. */ if (nb->bindlistcar != integer_binder) syserr(syserr_padbinder, nb->bindlistcar); current_stackdepth -= alignof_toplevel_auto; intregwords++; } if (nb == NULL) syserr(syserr_null_nb); nb = nb->bindlistcdr; } if (q != NULL) { int32 i = 0; Binder *b = gentempbinder(te_void); /* @@@ hack */ bindstg_(b) |= b_spilt; cg_bindlist(mkSynBindList(0, b), 0); #define J_LDRLVKxx J_LDRLVK for (q = (RegList *)dreverse((List *)q); q != NULL; q = rl_discard(q)) { emitvk(alignof_toplevel_auto==8 ? J_LDRLVKxx|J_ALIGN8 : J_LDRVK|J_ALIGN4, q->rlcar, i, b); i += alignof_toplevel_auto; } emitsetsp(J_SETSPENV, nb); current_stackdepth -= i; } /* Recreate the list of used registers to keep life safe */ /* @@@ Redo soon? */ while (usedregs) usedregs = rl_discard(usedregs); while (usedfpregs) usedfpregs = rl_discard(usedfpregs); nusedregs = nusedfpregs = 0; if (argstruct->specialarg != GAP) usedregs = mkRegList(usedregs, argstruct->specialarg); for (i=0; i<intregwords; i++) { VRegnum r = R_A1+i; if (ArgDeferred(r, argstruct->fn) && argstruct->deferred[i].r != GAP) r = argstruct->deferred[i].r; AddUsedReg(r); } #ifdef TARGET_FP_ARGS_IN_FP_REGS for (i=0; i<fltregargs; i++) AddUsedReg(R_FA1+i); /* @@@ AM: why on earth does this code not use 'usedfpregs?'. */ /* answer: only one call of cg_expr for odd machine before discarded. */ #endif } /* Marker in argwords if a special register was used for a struct result */ return k_argdesc_(arg[n].addr/alignof_toplevel_auto, argfpmask, intregwords, fltregargs, argstruct->resultregs, argstruct->specialarg != GAP ? K_SPECIAL_ARG : 0L); } static void LoadDeferredArgReg(FnargStruct const *argstruct, int32 i) { VRegnum r = argstruct->deferred[i].r; if (r != GAP) { emitreg(J_MOVR, R_A1+i, GAP, r); bfreeregister(r); } else if (argstruct->deferred[i].e != NULL) (void)cg_exprreg(argstruct->deferred[i].e, R_A1+i); } static void LoadDeferredArgRegs(FnargStruct const *argstruct) { int32 i = NARGREGS; while (--i >= 0) LoadDeferredArgReg(argstruct, i); if (argstruct->specialarg != GAP) LoadDeferredArgReg(argstruct, argstruct->specialarg-R_A1); } /* For functions of 10 args or less, C stack is used, not SynAlloc space: */ #define STACKFNARGS 10 /* n.b. this is *not* a hard limit on no. of args */ /* NB also that I need STACKFNARGS to be at least as large as the no of */ /* registers for passing args if I have an 88000 as target. */ static void cg_fnap_1(AEop op, Expr *fn, TypeExpr *fnt, ExprList *a, VRegnum resreg, FnargStruct *argstruct) { int32 argdesc; VRegnum structresultp = GAP; Expr *structresult = NULL; Binder *structresultbinder = NULL; int32 resultwords = 0; uint16 fnflags; argstruct->resultregs = 0; argstruct->auxflags = fnflags = typefnaux_(fnt).flags; argstruct->resultrep = mcrepoftype(typearg_(fnt)); if ((op == s_fnapstruct || op == s_fnapstructvoid) && returnsstructinregs_t(fnt)) { resultwords = sizeoftype(typearg_(fnt)) / MEMCPYQUANTUM; structresult = exprcar_(a); a = cdr_(a); /* The +resreg term below accounts for the built-in */ /* divide+remainder functions, which are lyingly described as */ /* returning a single result (because that's easier for the */ /* front end to handle). resreg is always 0 for user-defined */ /* functions. */ argstruct->resultregs = resultwords + resreg; } { ArgInfo v[STACKFNARGS]; int32 n = length(a); /* The n+1 on the next line gives a sentinel to cg_fnargs. */ ArgInfo *p = (n+1) > STACKFNARGS ? (ArgInfo *)SynAlloc((n+1)*sizeof(ArgInfo)) : v; argstruct->specialarg = #ifdef TARGET_SPECIAL_ARG_REG (fnflags & f_specialargreg # ifdef TARGET_STRUCT_RESULT_REGISTER || op == s_fnapstruct || op == s_fnapstructvoid # endif ) ? TARGET_SPECIAL_ARG_REG : #endif GAP; argstruct->fn = fn; argstruct->fnreg = GAP; argstruct->fnsave = NULL; argdesc = cg_fnargs(a, p, n, argstruct); } /* Now the arguments are all in the right places - call the function */ if (structresult != NULL && op != s_fnapstructvoid) { if (h0_(structresult) == s_addrof && h0_(arg1_(structresult)) == s_binder) structresultbinder = exb_(arg1_(structresult)); else structresultp = cg_expr(structresult); /* /* this call to cg_expr() is wrong if specialarg or there may be a fn? */ /* it should probably go via the specialreg-like interface? */ } if (fntypeisvariadic(fnt)) argdesc |= K_VACALL; #if TARGET_SUPPRESS_VARIADIC_TAILCALL || TARGET_FLAGS_VA_CALLS /* WD: TARGET_FLAGS_VA_CALLS obsolete now: original meaning was not to use tailcalls on variadic function calls by 'faking' a normal function call. TARGET_SUPPRESS_VARIADIC_TAILCALL now does exactly that - without cheating */ if (fntypeisvariadic(fnt)) argdesc |= K_NOTAILCALL; #endif { Expr *temp; if (vregsort(resreg) == DBLREG && (fnflags & f_resultinintregs)) { /* returning fp result in integer registers (using hardfp) */ resreg = R_A1; argdesc = k_setresultregs_(argdesc, (argstruct->resultrep & MCR_SIZE_MASK) >> 2); } if (h0_(fn) == s_addrof && h0_(temp=arg1_(fn)) == s_binder) { TypeExpr *tt = princtype(bindtype_(exb_(temp))); /* The next next few lines represent an enthusiastic sanity check. */ /* We want to check that the Binder fn-type, esp. its typefnaux_() */ /* (which includes details of inline/reg-use/side-effectness) matches */ /* that in the s_addrof node (which is used above for struct-return- */ /* reg-use etc). Pointer equality (fnt==tt) used to work, but this is */ /* thwarted by globalize_expr() for C++ static initialisation. */ /* Note also that simplify.c:optimise_cast(isfntype) conspires too. */ LoadDeferredArgRegs(argstruct); if (fnt != tt) /* this memcmp is dubious, but the 'holes' should match. */ if (h0_(tt) != t_fnap || memcmp(&typefnaux_(fnt), &typefnaux_(tt), sizeof(TypeExprFnAux)) != 0) syserr(syserr_cg_fnap_1); if (fnflags & bitoffnaux_(s_pure)) argdesc |= K_PURE; if (fnflags & bitoffnaux_(s_commutative)) argdesc |= K_COMMUTATIVE; if (fnflags & f_resultinflags) argdesc |= K_RESULTINFLAGS; /* We could imagine code which emits several jopcodes here (saved in */ /* in-linable form in typefnaux_(fnt)) for in-line JOP expansion. */ if (fnflags & bitoffnaux_(s_swi)) emitcall(J_OPSYSK, resreg, argdesc, (Binder *)(IPtr)(typefnaux_(fnt).inlinecode)); else { emitcall(J_CALLK, resreg, argdesc | ((fnflags & f_notailcall) ? K_NOTAILCALL : 0), exb_(temp)); } } else switch (mcrepofexpr(fn)) { case 0x00000004: case 0x01000004: case 0x00000008: case 0x01000008: { VRegnum r = argstruct->fnreg; if (r == GAP) r = cg_expr(fn); LoadDeferredArgRegs(argstruct); emitcallreg(J_CALLR, resreg, argdesc, r); bfreeregister(r); break; } default: syserr(syserr_cg_fnap); } } if (structresult != NULL && op != s_fnapstructvoid) { int32 i; if (structresultbinder != NULL && !(bindstg_(structresultbinder) & bitofstg_(s_auto))) structresultp = cg_expr(structresult); for (i = 0; i < resultwords; i++) { if (structresultp != GAP) emit(J_memcpy(J_STRK|J_ALIGN4), resreg+i, structresultp, i * MEMCPYQUANTUM); else emitvk(J_memcpy(J_STRVK|J_ALIGN4), resreg+i, i * MEMCPYQUANTUM, structresultbinder); } bfreeregister(structresultp); } } static VRegnum cg_fnap(Expr *x, VRegnum resreg, bool valneeded) { SynBindList *sm1temps = NULL; Expr *sm1ass = NULL; if (target_stack_moves_once) /* If TARGET_STACK_MOVES_ONCE then we have to put all arglists in the */ /* same place. To avoid overwriting in f(g(1,2),g(3,4)) we transform */ /* this to "let (t0,t1) in (t0=g(1,2), t1=g(3,4), f(t0,t1))". */ /* We only do this transformation for ISHARD (= function containing) */ /* terms. This transformation is sometimes pessimistic (e.g. last */ /* arg to a procedure being a fn), but regalloc should be able to */ /* produce the code we first thought of. */ /* Before 'improving' the last arg. treatment, consider the case of */ /* it being a structure returning function, and thus overlap occurring. */ /* Note that this code destructively updates the aetree. */ { ExprList *a = exprfnargs_(x); for (; a != NULL; a = cdr_(a)) { Expr *ae = exprcar_(a); if (ae != NULL && nastiness(ae) == ISHARD) { /* ae == NULL for the return pointer for struct-in-regs */ /* functions */ TypeExpr *t = typeofexpr(ae); Binder *gen = gentempbinder(t); Expr *ass = mk_expr2(s_assign, t, (Expr *)gen, ae); exprcar_(a) = (Expr *)gen; sm1temps = mkSynBindList(sm1temps, gen); if (sm1ass == NULL) sm1ass = ass; else sm1ass = mk_expr2(s_comma, te_void, ass, sm1ass); } } } { /* Compile a call to a function - being tidied! */ RegSort rsort = vregsort(resreg); int32 spint = spareregs, spfp = sparefpregs; RegList *regstosave = usedregs, *fpregstosave = usedfpregs; int32 savebits = nusedregs, savefpbits = nusedfpregs; BindList *save_binders = active_binders; int32 d = current_stackdepth; SynBindList *things_to_bind = bindlist_for_temps(regstosave, fpregstosave); Expr *fn = arg1_(x); TypeExpr *fnt = princtype(typeofexpr(fn)); FnargStruct argstruct; /* Calling a function must preserve all registers - here I push any that */ /* are in use onto the stack. */ cg_bindlist(things_to_bind, 1); stash_temps(regstosave, fpregstosave, things_to_bind, J_STRV|J_ALIGN4V, J_STRFV|J_ALIGN4V, J_STRDV|J_ALIGN8); nusedregs = nusedfpregs = 0; /* new 20-6-87 */ usedregs = usedfpregs = NULL; spareregs = sparefpregs = 0; if (!((h0_(fnt) == t_content || h0_(fnt) == t_ref) && (h0_(fnt = princtype(typearg_(fnt))) == t_fnap || (h0_(fnt) == t_coloncolon && /* C++ ptr-to-mem fns */ h0_(fnt = princtype(typearg_(fnt))) == t_fnap)))) { pr_expr(fn); cc_msg(" of type "); pr_typeexpr(princtype(typeofexpr(fn)), 0); syserr(syserr_cg_fnap); } if (sm1temps != NULL) { cg_bindlist(sm1temps, 0); cg_exprvoid(sm1ass); } cg_fnap_1(h0_(x), fn, fnt, exprfnargs_(x), resreg, &argstruct); if (LanguageIsCPlusPlus) { /* need to know if we are inside a try{} block, but note that auto variables with destructors are also stored on currentExceptionEnv. */ ExceptionEnv* exenv = currentExceptionEnv; while (exenv!=NULL) { if (exenv->type == ex_handlerblock) { /* would be better to fiddle with the block flags so as to avoid having to fool the optimiser with bogus code*/ emit(J_CMPR , GAP, 0, 0);/*compare always true*/ emitbranch(J_B + Q_NE, exenv->handlers.henv.handlerblock); start_new_basic_block(nextlabel()); break; } exenv=exenv->cdr; } } if (rsort == DBLREG && (argstruct.resultrep & MCR_SIZE_MASK) == sizeof_float) rsort = FLTREG; /* All registers are now free - work out what the args to the fn are */ /* Switch back to the outer context of registers. */ while (usedregs) usedregs = rl_discard(usedregs); while (usedfpregs) usedfpregs = rl_discard(usedfpregs); usedregs = regstosave, usedfpregs = fpregstosave; nusedregs = savebits, nusedfpregs = savefpbits; spareregs = spint, sparefpregs = spfp; { VRegnum resultr = GAP; if (valneeded) { if (returnsstructinregs_t(fnt) && argstruct.resultregs > 1) resultr = resreg; else { resultr = fgetregister(rsort); if (rsort == FLTREG) { if (argstruct.auxflags & f_resultinintregs) emitreg(J_MOVIFR, resultr, GAP, R_A1); else emitreg(J_MOVFR, resultr, GAP, resreg); } else if (rsort == DBLREG) { if (argstruct.auxflags & f_resultinintregs) emitreg(J_MOVIDR, resultr, R_A1, R_A1+1); else emitreg(J_MOVDR, resultr, GAP, resreg); } else emitreg(J_MOVR, resultr, GAP, resreg); } } stash_temps(regstosave, fpregstosave, things_to_bind, J_LDRV|J_ALIGN4V, J_LDRFV|J_ALIGN4V, J_LDRDV|J_ALIGN8); while (things_to_bind) things_to_bind = freeSynBindList(things_to_bind); emitsetsp(J_SETSPENV, save_binders); current_stackdepth = d; return resultr; } } } static ExceptionEnv *mkExceptionEnv(ExceptionEnv* cdr, ex_enum type, void* destructee) { ExceptionEnv* ExEnv = (ExceptionEnv *) BindAlloc (sizeof (ExceptionEnv)); ExEnv->cdr = cdr; ExEnv->type = type; if (type==ex_destructor) ExEnv->handlers.destructee = (Binder*) destructee; else /*type==ex_handlerblock*/ ExEnv->handlers.henv.handlerblock = (LabelNumber*) destructee; return ExEnv; } static HandlerList *mkHandlerList(HandlerList *cdr, int type, LabelNumber *handler) { HandlerList *h = BindAlloc(sizeof(HandlerList)); h->cdr = cdr; h->type = type; h->handler = handler; return h; } /* jopcode generation for commands ... */ static void cg_cmd(Cmd *x) { Cmd *oldcmd = cg_current_cmd; AEop op; while (x != 0) { cg_current_cmd = x; if (cmdfileline_(x).f != 0) { /* This (outer) 'if' block could be a proc as appears below too */ if (!cg_infobodyflag) { #ifdef TARGET_HAS_PROFILE if (profile_option) emitfl(J_COUNT, cmdfileline_(x)); #endif if (usrdbg(DBG_PROC)) emit(J_INFOBODY, GAP, GAP, 0); cg_infobodyflag = 1; } if (usrdbg(DBG_LINE)) emitfl(J_INFOLINE, cmdfileline_(x)); } switch (op = h0_(x)) { default: syserr(syserr_cg_cmd, (long)op, op); break; case s_endcase: /* those 'break's meaning "exit switch" */ if (switchinfo.endcaselab==NOTINSWITCH) syserr(syserr_cg_endcase); else { emitsetspandjump(switchinfo.binders, switchinfo.endcaselab); } break; case s_break: /* those 'break's meaning "exit loop" */ if (loopinfo.breaklab==NOTINLOOP) syserr(syserr_cg_break); else { if (loopinfo.breaklab == 0) loopinfo.breaklab = nextlabel(); emitsetspandjump(loopinfo.binders, loopinfo.breaklab); } break; case s_continue: if (loopinfo.contlab==NOTINLOOP) syserr(syserr_cg_cont); else { if (loopinfo.contlab == 0) loopinfo.contlab = nextlabel(); emitsetspandjump(loopinfo.binders, loopinfo.contlab); } break; #ifdef EXTENSION_VALOF case s_resultis: /* Valof blocks will not work (a syserr will occur via cg_addr */ /* or cg_exprreg) for structure results and would need code */ /* here and at s_resultis (and cg_addr &c) to make them work. */ { Expr *val = cmd1e_(x); if (val != 0) /* In case of 'resultis <errornode>' */ (void)cg_exprreg(val, valofinfo.r); } emitsetspandjump(valofinfo.binders, valofinfo.lab); break; #endif case s_return: cg_count(cmdfileline_(x)); cg_return(cmd1e_(x), NO); break; case s_do: cg_loop(0, 0, 0, cmd1c_(x), cmd2e_(x)); break; case s_for: cg_loop(cmd1e_(x), cmd2e_(x), cmd3e_(x), cmd4c_(x), 0); break; case s_if: { LabelNumber *l1 = nextlabel(); Cmd *cc; cg_test(cmd1e_(x), 0, l1); cc = cmd2c_(x); if (cc != NULL) /* This mess is because we can properly have a null consequence for a */ /* condition, but then it does not have a count field to pass down to */ /* cg_count! */ { cg_count(cmdfileline_(cc)); cg_cmd(cc); } if ((x = cmd3c_(x))==0) start_new_basic_block(l1); else { LabelNumber *l2 = nextlabel(); emitbranch(J_B, l2); start_new_basic_block(l1); cg_cmd(x); start_new_basic_block(l2); cg_count(cmdfileline_(x)); } } break; case s_switch: if ((mcrepofexpr(cmd1e_(x)) >> MCR_SORT_SHIFT) > 1) syserr(syserr_cg_switch); cg_count(cmdfileline_(x)); { VRegnum r = cg_expr(cmd1e_(x)); struct SwitchInfo oswitchinfo; int32 ncases = 0, i; CasePair *casevec; Cmd *c; oswitchinfo = switchinfo; switchinfo.endcaselab = nextlabel(); switchinfo.binders = active_binders; switchinfo.defaultlab = switch_default_(x) ? nextlabel() : switchinfo.endcaselab; for (c = switch_caselist_(x); c != 0; c = case_next_(c)) ncases++; /* count cases */ /* n.b. SynAlloc is used in the next line -- the store will die very soon */ /* we should use a 'C' auto vector for small amounts here */ casevec = (CasePair *) SynAlloc(ncases*sizeof(casevec[0])); i = ncases; for (c = switch_caselist_(x); c != 0; c = case_next_(c)) { LabelNumber *ln = nextlabel(); if (h0_(c) != s_case) syserr(syserr_cg_caselist); i--; /* syn sorts them backwards */ casevec[i].caseval = evaluate(cmd1e_(c)); casevec[i].caselab = ln; /* case_lab_(c) */ cmd4c_(c) = (Cmd *)ln; } /* previous phases guarantee the cases are sorted by now */ blkflags_(bottom_block) |= BLKREXPORTED; casebranch(r, casevec, ncases, switchinfo.defaultlab); bfreeregister(r); cg_cmd(cmd2c_(x)); start_new_basic_block(switchinfo.endcaselab); switchinfo = oswitchinfo; } break; case s_try: { LabelNumber *l, *handler_exit_label, *handlerblock_label; ExceptionEnv* ExEnv = currentExceptionEnv;/* remember ExceptionEnv*/ Handler* handler_list = (Handler*) cmd2e_ (x); List* hl; currentExceptionEnv = mkExceptionEnv(currentExceptionEnv, ex_handlerblock, 0); hl = (List*) handler_list; for(currentExceptionEnv->handlers.henv.handlercount=0;hl!=NULL;hl=hl->cdr) { currentExceptionEnv->handlers.henv.handlerlist = mkHandlerList(currentExceptionEnv->handlers.henv.handlerlist, 0, /*should be handler type*/ nextlabel()); currentExceptionEnv->handlers.henv.handlercount++; } handlerblock_label = nextlabel(); currentExceptionEnv->handlers.henv.handlerblock = handlerblock_label; cg_cmd(cmd1c_(x)); /* body of 'try' */ ExEnv = currentExceptionEnv; currentExceptionEnv = currentExceptionEnv->cdr; l = nextlabel(); emitbranch(J_B, l); if (cmd3c_(x)!=NULL) /* cmd3c is handler_exit */ handler_exit_label = nextlabel(); else handler_exit_label = l; { /* set blk_table from HandlerEnv*/ int i = ExEnv->handlers.henv.handlercount; LabelNumber** ll = BindAlloc (sizeof (LabelNumber*) * i); start_new_basic_block(handlerblock_label); emitcasebranch(J_TYPECASE, GAP, ll, i); i = 0; for (;handler_list!=NULL; handler_list=handler_list->handcdr) /* if (h0_(handler_list->handbody) != s_throw) this is wrong; there is currently no easy way to distinguish a handler which just does throw;*/ { ll[i]=nextlabel(); start_new_basic_block(ll[i++]); cg_cmd(handler_list->handbody); emitbranch(J_B, handler_exit_label); } } if (cmd3c_(x)!=NULL) { start_new_basic_block(handler_exit_label); cg_cmd(cmd3c_(x)); emitbranch(J_B, l); } else if (debugging(DEBUG_CG)) printf("this try has no handler_exit block\n"); start_new_basic_block(l); } break; case s_catch: { Handler *unused_handler = cmdhand_(x); /* syn.c has given an error for this June 1993. */ IGNORE(unused_handler); x = cmd1c_(x); continue; } /* I wonder if this is the way to do it, or to pass this structure */ /* on to later stages of the compiler. The key thing is to ensure */ /* that all back-ends see: ORG n; ADD a1,delta; TAILCALLK fn. */ case s_thunkentry: { VfnList *l = (VfnList *)cmd1e_(x), *p; int32 ncases = 0, i; LabelNumber **table; for (p = l; p != 0; p = p->vfcdr) ncases++; table = (LabelNumber **) BindAlloc( ncases * sizeof(LabelNumber *)); for ((i = 0, p = l); p != 0; p = p->vfcdr) table[i++] = nextlabel(); #ifdef TARGET_HAS_DATA_VTABLES if (target_has_data_vtables || ncases > 1) #else if (ncases > 1) #endif emitcasebranch(J_THUNKTABLE, GAP, table, ncases); for ((i = 0, p = l); p != 0; (i++, p = p->vfcdr)) { start_new_basic_block(table[i]); if (TARGET_VTAB_ELTSIZE > 4) emit(J_ORG, GAP, GAP, i*TARGET_VTAB_ELTSIZE); emit(J_ADDK, R_P1, R_P1, p->vfdelta); /* ECN: Set 'K_THUNK' bit so we can differentiate these * from ordinary J_CALLK later */ emitcall(J_CALLK, V_resultreg(INTREG), k_argdesc_(1, 0, 1, 0, 0, 0)|K_THUNK, p->vfmem); cg_return(0,0); } } break; case s_case: if (switchinfo.defaultlab==NOTINSWITCH) syserr(syserr_cg_case); { LabelNumber *l1 = case_lab_(x); if (l1 == NULL) syserr(syserr_unset_case); cg_case_or_default(l1); } x = cmd2c_(x); continue; case s_default: if (switchinfo.defaultlab==NOTINSWITCH) syserr(syserr_cg_default); cg_case_or_default(switchinfo.defaultlab); x = cmd1c_(x); continue; case s_colon: { LabBind *labbinder = cmd1lab_(x); LabelNumber *ln = labbinder->labinternlab; if (ln == NULL) ln = labbinder->labinternlab = nextlabel(); start_new_basic_block(ln); } cg_count(cmdfileline_(x)); x = cmd2c_(x); continue; case s_goto: { LabBind *labbinder = cmd1lab_(x); LabelNumber *l = labbinder->labinternlab; if (l == NULL) l = labbinder->labinternlab = nextlabel(); if (labbinder->labuses & l_defined) /* else bind.c err msg */ { emitsetspgoto(active_binders, l); emitbranch(J_B, l); } } break; case s_semicolon: /* cmd1e_(x) should by non-NULL, but be gentle for error recovery. */ if (cmd1e_(x) != NULL) cg_exprvoid(cmd1e_(x)); break; case s_block: { BindList *sl = active_binders; int32 d = current_stackdepth; CmdList *cl = cmdblk_cl_(x); SynBindList *bl = cmdblk_bl_(x); bool destructee = false; cg_bindlist(bl, 0); if (bl != NULL) { Binder* e = bl->bindlistcar ; if (isclasstype_(princtype(typeofexpr((Expr*)e)))) { destructee = true; currentExceptionEnv = mkExceptionEnv (currentExceptionEnv, ex_destructor, e); start_new_basic_block(nextlabel()); } } if (usrdbg(DBG_VAR)) { current_env = (BindListList *) binder_cons2(current_env, binderise(bl)); /* Hmm, this code is in flux pro tem. but the idea is */ /* that we have to put debug scope info into block */ /* heads so that is cannot get deadcoded away (discuss) */ (void)start_new_basic_block(nextlabel()); } for (; cl!=NULL; cl = cdr_(cl)) cg_cmd(cmdcar_(cl)); if (usrdbg(DBG_VAR)) { current_env = current_env->bllcdr; (void)start_new_basic_block(nextlabel()); } if (destructee) { currentExceptionEnv = currentExceptionEnv->cdr; (void)start_new_basic_block(nextlabel()); } emitsetsp(J_SETSPENV, sl); current_stackdepth = d; } break; /* from switch */ #ifdef TARGET_HAS_INLINE_ASSEMBLER case s_asm: cg_asm (x); break; #endif } break; /* from loop */ } cg_current_cmd = oldcmd; } static void cg_test1(Expr *x, bool branchtrue, LabelNumber *dest) { VRegnum r; int32 bc, bcl; if (x == 0) { syserr(syserr_missing_expr); return; } verify_integer(x); if (usrdbg(DBG_LINE) && hasfileline_(h0_(x)) && exprfileline_(x) != 0) emitfl(J_INFOLINE, *exprfileline_(x)); if (integer_constant(x)) { if ((result2==0 && !branchtrue) || (result2!=0 && branchtrue)) emitbranch(J_B, dest); return; } else switch (h0_(x)) { case s_let: { BindList *sl = active_binders; int32 d = current_stackdepth; LabelNumber *ltrue = nextlabel(); LabelNumber *lfalse = nextlabel(); cg_bindlist(exprletbind_(x), 0); cg_test1(arg2_(x), !branchtrue, lfalse); { int32 d1 = current_stackdepth; BindList *sl1 = active_binders; start_new_basic_block(ltrue); emitsetsp(J_SETSPENV, sl); current_stackdepth = d; emitbranch(J_B, dest); active_binders = sl1; current_stackdepth = d1; start_new_basic_block(lfalse); emitsetsp(J_SETSPENV, sl); current_stackdepth = d; return; } } default: if (resultinflags_fn(x)) { uint32 cond = typefnauxflags_(princtype(typearg_(princtype(typeofexpr(arg1_(x)))))) & Q_MASK; r = cg_fnap(x, V_resultreg(INTREG), NO); bfreeregister(r); emitbranch(J_B + (branchtrue ? cond : Q_NEGATE(cond)), dest); return; } r = cg_expr(x); emit(J_CMPK+ (branchtrue ? Q_NE : Q_EQ), GAP, r, 0); bfreeregister(r); emitbranch(J_B+ (branchtrue ? Q_NE : Q_EQ), dest); return; case_s_any_string if (branchtrue) emitbranch(J_B, dest); return; case s_andand: if (branchtrue) { LabelNumber *l = nextlabel(); cg_test1(arg1_(x), 0, l); cg_count(cmdfileline_(cg_current_cmd)); cg_test1(arg2_(x), 1, dest); start_new_basic_block(l); return; } else { cg_test1(arg1_(x), 0, dest); cg_count(cmdfileline_(cg_current_cmd)); cg_test1(arg2_(x), 0, dest); return; } case s_oror: if (!branchtrue) { LabelNumber *l = nextlabel(); cg_test1(arg1_(x), 1, l); cg_count(cmdfileline_(cg_current_cmd)); cg_test1(arg2_(x), 0, dest); start_new_basic_block(l); return; } else { cg_test1(arg1_(x), 1, dest); cg_count(cmdfileline_(cg_current_cmd)); cg_test1(arg2_(x), 1, dest); return; } case s_boolnot: cg_test1(arg1_(x), !branchtrue, dest); return; case s_comma: cg_exprvoid(arg1_(x)); cg_test1(arg2_(x), branchtrue, dest); return; case s_monplus: /* Monadic plus does not have to generate any code */ cg_test1(arg1_(x), branchtrue, dest); return; /* case s_and: may turn into J_BIT */ case s_equalequal: bc = Q_NE, bcl = Q_UNE; break; case s_notequal: bc = Q_EQ, bcl = Q_UEQ; break; case s_greater: bc = Q_LE, bcl = Q_LS; break; case s_greaterequal: bc = Q_LT, bcl = Q_LO; break; case s_less: bc = Q_GE, bcl = Q_HS; break; case s_lessequal: bc = Q_GT, bcl = Q_HI; break; } { Expr *e1 = arg1_(x), *e2 = arg2_(x); int32 rep; if (resultinflags_fn(e1)) e1 = mk_expr3(s_cond, te_int, e1, mkintconst(te_int, 1, 0), mkintconst(te_int, 0, 0)); if (resultinflags_fn(e2)) e2 = mk_expr3(s_cond, te_int, e2, mkintconst(te_int, 1, 0), mkintconst(te_int, 0, 0)); rep = mcrepofexpr(e1); if (rep == MCR_SORT_FLOATING+8 || rep == MCR_SORT_FLOATING+8+MCR_ALIGN_DOUBLE) cg_condjump(J_CMPDR, e1, e2, DBLREG, (branchtrue ? Q_NEGATE(bc) : bc), dest); else if (rep == MCR_SORT_FLOATING+4) cg_condjump(J_CMPFR, e1, e2, FLTREG, (branchtrue ? Q_NEGATE(bc) : bc), dest); else if ((rep & MCR_SORT_MASK) == MCR_SORT_UNSIGNED || rep == MCR_SORT_PLAIN+1) /* plain char */ cg_condjump(J_CMPR, e1, e2, INTREG, (branchtrue ? Q_NEGATE(bcl) : bcl), dest); else if ((rep & MCR_SORT_MASK) == MCR_SORT_SIGNED) cg_condjump(J_CMPR, e1, e2, INTREG, (branchtrue ? Q_NEGATE(bc) : bc), dest); else syserr(syserr_cg_badrep, (long)rep); } return; } static void cg_cast2(VRegnum r1, VRegnum r, int32 mcmode, int32 mclength) { if (mcmode == 0) emit(J_EXTEND, r1, r, mclength); else emit(J_ANDK, r1, r, lowerbits(8*mclength)); } static VRegnum cg_cast1_(VRegnum r, int32 mclength, int32 mcmode, int32 argrep) { int32 argmode = argrep >> MCR_SORT_SHIFT, arglength = argrep & MCR_SIZE_MASK; VRegnum r1; RegSort rsort = (mcmode!=2) ? INTREG : mclength==4 ? FLTREG : DBLREG; if (mcmode==3 || argmode==3) { if (mcmode==argmode && mclength==arglength) return r; else syserr(syserr_cg_cast); } if (mcmode==argmode) switch(mcmode) { case 0: /* change width of integer */ /* The test mclength==4 on the next and subsequent lines is a */ /* temporary hack for TARGET_IS_ADENART on the way to full 64-bit ops. */ if (mclength>=arglength || mclength==4) return r; emit(J_EXTEND, r1=fgetregister(INTREG), r, /* Yukky coding here 0 is EXTENDBW, 1 is EXTENDBL, 2 is EXTENDWL... * this oddity should be changed sometime later - or at the very least * lifted into some enumeration or set of #define constants. */ mclength == 1 ? (arglength == 2 ? 0 : 1) : 2); bfreeregister(r); return r1; case 1: /* change width of (unsigned) */ /* The test mclength==4 on the next and subsequent lines is a */ /* temporary hack for TARGET_IS_ADENART on the way to full 64-bit ops. */ if (mclength>=arglength || mclength==4) return r; emit(J_ANDK, r1=fgetregister(INTREG), r, lowerbits(8*mclength)); bfreeregister(r); return r1; case 2: /* change width of float */ if (mclength==arglength) return r; r1 = fgetregister(rsort); if (mclength==4 && arglength==8) emitreg(J_MOVDFR, r1, GAP, r); else if (mclength==8 && arglength==4) emitreg(J_MOVFDR, r1, GAP, r); else syserr(syserr_cg_fpsize, (long)arglength, (long)mclength); bfreeregister(r); return r1; default: if (mclength==arglength) return r; syserr(syserr_cg_cast1, (long)mcmode); return GAP; } else if (mcmode==2) { /* floating something */ /* @@@ LDS 23Aug89 - This comment used to say: */ /* "Earlier parts of the compiler ensure that it is only necessary to */ /* cope with full 32-bit integral types here. Such things as (float) on */ /* a character are dealt with as (float)(int)<char> with the inner cast */ /* explicit in the parse tree." */ /* This is no longer true (move of cast optimisation to optimise1()) and */ /* is clearly nonsense, as this function throws away integer widening */ /* casts in cases 0 and 1 (signed and unsigned) of the if () above. */ /* if (arglength!=4) syserr(syserr_cg_cast3, (long)arglength); */ #ifdef TARGET_LACKS_UNSIGNED_FIX if (argmode != 0) /* unsigned float - simulate with signed */ { VRegnum r2; emit(J_EORK, r2 = fgetregister(INTREG), r, 0x80000000); emitreg(J_FLTDR+J_SIGNED, r1 = fgetregister(DBLREG), GAP, r2); bfreeregister(r2); /* N.B. fc_two_31 is double - but this trick won't work with single */ /* so I do it in double and then convert down to single precision */ emitfloat1(J_MOVDK, r2 = fgetregister(DBLREG), GAP, fc_two_31); emitreg(J_ADDDR, r1, r1, r2); bfreeregister(r2); /* the next line should recursively call cg_cast() or cg_expr1() so we */ /* check that we are not running out of regs. */ if (mclength==4) { VRegnum r3 = fgetregister(FLTREG); emitreg(J_MOVDFR, r3, GAP, r1); /* shorten */ bfreeregister(r1); r1 = r3; } } else #endif /* TARGET_LACKS_UNSIGNED_FIX */ { int32 w = (argmode==0) ? J_SIGNED : J_UNSIGNED; r1 = fgetregister(rsort); emitreg((rsort==FLTREG ? J_FLTFR : J_FLTDR) + w, r1, GAP, r); } bfreeregister(r); return r1; } else if (argmode==2) { /* fixing something */ #ifdef TARGET_LACKS_UNSIGNED_FIX /* N.B. the mclength==4 test in the next line is to produce shorter code */ /* for (unsigned short)(double)x. It implies that this is calculated as */ /* (unsigned short)(int)(double)x. */ if (mcmode != 0 && mclength == 4) { VRegnum r2, r3; /* Fixing to an unsigned result is done by subtracting 2^31, so that the * range is signed, and a signed FIX can be used with rounding to minus * infinite. After this, adding 2^31 again gives the correct result, * including positive/negative overflow. */ if (arglength == 4) { /* cast to double, since float doesn't have enough precision */ emitreg(J_MOVFDR, r3 = fgetregister(DBLREG), GAP, r); bfreeregister(r); r = r3; } emitfloat1(J_MOVDK, r2 = fgetregister(DBLREG), GAP, fc_two_31); emitreg(J_SUBDR, r, r, r2); /* use 3-addr arm op one day? */ emitreg(J_FIXDRM+J_SIGNED, r1 = fgetregister(INTREG), GAP, r); emit(J_EORK, r1, r1, 0x80000000); bfreeregister(r2); } else emitreg((arglength==4 ? J_FIXFR : J_FIXDR) + J_SIGNED, r1 = fgetregister(INTREG), GAP, r); /* see N.B. above */ #else /* TARGET_LACKS_UNSIGNED_FIX */ { int32 w = (mcmode == 0) ? J_SIGNED : J_UNSIGNED; emitreg((arglength==4 ? J_FIXFR : J_FIXDR) + w, r1 = fgetregister(INTREG), GAP, r); } #endif /* TARGET_LACKS_UNSIGNED_FIX */ /* If I do something like (short)<some floating expression> I need to */ /* squash the result down to 16 bits. */ if (mclength < 4) cg_cast2(r1, r1, mcmode, mclength); bfreeregister(r); return r1; } else if (arglength==4 && mclength==4) return r; else if (mcmode==0 || mcmode==1) { if (mclength>=4) return r; cg_cast2(r1=fgetregister(INTREG), r, mcmode, mclength); bfreeregister(r); return r1; } else { syserr(syserr_cg_cast2, (long)mcmode, (long)mclength, (long)argmode, (long)arglength); return GAP; } } static VRegnum cg_cast1(Expr *x1, int32 mclength, int32 mcmode) { if (mclength==0) return cg_exprvoid(x1); /* cast to void */ return cg_cast1_(cg_expr(x1), mclength, mcmode, mcrepofexpr(x1)); } /* At some point we might be willing for a xxx/target.h to specify a */ /* macro/fn for (a renamed) cg_limit_displacement to exploit machines */ /* like ARM which do not have a proper notion of quantum/min/max. */ static int32 cg_limit_displacement(int32 n, J_OPCODE op, int32 ld_align, int32 mclength, int32 flag) /* nasty arg! */ { int32 mink, maxk, span, w, offset; IGNORE(mclength); IGNORE(flag); mink = MinMemOffset(op + ld_align); maxk = MaxMemOffset(op + ld_align); span = maxk - mink + 1; /* I insist that span be a power of two, so that the inserted offset */ /* in the code given below has a neat machine representation. On many */ /* machines all is OK already, but on the ARM span as defined above is */ /* one less than a power of two. Fix it up... */ /* AM: I think 'neat' above means 'ARM-neat(8 bits)'. */ w = 0; do { span -= w; w = span & (-span); /* least significant bit */ } while (span != w); /* stop when span has just 1 bit */ /* If n is between mink and maxk (and quantum accessible) we want to */ /* return it directly, else generate a 'least bits' additive fixup. */ /* The following expression is believed algebraically equivalent to */ /* ACN's in the case quantum=1. @@@ Unify with take_neat_address. */ /* Note the assumption that (mink & -quantum) == mink! */ offset = n; if (offset < mink || offset > maxk) { offset = (unsigned32)n % span; /* If this will do, it is bound to leave a remainder that */ /* is easier to handle (fewer bits) than n was, whereas the */ /* numbers below have no such guarrantee */ if (offset < mink || offset > maxk) offset = (n - mink > 0) ? mink + (n - mink) % span : (maxk - n > 0) ? maxk - (maxk - n) % span : maxk + (maxk - n) % span; } return offset & (-MemQuantum(op + ld_align)); } static VRegnum cg_stind(VRegnum r, Expr *val, Expr *x, const int32 flag, Binder *b, const int32 mcmode, const int32 mclength, bool address, int volatileorunaligned) /* now combines effect of old cg_content. */ /* calculates: *x if flag==s_content */ /* *x = r if flag==s_assign */ /* prog1(*x,*x = r) if flag==s_displace */ /* In the latter two cases, if r==GAP the value to be stored is given by */ /* val (not yet given to cg_expr) */ /* The above values are the ONLY valid values for flag */ { J_OPCODE ld_op; int32 ld_align; Expr *x1, *x2 = NULL; int32 n = 0, shift = 0, postinc = 0, down = 0; /* n.b. could add down to addrmode sometime */ enum Addr_Mode { AD_RD, AD_RR, AD_VD } addrmode = AD_RD; RegSort rsort = mcmode!=2 ? INTREG : (mclength==4 ? FLTREG : DBLREG); int32 signedness = mclength >= 4 ? 0 : mcmode == 0 ? J_SIGNED : J_UNSIGNED; switch (mcmode) { case 0: /* signed */ case 1: /* unsigned */ switch (mclength) { case 1: ld_op = J_LDRBK; ld_align = J_ALIGN1; break; case 2: ld_op = J_LDRWK; ld_align = J_ALIGN2; break; case 4: ld_op = J_LDRK; ld_align = J_ALIGN4; break; case 8: ld_op = J_LDRLK; ld_align = J_ALIGN8; break; default: syserr(syserr_cg_bad_width, (long)mclength); ld_op = J_NOOP; ld_align = J_ALIGN1; } break; case 2: if (rsort==FLTREG) ld_op = J_LDRFK, ld_align = J_ALIGN4; else ld_op = J_LDRDK, ld_align = J_ALIGN8; break; default: syserr(syserr_cg_bad_mode, (long)mcmode); ld_op = J_NOOP; ld_align = J_ALIGN1; break; } if (volatileorunaligned & IsUnaligned) ld_align = J_ALIGN1; #ifdef NEW_J_ALIGN_CODE /* was TARGET_IS_ADENART */ /* Although this code is just for a special machine (which encourages */ /* all 64-bit aligned loads to be done with J_LDRLK), the idea should */ /* be generalisable (e.g. to improve the TARGET_LACKS_HALFWORD_STORE */ /* code below). */ /* We convert ld/st 8/16/32 bits into 64-bit rd/wr, sign-/zero- */ /* extending on load 8/16 bits and write beyond the item into */ /* space which alignof_toplevel guarantees is junk. */ /* Note: the only reason we don't always enable this code is that it */ /* might harm cross-jumping optimisation. */ if (b != NULL) { int32 newalign = toplevel_alignment(b); int32 new_j_align = newalign == 8 ? J_ALIGN8 : newalign == 4 ? J_ALIGN4 : newalign == 2 ? J_ALIGN2 : J_ALIGN1; if (new_j_align > ld_align) ld_align = new_j_align; } #endif #ifdef ADDRESS_REG_STUFF if (rsort==INTREG && address) rsort = ADDRREG; #else IGNORE(address); #endif while (h0_(x) == s_cast) { int32 rep = mcrepofexpr(arg1_(x)); if (rep >= MCR_SORT_FLOATING || (rep & MCR_SIZE_MASK) != sizeof_ptr) break; x = arg1_(x); } switch (h0_(x)) { case s_plus: x1 = arg1_(x), x2 = arg2_(x); #ifdef TARGET_HAS_SCALED_ADDRESSING /* one might wonder whether the test for is_shifted or s_integer should */ /* come first. Observe that either is correct, and the sensible code */ /* can never have both on an indirection. E.g. *(int *)(3 + (x<<7)). */ /* Moreover, if the machine cannot support all these modes then some are */ /* killed below. */ if (is_shifted(x1, mclength, signedness, ld_op | ld_align)) { Expr *x3 = x1; x1 = x2; x2 = shift_operand(x3); shift = shift_amount(x3); addrmode = AD_RR; } else if (is_shifted(x2, mclength, signedness, ld_op | ld_align)) { shift = shift_amount(x2); x2 = shift_operand(x2); addrmode = AD_RR; } else #endif /* TARGET_HAS_SCALED_ADDRESSING */ if (h0_(x1)==s_integer) n = intval_(x1), x1 = x2; else if (h0_(x2)==s_integer) n = intval_(x2); else addrmode = AD_RR; break; case s_minus: x1 = arg1_(x), x2 = arg2_(x); #ifdef TARGET_HAS_SCALED_ADDRESSING if (is_shifted(x1, mclength, signedness, ld_op | ld_align)) { Expr *x3 = x1; x1 = mk_expr1(s_neg, type_(x), x2); x2 = shift_operand(x3); shift = shift_amount(x3); addrmode = AD_RR; } /* /* why on earth is it interesting if x2 is shifted if we don't have */ /* negative-indexing? */ /* ACN to check and move is_shifted test into conditional code? */ else if (is_shifted(x2, -mclength, signedness, ld_op | ld_align)) /* Negative mclength marks operand as subtracted */ #ifdef TARGET_HAS_NEGATIVE_INDEXING { shift = shift_amount(x2); if ((shift & (SHIFT_RIGHT|SHIFT_ARITH)) == (SHIFT_RIGHT|SHIFT_ARITH)) cc_rerr(cg_rerr_iffy_arithmetics); x2 = shift_operand(x2); down = J_NEGINDEX, addrmode = AD_RR; } else if (h0_(x2)==s_integer) n = -intval_(x2); else down = J_NEGINDEX, addrmode = AD_RR; #else /* !TARGET_HAS_NEGATIVE_INDEXING */ { shift = shift_amount(x2); x2 = shift_operand(x2); x2 = mk_expr1(s_neg, typeofexpr(x2), x2); addrmode = AD_RR; } else if (h0_(x2)==s_integer) n = -intval_(x2); else x1 = x, x2 = 0; #endif /* TARGET_HAS_NEGATIVE_INDEXING */ #else /* TARGET_HAS_SCALED_ADDRESSING */ if (h0_(x2)==s_integer) n = -intval_(x2); else x1 = x, x2 = 0; #endif /* TARGET_HAS_SCALED_ADDRESSING */ break; case s_displace: { Expr *v = arg1_(x), *x3 = arg2_(x); if (h0_(x3) == s_plus && is_same(arg1_(x3),v) && integer_constant(arg2_(x3))) { postinc = result2; x = v; } } /* drop through */ default: x1 = x, x2 = 0; break; } /* This code was, and may be better a procedure. */ /* Sample observations: x2 is valid only if addrmode == AD_RR (2 reg addr) */ /* Now make allowance for the limited offsets available with LDRK/STRK */ if (addrmode == AD_RD) { int32 n1; if (h0_(x1) == s_integer) { n += intval_(x1); n1 = cg_limit_displacement(n, ld_op, ld_align, mclength, flag); x1 = mkintconst(type_(x), n - n1, 0); } else { n1 = cg_limit_displacement(n, ld_op, ld_align, mclength, flag); if (n1 != n) x1 = mk_expr2(s_plus, type_(x), x1, mkintconst(te_int, n-n1, 0)); } n = n1; } /* The following line needs regularising w.r.t. machines, like ARM */ /* where fp/halfword addressing differs from int/byte. */ if (addrmode == AD_RR && (0 #ifdef TARGET_LACKS_RR_STORE || (flag != s_content && mcmode != 2) #endif #ifdef TARGET_LACKS_RR_HALFWORD_STORE || (target_lacks_rr_halfword_store && flag != s_content && mcmode != 2 && mclength == 2) #endif #ifdef TARGET_LACKS_RR_FP_ACCESSES || mcmode == 2 #endif #ifdef TARGET_LACKS_RR_UNALIGNED_ACCESSES || (volatileorunaligned & IsUnaligned) #endif )) /* Deal with data types which cannot support register indexed address */ /* modes: convert back to something more simple. */ { #ifdef TARGET_HAS_SCALED_ADDRESSING /* If what we have is *(a+(b+k)), it's a good idea to rewrite as *((a+b)+k) */ /* Not really dependent on TARGET_HAS_SCALED_ADDRESSING in principle, */ /* but the code below would need to be slightly different if not (shift, */ /* down). */ if ((shift & SHIFT_RIGHT) == 0 && (h0_(x2) == s_plus || h0_(x2) == s_minus)) { Expr *x3 = arg1_(x2), *x4 = arg2_(x2); if (h0_(x3) == s_integer && h0_(x2) == s_plus) { Expr *t = x4; x4 = x3, x3 = t; } if (h0_(x4) == s_integer) { int32 n1; int32 d = (h0_(x2) == s_plus) ? down : down ^ J_NEGINDEX; n = intval_(x4); if (shift != 0) n = n << (shift & SHIFT_MASK); if (d) n = -n; n1 = cg_limit_displacement(n, ld_op, ld_align, mclength, flag); if (n1 == n) { addrmode = AD_RD; x1 = mk_expr2((down != 0 ? s_minus : s_plus), type_(x), x1, mk_expr2(s_leftshift, type_(x3), x3, mkintconst(te_int, shift, 0))); } } } #endif if (addrmode != AD_RD) { x1 = x; n = 0; /* just to make sure! */ addrmode = AD_RD; down = 0; } } { VRegnum r1,r2,r99; Binder *x1b = 0; /* The following test is probably in the wrong place. Note that the */ /* reduction to 4k boundaries above does not help if AD_VD then updates. */ /* Further, use of AD_VD mode probably does not help at all if the binder */ /* is a long way from SP or FP. */ /* @@@ For keeping IP sane, AM thinks we should mark IP as not-available */ /* if stack frame size (plus largest offset in AD_VD) exceeds single */ /* register addressability range. Views? */ if (addrmode == AD_RD && postinc == 0) { x1b = is_local_adcon(x1); /* *(&<local> + n) will use VD addressing mode */ if (x1b) addrmode = AD_VD; } if (addrmode != AD_VD) { if (addrmode == AD_RD) r1 = cg_expr(x1), r2 = GAP; /* is_same(x1,x2) is not worth testing for addresses */ else if (nastiness(x1) < nastiness(x2)) r2 = cg_expr(x2), r1 = cg_expr(x1); else r1 = cg_expr(x1), r2 = cg_expr(x2); } else r1 = r2 = GAP; /* To avoid dataflow anomalies */ r99 = (flag == s_assign) ? GAP : fgetregister(rsort); ld_op |= ld_align; if (volatileorunaligned & BaseIsWordAligned) ld_op |= J_BASEALIGN4; if (val != NULL) r = cg_expr(val); if (flag != s_assign) { int32 ld_op_su = ld_op | signedness; if (addrmode == AD_RD) emit(ld_op_su, r99, r1, n); else if (addrmode == AD_VD) emitvk(J_addvk(ld_op_su), r99, n, x1b); else emitshift(J_KTOR(ld_op_su) + down, r99, r1, r2, shift); } if (flag != s_content) { #ifdef TARGET_LACKS_HALFWORD_STORE /* It would be nice it we could make the back-end do this fabrication. */ /* We do not do so yet as it is unclear how the work register 'rx' could */ /* could be passed. */ if (target_lacks_halfword_store && (ld_op & J_TABLE_BITS) == J_LDRWK) { if (b != NULL && target_lsbytefirst && toplevel_alignment(b) >= alignof_int) { /* new experimental ARM J_ALIGNMENT code: */ ld_op = ld_op & ~J_ALIGNMENT | J_ALIGN4; goto elsecase; } else { int32 basealign = ld_op & J_BASEALIGN4; VRegnum rx = fgetregister(INTREG); int32 a_msb, a_lsb; if (addrmode == AD_RR) syserr(syserr_cg_indexword); if (target_lsbytefirst) { a_lsb = n; a_msb = n+1;} else { a_msb = n; a_lsb = n+1;} if (addrmode == AD_VD) emitvk(J_STRBVK|J_ALIGN1, r, a_lsb, x1b); else emit(J_STRBK|basealign|J_ALIGN1, r, r1, a_lsb); emit(J_SHRK+J_SIGNED, rx, r, 8); if (addrmode == AD_VD) emitvk(J_STRBVK|J_ALIGN1, rx, a_msb, x1b); else emit(J_STRBK|basealign|J_ALIGN1, rx, r1, a_msb); bfreeregister(rx); } } else elsecase: #endif { J_OPCODE st_op = J_LDtoST(ld_op); if (addrmode == AD_RD) emit(st_op, r, r1, n); else if (addrmode == AD_VD) emitvk(J_addvk(st_op), r, n, x1b); else emitshift(J_KTOR(st_op) + down, r, r1, r2, shift); } } /* Here there had been a s_displace within the indirection, and I do the */ /* update part of it. */ if (addrmode != AD_VD) { if (postinc != 0) { emit(J_ADDK, r1, r1, postinc); cg_storein(r1, NULL, x, s_assign); /* really a call to cg_var so far */ } bfreeregister(r1); } if (addrmode == AD_RR) bfreeregister(r2); if (flag == s_content) { if (volatileorunaligned & IsVolatile) emituse(r99, rsort); return r99; } if (flag == s_displace) { bfreeregister(r); if (volatileorunaligned & IsVolatile) emituse(r99, rsort); return r99; } return r; } } static VRegnum chroma_check(VRegnum v) /* This code goes to some trouble to see if there would be a real register */ /* available for use, even though register allocation happens later. This */ /* behaviour is so that I have something on which to base an heuristic */ /* relating to spilling things to the stack. */ { if (isintregtype_(vregsort(v))) { if (AddUsedReg(v) <= NTEMPREGS+NARGREGS+NVARREGS) return v; } else { usedfpregs = mkRegList(usedfpregs, v); #ifdef TARGET_SHARES_INTEGER_AND_FP_REGISTERS if ((nusedregs+=2) <= NTEMPREGS+NARGREGS+NVARREGS) return v; #else if (++nusedfpregs <= NFLTTEMPREGS+NFLTARGREGS+NFLTVARREGS) return v; #endif } /* The next line can happen either if: * 1. target.h gives NTEMPREGS=NARGREGS=NVARREGS=0 or * 2. an op like unsigned fix takes a number of temporaries larger * that the 4 allowed for below (this is delicate, see cg_expr1()). */ syserr(syserr_chroma); return v; } static VRegnum reserveregister(RegSort precision) { nreservedregs++; return vregister(precision); } static VRegnum getreservedreg(VRegnum r) { nreservedregs--; return chroma_check(r); } VRegnum fgetregister(RegSort rtype) { return chroma_check(vregister(rtype)); } void bfreeregister(VRegnum r) { if (r == GAP) return; if (generic_member((IPtr)r, (List *)usedregs)) { nusedregs--; usedregs = (RegList *)generic_ndelete((IPtr)r, (List *)usedregs); } else if (generic_member((IPtr)r, (List *)usedfpregs)) { #ifdef TARGET_SHARES_INTEGER_AND_FP_REGISTERS nusedregs -= 2; #else nusedfpregs--; #endif usedfpregs = (RegList *)generic_ndelete((IPtr)r, (List *)usedfpregs); } /* There used to be a syserr() trap here that checked that registers were */ /* discarded tidily - under the newer order of things it has gone away. */ } #define jop_iscmp_(op) (((op)&~Q_MASK)==J_CMPR || \ ((op)&~Q_MASK)==J_CMPFR || \ ((op)&~Q_MASK)==J_CMPDR) J_OPCODE Q_swap(J_OPCODE op) { /* If the bit patterns for the codes were more sensible then this could */ /* be cheaper. As it stands more cases coalesce than the code admits. */ switch (op & Q_MASK) { default: syserr(syserr_Q_swap, (long)op); case Q_AL: case Q_AL+Q_UBIT: case Q_UEQ: case Q_UNE: case Q_EQ: case Q_NE: return op; case Q_LT: case Q_GT: return op ^ (Q_LT ^ Q_GT); case Q_LE: case Q_GE: return op ^ (Q_LE ^ Q_GE); case Q_LO: case Q_HI: return op ^ (Q_LO ^ Q_HI); case Q_LS: case Q_HS: return op ^ (Q_LS ^ Q_HS); } } static Binder *is_local_adcon(Expr *a) { if (h0_(a) == s_addrof) { Expr *w = arg1_(a); if (h0_(w) == s_binder) { Binder *b = exb_(w); if ((bindstg_(b) & PRINCSTGBITS) == bitofstg_(s_auto)) return b; } } return 0; } static Expr *take_address(Expr *e) { if (h0_(e)==s_content) return arg1_(e); /* & * x ---> x */ else if (h0_(e)==s_cast) return take_address(arg1_(e)); /* ignore casts */ else return cg_optimise0(mk_expr1(s_addrof, ptrtotype_(typeofexpr(e)), e)); } /* This routine forges 'Binder's and so MUST be done in one place. */ /* It is arguable that is should be more opportunistic about re-using */ /* pre-existing adcons (e.g. use FLT ones for INTs on the ARM). */ static Expr *take_neat_address(Binder *b, RegSort rsort) /* b is a static or extdef binder */ { int32 off = bindaddr_(b); BindList *bb = datasegbinders; Binder *bb_elt = NULL; int32 base = 0; int32 loctype = binduses_(b) & u_loctype; J_OPCODE op = isintregtype_(rsort) ? J_LDRK+J_ALIGN4 : J_LDRFK+J_ALIGN4; int32 mink, maxk, span; mink = MinMemOffset(op); maxk = MaxMemOffset(op); /* The alignof_max is needed on machines like the i860. */ /* alignof_max acts like quantum in cg_limit_displacement. */ span = (maxk+1-mink) & -(int32)4 & -(int32)alignof_max; /* I find a binder for a variable at (&datasegment+nnn) where nnn is a */ /* neat number and the variable I want now is close to it. */ /* The following code should use xxx % span as in cg_limit_displacement. */ /* @@@ In fact this whole code probably should be a call to */ /* cg_limit_displacement with possibly a flag arg (they do same job!). */ /* @@@ more complication if LDRK_MAX == LDRK_MIN... */ if (span == 0) return take_address((Expr *)b); while (off > maxk) base += span, off -= span; while (off < mink) base -= span, off += span; /* Find a binder for the address involved... */ for (; bb != NULL; bb = bb->bindlistcdr) { bb_elt = bb->bindlistcar; if (bindaddr_(bb_elt) == base && (binduses_(bb_elt) & u_loctype) == loctype) break; } if (bb == NULL) { bb_elt = genglobinder(te_int); /* MUST be global */ bindaddr_(bb_elt) = base; binduses_(bb_elt) |= loctype; datasegbinders = (BindList *) global_cons2(SU_Other, datasegbinders, bb_elt); } if (off == 0) return take_address((Expr *)bb_elt); else return mk_expr2(s_plus, te_int, take_address((Expr *)bb_elt), mkintconst(te_int, off, 0)); } static VRegnum loadadcon(Binder *b) /* only used once from cg_addr() */ { VRegnum r = fgetregister(ADDRREG); J_OPCODE op = J_ADCON; if (!(bindstg_(b) & b_fnconst)) { if ((bindstg_(b) & b_undef) ? (alignof_toplevel_static >= 4 || alignoftype(bindtype_(b)) >= 4) : (bindaddr_(b) & 3) == 0) op = J_ADCON+J_BASEALIGN4; } emitbinder(op, r, b); return r; } static void emituse(VRegnum r, RegSort rsort) { if (isintregtype_(rsort)) emit(J_USE, r, GAP, 0); else if (rsort == FLTREG) emit(J_USEF, r, GAP, 0); else emit(J_USED, r, GAP, 0); } static VRegnum cg_var(VRegnum r, Binder *b, AEop flag, int32 mcmode, int32 mclength, bool address) { /* AM 22-10-86: New code amalgamating cg_var and (part of) cg_storein. */ /* flag is a member of {s_content,s_displace,s_assign}, see cg_stind(). */ /* fixes bugs in &-locals and extern value fetch. */ /* variables can be of several flavours : */ /* (a) local reference offset from sp */ /* (b) global reference offset from &datasegment */ /* (c) constant codegenerate associated value (done elsewhere) */ /* (d) external indirect access necessary */ /* local vars (even char/short) are treated as possible register vars */ /* (unless address taken - see below) and are treated as 4 byte values */ /* with the top bits set up so that widening is done on STORE not on */ /* load. This seems a good strategy. */ /* If they have address taken then this strategy does not work (consider */ /* signed short/char variables). Hence they MUST be put on the stack, */ /* and be properly accessed (this code fixed a bug in version 1.10)). */ /* A related bug from extern loads loading (possibly incorrect) top bits */ /* is fixed at the same time. */ /* Note that we must be extra careful with short/char vars whose address */ /* is taken on 370/68000 sex machines. */ /* note that 'b' didn't ought to be a struct/union value. */ RegSort rsort = mcmode!=2 ? INTREG : (mclength==4 ? FLTREG : DBLREG); VRegnum r99 = GAP; /* Never used but this saves dataflow anomaly */ bool volatileorunaligned = isvolatile_type(bindtype_(b)) | (isunaligned_type(bindtype_(b)) << 1); #ifdef ADDRESS_REG_STUFF if (rsort==INTREG && address) rsort = ADDRREG; #else IGNORE(address); #endif switch (bindstg_(b) & PRINCSTGBITS) { default: syserr(syserr_cg_stgclass, (long)bindstg_(b)); case b_globalregvar: case bitofstg_(s_auto): if (!((bindstg_(b) & (b_addrof|b_spilt)) && mclength < 4)) { /* We use LDRxV/STRxV for variables either whose address is */ /* not taken or which occupy 1 or 2 whole stack word(s). */ /* Avoid this for short/char &-taken locals, consider */ /* extern short x=0; *(&x+0) = -1; f(x); */ /* The indirect assignment to x cannot affect the top bits */ /* (e.g. maybe in procedure) and so LDRV cannot be used to */ /* load a pre-(sign/zero) padded version of x as it would be */ /* if x is in a register. Also mutter about machine sex. */ if (flag != s_assign) { r99 = fgetregister(rsort); emitbinder(floatyop(rsort, J_LDRV|J_ALIGN4V, J_LDRFV|J_ALIGN4V, J_LDRDV|J_ALIGN8), r99, b); } /* N.B. local integer variables are ALWAYS stored in a 32-bit word even */ /* if only 8 or 16 bits is needed. Hence STRV does not need length data */ if (flag != s_content) emitbinder(floatyop(rsort, J_STRV|J_ALIGN4V, J_STRFV|J_ALIGN4V, J_STRDV|J_ALIGN8), r, b); break; } /* else drop through to use J_ADCONV via s_extern case. */ /* This is certainly NOT optimal code, but better than bugs. */ /* The previous code here was buggy, but on the other hand, I like the * idea of using STRV/STRK (32 bits) for storing simple short/char * vars made feasible by the padding performed on simple variables by * vargen.c. Of course this is not possible in general in cg_stind() * because of array elements. Worry a bit too about oddsex machines. */ jolly: r = cg_stind(r, NULL, take_address((Expr *)b), flag, b, mcmode, mclength, NO, volatileorunaligned); if (flag == s_content) return r; flag = s_assign; break; case bitofstg_(s_extern): if (bindstg_(b) & b_undef) goto jolly; case bitofstg_(s_static): if ((binduses_(b) & u_bss) && bindaddr_(b) == BINDADDR_UNSET) goto jolly; /* v1 -> *(&datasegment + nnn) when v1 is a static */ /* See comment for s_extern above for possible improvement too. */ r = cg_stind(r, NULL, take_neat_address(b, rsort), flag, b, mcmode, mclength, NO, volatileorunaligned); if (flag == s_content) return r; flag = s_assign; break; } if (flag == s_content) { if (volatileorunaligned & IsVolatile) emituse(r99, rsort); return r99; } if (flag != s_displace && !(volatileorunaligned & IsVolatile)) { cgstate.juststored.var = b; cgstate.juststored.reg = r; } if (flag == s_displace) { bfreeregister(r); if (volatileorunaligned & IsVolatile) emituse(r99, rsort); return r99; } return r; } VRegnum cg_storein(VRegnum r, Expr *val, Expr *e, AEop flag) /* if flag is s_displace return old value, else flag is s_assign and return stored value (already coerced). */ { int32 mcrep = mcrepofexpr(e); int32 mcmode = mcrep >> MCR_SORT_SHIFT; int32 mclength = mcrep & MCR_SIZE_MASK; bool volatileorunaligned = isvolatile_expr(e) | (isunaligned_expr(e) << 1); VRegnum res = GAP; switch (h0_(e)) { case s_binder: if (val != NULL) r = cg_expr(val); res = cg_var(r, exb_(e), flag, mcmode, mclength, 0); break; case s_content4: volatileorunaligned |= BaseIsWordAligned; case s_content: e = arg1_(e); if (memory_access_checks) { Expr *fname = mclength==1 ? sim.writecheck1 : mclength==2 ? sim.writecheck2 : sim.writecheck4; e = mk_expr2(s_fnap, typeofexpr(e), fname, mkArgList1(e)); } res = cg_stind(r, val, e, flag, NULL, mcmode, mclength, NO, volatileorunaligned); break; /* The following case is caused by s.*m = 42; where s is a one-word */ /* struct. Optimise1() changes to (m, s) = 42; !!! */ case s_comma: cg_exprvoid(arg1_(e)); return cg_storein(r, val, arg2_(e), flag); /* The following case is caused by 's.m = 42; where s is a one-word */ /* struct. The problem is that optimise0 changes s.m to (typeof_m)s. */ /* The solution below is rather nasty and doesn't even try to fix the */ /* way that { (char)a = 1; } warns and then syserrs in pcc mode! */ case s_cast: if ((mcrep & ~0x01000000) == (mcrepofexpr(arg1_(e)) & ~0x01000000)) return cg_storein(r, val, arg1_(e), flag); /* drop through */ default: syserr(syserr_cg_storein, (long)h0_(e)); } if (volatileorunaligned & IsVolatile) emit(J_VSTORE, GAP, GAP, 0); return res; } static VRegnum cg_addr(Expr *sv, bool valneeded) { VRegnum r; Expr *e; for (;;) switch (h0_(sv)) { case s_comma: /* can occur in structure manipulation code */ cg_exprvoid(arg1_(sv)); sv = arg2_(sv); continue; case s_cast: /* & ((cast)x) ---> & x */ sv = arg1_(sv); continue; case s_cond: /* & (p ? x : y) ---> p ? (&x) : (&y) */ arg2_(sv) = take_address(arg2_(sv)); arg3_(sv) = take_address(arg3_(sv)); type_(sv) = typeofexpr(arg2_(sv)); return cg_expr1(sv, valneeded); case s_assign: /* this can happen with structure assignments - it is essentially an */ /* artefect of transformations made here in the codegenerator but seems */ /* fairly convenient. */ /* In particular this is used in the case of */ /* (a = b) . c */ /* which in effect turns into */ /* ((a = b), a . c) */ /* but with need for special care if a is an expression that might have */ /* side effects when being evaluated. */ e = arg1_(sv); switch (h0_(e)) { default: syserr(syserr_cg_addr); case s_content: case s_content4: { TypeExpr *t = typeofexpr(arg1_(e)); Binder *gen = gentempbinder(t); /* & (*p=q) */ /* turns into */ /* (let g; g = p, *g = q, g) */ /* where the temp var is to ensure that p gets evaluated just once. */ sv = mk_exprlet(s_let, /* @@@ The semantic analyser should export such a function ... */ t, mkSynBindList(0, gen), mk_expr2(s_comma, t, mk_expr2(s_assign, t, (Expr *)gen, arg1_(e)), mk_expr2(s_comma, t, mk_expr2(s_assign, typeofexpr(arg2_(sv)), mk_expr1(h0_(e), t, (Expr *)gen), arg2_(sv)), (Expr *)gen))); if (debugging(DEBUG_CG)) { eprintf("& p = q ---> "); pr_expr_nl(sv); } } return cg_expr1(sv, valneeded); case s_binder: cg_exprvoid(sv); /* get the assignment done, voiding the result */ sv = e; /* then take address of the lhs variable */ } /* drop through */ case s_binder: { Binder *b = exb_(sv); switch (bindstg_(b) & PRINCSTGBITS) { default: syserr(syserr_cg_stgclass, (long)bindstg_(b)); case bitofstg_(s_auto): if (valneeded) { emitbinder(J_ADCONV, r = fgetregister(ADDRREG), b); return (r); } else return GAP; case bitofstg_(s_static): case bitofstg_(s_extern): if (valneeded) return loadadcon(b); else return GAP; } } case s_int64con: if (!valneeded) return GAP; emitint64(J_ADCONLL, r = fgetregister(ADDRREG), GAP, exi64_(sv)); return r; case s_floatcon: { FloatCon *f = exf_(sv); if (is_float_(f->floatlen)) { if (!valneeded) return GAP; emitfloat(J_ADCONF, r = fgetregister(ADDRREG), GAP, f); return r; } else if (is_anydouble_(f->floatlen)) { if (!valneeded) return GAP; emitfloat(J_ADCOND, r = fgetregister(ADDRREG), GAP, f); return r; } } default: syserr(syserr_cg_addr1, (long)h0_(sv)); } } #if defined TARGET_HAS_SCALED_OPS || defined TARGET_HAS_SCALED_ADD static VRegnum cg_opshift(J_OPCODE jop, Expr *arg1, Expr *arg2, int32 shift) /* * Note that the scheme we have here can only cope with constant scale * quantities - the ARM can support dynamic shift-amounts, as in * ORR r1, r2, r3, LSL r4 * but same will not fit in with the limitations os Jopcode formats. */ { bool same = 0; VRegnum r, r2, targetreg; if (is_same(arg1,arg2)) (same = 1, r = r2 = cg_expr(arg1)); else if (nastiness(arg1) < nastiness(arg2)) r2 = cg_expr(arg2), r = cg_expr(arg1); else r = cg_expr(arg1), r2 = cg_expr(arg2); targetreg = (jop_iscmp_(jop) ? GAP : fgetregister(INTREG)); emitshift(jop, targetreg, r, r2, shift); bfreeregister(r); if (!same) bfreeregister(r2); return targetreg; } #endif /* TARGET_HAS_SCALED_OPS */ static void verify_integer(Expr *x) /* @@@ probably overcautious and underused nowadays. */ { switch(mcrepofexpr(x)) { case 0x00000001: /* signed integers are OK */ case 0x00000002: case 0x00000004: case 0x00000008: case 0x01000001: /* unsigned integers are OK */ case 0x01000002: case 0x01000004: case 0x01000008: case 0x03000001: /* structures/unions up to 4 bytes long are OK */ case 0x03000002: case 0x03000003: case 0x03000004: case 0x04000001: /* plain, short integers are OK */ case 0x04000002: return; default: syserr(syserr_integer_expected); } } static VRegnum cg_binary_or_fn(J_OPCODE op, TypeExpr *type, Expr *fname, Expr *a1, Expr *a2, bool commutesp) { /* commutesp is used to control selection of special cases on integer */ /* args as well as commutativity. */ /* This code is only ever activated on integerlike things */ if (commutesp && nastiness(a1)<nastiness(a2)) { Expr *t = a1; a1 = a2; a2 = t; } #if defined TARGET_HAS_MULTIPLY || defined TARGET_IS_SPARC if (commutesp && integer_constant(a2)) /* really just allow MULK */ return cg_binary(op, a1, a2, commutesp, INTREG); #endif /* Fortunately I can somewhat fudge the creation of a function call node */ /* since it will only be looked at be this codegenerator and in the */ /* restricted context of function calls only little bits of type info */ /* are looked at. */ /* N.B. in this version I make (p/q) turn into divide(q,p) since that */ /* seems to make register usage behave better. This is an incompatible */ /* change from some earlier versions of this compiler - BEWARE */ /* Detection of special case of divide, remainder by 10 moved to cse.c */ a1 = mk_expr2(s_fnap, type, fname, mkArgList2(a2, a1)); return cg_expr(a1); } static VRegnum cg_binary_1(J_OPCODE op, Expr *a1, Expr *a2, bool commutesp, J_OPCODE *condP, RegSort fpp) { /* This routine has been grossly uglified by CMP's having conds */ J_OPCODE cond = condP==0 ? 0 : *condP; if (is_same(a1, a2)) { VRegnum r, targetreg; r = cg_expr(a1); /* Do this BEFORE allocating targetreg */ targetreg = jop_iscmp_(op) ? GAP : fgetregister(fpp); emitreg(op+cond, targetreg, r, r); bfreeregister(r); return(targetreg); } /* This first swap is entirely looking for constant arg cases, */ /* possible evaluation order swap comes later. */ if (commutesp && nastiness(a1)<nastiness(a2)) { Expr *t = a1; a1 = a2; a2 = t; if (condP) *condP = cond = Q_swap(cond); } #ifdef TARGET_HAS_SCALED_ADD if (op == J_ADDR || op == J_SUBR) { if (op == J_ADDR && is_shifted(a2, 0, 0, 0)) return cg_opshift(op+cond, a1, shift_operand(a2), shift_amount(a2)); if (is_shifted(a1, 0, 0, 0)) { if (condP) *condP = cond = Q_swap(cond); return cg_opshift((op==J_SUBR ? J_RSBR : op) + cond, a2, shift_operand(a1), shift_amount(a1)); } } #endif /* TARGET_HAS_SCALED_ADD */ { VRegnum targetreg; #ifdef TARGET_HAS_SCALED_OPS /* The following code has come here as the best place for it. */ /* One might wonder whether the test for is_shifted or s_integer should */ /* come first. Observe that either is correct. Consider: */ /* if ((x>>7) == 27) ... */ /* We can either do MOVK r,27; CMPR r, x LSR 7 */ /* or MOVR r, x LSR 7; CMPK r, 27 */ /* The former is preferable if loop invariants are optimised. */ /* The former is what we do here... */ if (op == J_ADDR || op == J_SUBR || op == J_ANDR || op == J_ORRR || op == J_EORR || (op & ~Q_MASK) == J_CMPR) { if (is_shifted(a2, 0, 0, 0)) return cg_opshift(op+cond, a1, shift_operand(a2), shift_amount(a2)); if (is_shifted(a1, 0, 0, 0)) { if (condP) *condP = cond = Q_swap(cond); return cg_opshift((op==J_SUBR ? J_RSBR : op) + cond, a2, shift_operand(a1), shift_amount(a1)); } } #endif /* TARGET_HAS_SCALED_OPS */ if (jop_canRTOK(op) && integer_constant(a2)) /* floating case below */ { int32 n = result2; VRegnum r1 = cg_expr(a1); /* Compare instructions do not need a real destination. */ targetreg = jop_iscmp_(op) ? GAP : fgetregister(fpp); #define jop_isregshift_(op) \ (((op) & ~(J_SIGNED+J_UNSIGNED)) == J_SHLR || \ ((op) & ~(J_SIGNED+J_UNSIGNED)) == J_SHRR) if (jop_isregshift_(op)) { if (n == 0) /* this case should not currently happen */ { bfreeregister(targetreg); /* i.e. don't use reg */ return r1; } if ((0xffffffff & (unsigned32)n) >= (unsigned32)32) { /* The following optimisations of errors are overzealous (warned in sem.c) */ /* but ensure compatible behaviour of constants and expressions. */ VRegnum r2 = fgetregister(INTREG); #ifdef TARGET_LACKS_RIGHTSHIFT if ((op & ~(J_SIGNED+J_UNSIGNED)) == J_SHRR) op ^= (J_SHRR^J_SHLR), n = -n; #endif /* TARGET_LACKS_RIGHTSHIFT */ emit(J_MOVK, r2, GAP, n); emitreg(op+cond, targetreg, r1, r2); bfreeregister(r2); op = J_NOOP; } } /* @@@ do similar things for div/rem by 0? */ if (op != J_NOOP) emit(J_RTOK(op+cond), targetreg, r1, n); bfreeregister(r1); return targetreg; } #ifdef TARGET_HAS_FP_LITERALS if (h0_(a2) == s_floatcon && fpliteral(exf_(a2), J_RTOK(op))) { VRegnum r1 = cg_expr(a1); targetreg = jop_iscmp_(op) ? GAP : fgetregister(fpp); /* The next line is just emitfloat because it is illegal to have FP_LITERALS * and also needing the literals in store. */ emitfloat(J_RTOK(op+cond), targetreg, r1, exf_(a2)); bfreeregister(r1); return targetreg; } #endif /* TARGET_HAS_FP_LITERALS */ { VRegnum r1, r2; if (nastiness(a1) < nastiness(a2)) r2 = cg_expr(a2), (!isintregtype_(fpp) ? sparefpregs++ : spareregs++), r1 = cg_expr(a1), /* Do this BEFORE allocating targetreg */ (!isintregtype_(fpp) ? sparefpregs-- : spareregs--); else r1 = cg_expr(a1), (!isintregtype_(fpp) ? sparefpregs++ : spareregs++), r2 = cg_expr(a2), /* Do this BEFORE allocating targetreg */ (!isintregtype_(fpp) ? sparefpregs-- : spareregs--); targetreg = jop_iscmp_(op) ? GAP : fgetregister(fpp); emitreg(op+cond, targetreg, r1, r2); bfreeregister(r1); bfreeregister(r2); } return(targetreg); } } static VRegnum cg_binary(J_OPCODE op, Expr *a1, Expr *a2, bool commutesp, RegSort fpp) { return cg_binary_1(op, a1, a2, commutesp, 0, fpp); } static void cg_condjump(J_OPCODE op, Expr *a1, Expr *a2, RegSort rsort, J_OPCODE cond, LabelNumber *dest) { bfreeregister(cg_binary_1(op, a1, a2, 1, &cond, rsort)); emitbranch(J_B+cond, dest); } static void cg_count(FileLine fl) { #ifdef TARGET_HAS_PROFILE if (full_profile_option && fl.f != 0) emitfl(J_COUNT, fl); #else IGNORE(fl); #endif } static void cg_test(Expr *x, bool branchtrue, LabelNumber *dest) { /* I wonder if the count-point that was here was really useful? ... cg_count(cmdfileline_(cg_current_cmd)); ... end of commented out code */ cg_test1(x, branchtrue, dest); } static bool at_least_once(Expr *init, Expr *endtest) { /* This should return true if the boolean formula endtest is certain to */ /* return false if obeyed straight after the execution of init. This is */ /* used to map 'for' loops onto 'do .. while' ones where the test is a */ /* little cheaper. */ /* The cases I recognize at present are where the initializer is an */ /* expression (possibly with commas) ending with a form 'var=int' for */ /* a simple variable, and the end test is an expression 'var op int' or */ /* 'int op var' for the same variable and a relational operator. Then */ /* by comparing the two integers I can see if the endtest will fail on */ /* entry to the loop & if so move it to the end. It might be worth */ /* extending this code to identify the forms 'var', 'var++', 'var--', */ /* '++var' and '--var' in the end test position, depending somewhat on */ /* the perception we have of what sorts of loop are commonly written. */ int32 i1, i2; int32 unsignedp; Expr *var, *x1, *x2; AEop tst; if (endtest==0) return(1); /* no endtest => this does not matter */ if (init==0) return(0); /* no init for => I can't tell */ while (h0_(init) == s_comma) init = arg2_(init); while (h0_(init) == s_cast) init = arg1_(init); if (!(h0_(init)==s_assign)) return(0); var = arg1_(init); if (!(h0_(var)==s_binder)) return(0); i1 = mcrepofexpr(var); if (i1!=4 && i1!=0x01000004) return(0); /* int or unsigned int OK */ init = arg2_(init); if (!integer_constant(init)) return(0); i1 = result2; /* Now I know that the initializer is 'var = i1' */ if (!isrelational_(tst = h0_(endtest))) return(0); x1 = arg1_(endtest); x2 = arg2_(endtest); { Expr *v = 0; if (integer_constant(x2) && (x1 == var || (h0_(x1) == s_cast && arg1_(x1) == var))) v = x1, i2 = result2; else if (integer_constant(x1) && (x2 == var || (h0_(x2) == s_cast && arg1_(x2) == var))) v = x2, i2 = i1, i1=result2; else return 0; if (h0_(v) == s_cast) { /* ok if both types are effectively the same, or if they are the same width and one is signed and the other unsigned */ int32 repdiff = mcrepofexpr(var) ^ mcrepofexpr(v); if ((repdiff & MCR_SIZE_MASK) != 0 || ((repdiff >> MCR_SORT_SHIFT) & ~1) != 0) return 0; } unsignedp = unsigned_expression_(v); } /* NB the tests here are done in signed or unsigned mode */ /* depending on the character of the variable v. */ { unsigned32 i1u = i1 & 0xffffffff, i2u = i2 & 0xffffffff; switch (tst) { default: return(0); case s_equalequal: return(i1==i2); case s_notequal: return(i1!=i2); case s_greater: if (unsignedp) return (i1u>i2u); else return(i1>i2); case s_greaterequal: if (unsignedp) return (i1u>=i2u); return(i1>=i2); case s_less: if (unsignedp) return (i1u<i2u); return(i1<i2); case s_lessequal: if (unsignedp) return (i1u<=i2u); return(i1<=i2); } } } static int32 alignofpointee(Expr *x, int32 knownalign) { int32 a1 = 1, a2 = 1; /* Compute maximum of type-based alignment and layout-based alignment. */ /* Maybe it would help if previous stages could have done this. */ /* Note that it is better that optimise() has removed any possible */ /* outer (e.g. arg) cast to (void *) from a more aligned pointer type. */ TypeExpr *t = princtype(typeofexpr(x)); if (h0_(t) == t_content || h0_(t) == t_ref) { TypeExpr *tt = typearg_(t); if (isunaligned_type(tt)) return 1; /* the (amusingly named) test on next line seems overkeen... */ /* ... but it protects for memcpy applied to (void *). */ if (sizeoftypelegal(tt)) a1 = alignoftype(tt); } if (isstring_(h0_(x))) a2 = alignof_literal; else if (h0_(x) == s_addrof && h0_(arg1_(x)) == s_binder) a2 = toplevel_alignment(exb_(arg1_(x))); if (a1 > knownalign) knownalign = a1; if (a2 > knownalign) knownalign = a2; return knownalign; } static int32 sizeofpointee(Expr *x, int32 *padding) { /* @@@ Beware: sizeofpointee() is now a constraint on how strings */ /* are stored (and even shared!) in memory. Hence more of the string */ /* stuff which some back-ends (including ARM) manage needs to move to */ /* MIP so we can see that it is consistent. */ int32 len = 0, pad = 0; if (h0_(x) == s_string) { len = stringlength(exs_(x)->strseg)+1; /* isstring_()? */ pad = padsize(len, alignof_literal) - len; } else if (h0_(x) == s_addrof) { x = arg1_(x); if (h0_(x) == s_binder && sizeoftypelegal(bindtype_(exb_(x)))) { len = sizeoftype(bindtype_(exb_(x))); pad = padsize(len, toplevel_alignment(exb_(x))) - len; } } *padding = pad; return len; } #define symisctor(s) (LanguageIsCPlusPlus ? strncmp(symname_(s), "__ct", 4) == 0 : 0) static void emitcopy(Icode *ic) { if (ic->op == J_SETSPENV) { active_binders = ic->r2.bl; emitsetsp(ic->op, ic->r3.bl);; } else emitic(ic); } static Inline_ArgSubstList *New_Inline_ArgSubstList(Inline_ArgSubstSort sort) { Inline_ArgSubstList *sl = (Inline_ArgSubstList *)SynAlloc(sizeof(Inline_ArgSubstList)); sl->notnull = NO; sl->sort = sort; return sl; } static VRegnum TryInlineRestore( Binder *fname, ExprList *args, Expr *structresult, RegSort rsort, bool valneeded) { VRegnum resultr = GAP; Inline_RestoreControl rc; BindList *oactive = active_binders; Inline_SavedFn px; Inline_SavedFn *p = Inline_FindFn(fname); VRegnum structresultp = GAP; Binder *structresultbinder = NULL; bool resultisstruct = NO; int32 narg = length((List *)args); if (structresult != NULL && !returnsstructinregs_t(bindtype_(fname))) narg++; if (p == NULL || narg != length((List *)p->fndetails.argbindlist)) return NOT_OPEN_COMPILABLE; px = *p; rc.exitlabel = nextlabel(); rc.env = oactive; rc.argreplace = NULL; { TypeExpr *fntype = bindtype_(fname); TypeExpr *restype = typearg_(fntype); if (returnsstructinregs_t(fntype) && (mcrepoftype(restype) & MCR_SORT_MASK) == MCR_SORT_STRUCT) { /* Note that returnsstructinregs() but structresult==NULL is */ /* possible: it occurs precisely when the function being called */ /* here provides the return value for the calling function. */ /* (also, in this case the call is s_fnapstructvoid rather than */ /* s_fnapstruct). But we mustn't let Inline_Restore think the */ /* call is voided in this case, or it will kill instructions */ /* loading the result */ VRegnum r = V_resultreg(INTREG); unsigned i, n = (unsigned)sizeoftype(restype) / MEMCPYQUANTUM; resultisstruct = YES; for (i = 0; i < n; i++) { rc.resultregs[i] = r; rc.newresultregs[i] = fgetregister(INTREG); r++; } rc.nresults = n; if (structresult != NULL) { if (h0_(structresult) == s_addrof && h0_(arg1_(structresult)) == s_binder) structresultbinder = exb_(arg1_(structresult)); else structresultp = cg_expr(structresult); } } else if (isvoidtype(restype)) { rc.nresults = 0; } else { rc.nresults = 1; rc.resultregs[0] = V_resultreg(rsort); if (!valneeded) rc.newresultregs[0] = GAP; else resultr = rc.newresultregs[0] = fgetregister(rsort); } } /* Arrange to do inline substitution for suitable arguments, rather than * assignment to an argument binder. CSE can achieve the same effect, but * doing it here is a significant time saver for both CSE and regalloc; * also, by direct sustitution of &arg into *par, we can hope to remove * the spurious address-taken attribute from arg and improve generated * code significantly: this can't be done after CSE (address-taken-ness * has then already been used to determine aliasing). */ if (!(var_cc_private_flags & 1048576L)) { Inline_ArgSubstList **slp = &rc.argreplace; ExprList *a = args; Inline_ArgBinderList *argl; for (argl = px.args; argl != NULL; argl = cdr_(argl), a = cdr_(a)) { Binder *b = argl->globarg; Expr *ex = exprcar_(a); Expr *rest = NULL; bool byreference = NO; Inline_ArgSubstList *sl = NULL; if (h0_(ex) == s_comma) { rest = arg1_(ex); ex = arg2_(ex); } if (h0_(ex) == s_addrof) { byreference = YES; ex = arg1_(ex); } if (!byreference && h0_(ex) == s_integer) { sl = New_Inline_ArgSubstList(T_Int); if (argl->narrowtype != NULL) b = argl->globnarrowarg; } else if (argl->narrowtype != NULL) { if ( h0_(ex) == s_binder && !byreference && !(bindstg_(exb_(ex)) & b_addrof) && (bindstg_(exb_(ex)) & bitofstg_(s_auto)) && mcrepofexpr(ex) == mcrepoftype(argl->narrowtype)) { sl = New_Inline_ArgSubstList(T_Binder); b = argl->globnarrowarg; } } else if (h0_(ex) == s_binder /* a variable is only substitutable if it's not updated in the function to be inlined. Local to the calling function and not also passed by reference is sufficient to ensure this. The latter is checked later. */ && !( (bindstg_(exb_(ex)) & b_addrof) && sizeoftypelegal(bindtype_(exb_(ex))) && (mcrepofexpr(ex) & MCR_SIZE_MASK) < sizeof_int) && (byreference || (bindstg_(exb_(ex)) & bitofstg_(s_auto)))) { if (!byreference) { if (bindstg_(exb_(ex)) & b_addrof) continue; sl = New_Inline_ArgSubstList(T_Binder); if (symisctor(currentfunction.symstr) && symisctor(bindsym_(fname)) && exb_(ex) == currentfunction.argbindlist->bindlistcar) sl->notnull = YES; } else if (!(bindstg_(exb_(ex)) & bitofstg_(s_auto))) { sl = New_Inline_ArgSubstList(T_Adcon); if (!(bindstg_(exb_(ex)) & bitofstg_(s_weak))) sl->notnull = YES; } else { int32 rep = mcrepofexpr(ex); int32 sort = rep & MCR_SORT_MASK, len = rep & MCR_SIZE_MASK; sl = New_Inline_ArgSubstList(T_AdconV); sl->size = sort == MCR_SORT_FLOATING ? (len == 4 ? MEM_F : MEM_D) : sort < MCR_SORT_FLOATING ? (len == 1 ? MEM_B : len == 2 ? MEM_W : len == 4 ? MEM_I : MEM_LL) : MEM_NONE; sl->notnull = YES; } } else if (h0_(ex) == s_plus && h0_(arg1_(ex)) == s_binder && h0_(arg2_(ex)) == s_integer && symisctor(currentfunction.symstr) && symisctor(bindsym_(fname)) && exb_(arg1_(ex)) == currentfunction.argbindlist->bindlistcar) { sl = New_Inline_ArgSubstList(T_Plus); sl->notnull = YES; } if (sl != NULL) { cdr_(sl) = NULL; sl->arg = b; sl->replacement.ex = ex; sl->refsleft = NO; sl->rest = rest; *slp = sl; slp = &cdr_(sl); } } } if (debugging(DEBUG_CG)) cc_msg("\ninlined $b\n", fname); Inline_Restore(&px, &rc); { typedef struct ArgValList ArgValList; struct ArgValList { ArgValList *cdr; Expr *init; }; ArgValList *argvals = NULL; Inline_ArgSubstList *sl = rc.argreplace; Inline_ArgBinderList *argl = px.args; BindList *bl = px.fndetails.argbindlist; ExprList *a = args; for (; argl != NULL; argl = cdr_(argl), a = cdr_(a)) { Expr *ex = exprcar_(a); TypeExpr *t; Binder *bglob = argl->narrowtype == NULL || argl->globnarrowarg == NULL ? argl->globarg : argl->globnarrowarg; if (sl != NULL && sl->arg == bglob) { bool refsleft = sl->refsleft; Expr *rest = sl->rest; sl = cdr_(sl); if (!refsleft) { if (rest != NULL) argvals = (ArgValList *)syn_list2(argvals, rest); continue; } } { Binder *b = bl->bindlistcar; if (bindsym_(b) != bindsym_(bglob)) syserr("Inline_Restore: argument substitution confused"); if (argl->globnarrowarg != NULL) { b = argl->instantiatednarrowarg; t = argl->narrowtype; /*/* this optimise0 is questionable -- Harry will improve */ ex = optimise0(mkcast(s_assign, ex, t)); } else if (h0_(ex) != s_string) t = typeofexpr(ex); else t = mk_typeexpr1(s_content, primtype_(bitoftype_(s_char)), 0); bindtype_(b) = t; argvals = (ArgValList *) syn_list2(argvals, mk_expr2(s_assign, t, (Expr *)b, ex)); bl = bl->bindlistcdr; } } emitsetsp(J_SETSPENV, rc.env); if (px.ix_narrowspenv >= 0) { BlockHead *insert = blkdown_(px.top_block); emitsetsp(J_SETSPENV, blkcode_(insert)[px.ix_narrowspenv].r3.bl); } argvals = (ArgValList *)dreverse((List *)argvals); for (; argvals != NULL; argvals = (ArgValList *)discard2(argvals)) cg_exprvoid(argvals->init); } local_binders = (BindList *)nconc((List *)local_binders, (List *)px.var_binders); regvar_binders = (BindList *)nconc((List *)regvar_binders, (List *)px.reg_binders); { /* We now try to merge both the first and last blocks of an inlined * function with blocks from the caller: if the inlined function has just * one block, it can be inlined without introducing any extra blocks * (we _have_ created the labels for the blocks we won't be introducing, * which will make the labels for real blocks sparser. Let's hope it * doesn't matter. * (firstblockmergeable and lastblockmergeable tell us whether we can) */ BlockHead *insert = blkdown_(px.top_block); BlockHead *end_insert = px.bottom_block; if (insert == end_insert || (px.firstblockmergeable && blklab_(blkdown_(insert)) == blknext_(insert) && !(blkflags_(insert) & BLKSWITCH))) { Icode *ic = blkcode_(insert); uint32 i = 0, len = blklength_(insert); uint8 *ignoremap = px.firstblockignore; for (; i < len; i++, ic++) if (ignoremap == NULL) emitcopy(ic); else { /* The narrowing store into an argument binder is turned into * a load, to guard against cg's desire to reuse a register * just stored rather than to load from the place just stored * to. */ if ((ignoremap[(i+px.ix_max)/8] & regbit((i+px.ix_max)%8)) && stores_r1(ic->op)) { ic->op = J_XtoY(ic->op, J_STRK, J_LDRK); emitcopy(ic); } else if (!(ignoremap[i/8] & regbit(i%8))) emitcopy(ic); } if (blkflags_(insert) & BLK2EXIT) emitbranch(J_B+(blkflags_(insert) & Q_MASK), blknext1_(insert)); if (insert == end_insert) insert = NULL; /* just one block to be inlined */ else insert = blkdown_(insert); } if (insert != NULL) { BlockHead *insert_after = bottom_block; BlockHead *insert_before; BlockHead *endblock = px.lastblockmergeable ? end_insert : NULL; emitbranch(J_B, blklab_(insert)); if (debugging(DEBUG_CG)) { BlockHead *b = insert; for (; b != endblock; b = blkdown_(b)) flowgraf_printblock(b, NO); } if (px.lastblockmergeable) { Icode *ic = blkcode_(endblock); unsigned32 i = 0, len = blklength_(endblock); active_binders = blkstack_(end_insert); start_new_basic_block(blklab_(endblock)); for (; i < len; i++, ic++) emitcopy(ic); if (insert == end_insert) end_insert = blkup_(bottom_block); else end_insert = blkup_(endblock); } else { active_binders = blkstack_(blkdown_(px.top_block)); start_new_basic_block(rc.exitlabel); } insert_before = bottom_block; /* (the new block just started) */ blkdown_(insert_after) = insert; blkup_(insert) = insert_after; blkdown_(end_insert) = insert_before; blkup_(insert_before) = end_insert; } } emitsetsp(J_SETSPENV, oactive); if (debugging(DEBUG_CG)) cc_msg("\nend inlined $b\n", fname); if (structresult != NULL) { int32 i; if (structresultbinder != NULL && !(bindstg_(structresultbinder) & bitofstg_(s_auto))) structresultp = cg_expr(structresult); for (i = 0; i < rc.nresults; i++) { VRegnum r = rc.newresultregs[i]; if (structresultp != GAP) emit(J_memcpy(J_STRK|J_ALIGN4), r, structresultp, i * MEMCPYQUANTUM); else emitvk(J_memcpy(J_STRVK|J_ALIGN4), r, i * MEMCPYQUANTUM, structresultbinder); bfreeregister(r); } bfreeregister(structresultp); } else if (resultisstruct) { /* but structresult == NULL : move renamed result registers */ /* to result registers */ int32 i; for (i = 0; i < rc.nresults; i++) { VRegnum r = rc.newresultregs[i]; emitreg(J_MOVR, rc.resultregs[i], GAP, r); bfreeregister(r); } } return resultr; } #define ptrtofn_(f) (mk_expr1(s_addrof, ptrtotype_(typeofexpr(f)), (f))) static int32 LengthOfString(String *p) { int32 n = 0; StringSegList *s = p->strseg; for ( ; s != NULL ; s = s->strsegcdr) { size_t l = (size_t)s->strseglen; if (l > 0) { size_t l1 = strlen(s->strsegbase); if (l1 < l) { n += l1; break; } n += l; } } return n; } static VRegnum open_compilable(Expr **xp, RegSort rsort, bool valneeded) { Expr *x = *xp; Expr *fname = arg1_(x); Expr *a1 = NULL, *a2 = NULL, *a3 = NULL; int32 narg = 0, n; ExprList *a = exprfnargs_(x); if (h0_(fname) != s_addrof) return NOT_OPEN_COMPILABLE; fname = arg1_(fname); if (fname == NULL || h0_(fname) != s_binder) return NOT_OPEN_COMPILABLE; /* Only consider this call if the function is a direct function name */ if (a != NULL) { a1 = exprcar_(a); narg++; a = cdr_(a); if (a != NULL) { a2 = exprcar_(a); narg++; a = cdr_(a); if (a != NULL) { a3 = exprcar_(a); narg++; a = cdr_(a); if (a != NULL) narg++; } } } #ifdef TARGET_INLINES_MONADS /* distinctly special case-ish */ if (narg == 1) { int32 i = target_inlinable(exb_(fname), narg); if (i) { VRegnum r1 = cg_expr(a1); VRegnum targetreg = fgetregister(rsort); emit(floatyop(rsort, J_INLINE1, J_INLINE1F, J_INLINE1D), targetreg, r1, i); bfreeregister(r1); return targetreg; } } #endif #ifdef TARGET_HAS_DIVREM_FUNCTION /* The idea here is that if we are doing both divide and remainder, CSE can eliminate one call. To do this, it and regalloc need to understand that div & udiv return two results. */ /* Should we invent a V_resultreg2 macro for R_A1+1? */ if (fname == arg1_(sim.remfn) && narg == 2) return cg_fnap(mk_expr2(s_fnap, te_int, sim.divfn, (Expr *)exprfnargs_(x)), R_A1+1, YES); else if (fname == arg1_(sim.uremfn) && narg == 2) return cg_fnap(mk_expr2(s_fnap, te_uint, sim.udivfn, (Expr *)exprfnargs_(x)), R_A1+1, YES); #endif if (fname == sim.llsrem && narg == 3) return cg_fnap(mk_expr2(h0_(x), te_llint, ptrtofn_(sim.llsdiv), (Expr *)exprfnargs_(x)), R_A1+2, YES); else if (fname == sim.llurem && narg == 3) return cg_fnap(mk_expr2(h0_(x), te_ullint, ptrtofn_(sim.lludiv), (Expr *)exprfnargs_(x)), R_A1+2, YES); else if (fname == sim.llsrrem && narg == 3) return cg_fnap(mk_expr2(h0_(x), te_llint, ptrtofn_(sim.llsrdv), (Expr *)exprfnargs_(x)), R_A1+2, YES); else if (fname == sim.llurrem && narg == 3) return cg_fnap(mk_expr2(h0_(x), te_ullint, ptrtofn_(sim.llurdv), (Expr *)exprfnargs_(x)), R_A1+2, YES); if (bindsym_(exb_(fname)) == sim.strcpysym) { if (narg == 2 && h0_(a2) == s_string) { /* isstring_()? */ int32 n = LengthOfString(exs_(a2)); *xp = mk_expr2(s_fnap, type_(x), sim.realmemcpyfn, mkArgList3(a1, a2, mkintconst(te_int, n+1, 0))); return open_compilable(xp, rsort, valneeded); } else return NOT_OPEN_COMPILABLE; } if (bindsym_(exb_(fname)) == sim.strlensym) { if (narg == 1 && h0_(a1) == s_string) { /* isstring_()? */ int32 n = LengthOfString(exs_(a1)); return cg_expr(mkintconst(te_int, n, 0)); } else return NOT_OPEN_COMPILABLE; } /* Next macro tests if translating 'memcpy' to '_memcpy' is worthwhile */ /* It must be still in flux... */ #define structptrlike(e) ((alignofpointee(e,1) & (MOVC_ALIGN_MIN-1)) == 0) #ifdef TARGET_HAS_BLOCKMOVE # define cg_inlineable_size(n) (((n) & (MEMCPYQUANTUM-1)) == 0) #else /* Currently the non-J_MOVC expansion below only works for mults of 4, */ /* and then only if guaranteed 4-byte aligned. */ # define cg_inlineable_size(n) (alignof_struct >= 4 && (n & 3) == 0) #endif if (bindsym_(exb_(fname)) == bindsym_(exb_(arg1_(sim.realmemcpyfn))) && !valneeded && narg == 3 && h0_(a3) == s_integer && ((n = intval_(a3)) < MEMCPYQUANTUM || (structptrlike(a1) && structptrlike(a2)))) { Expr *x1; Expr *args = (Expr *)exprfnargs_(x); if (!cg_inlineable_size(n)) { int32 padding; int32 destsize = sizeofpointee(a1, &padding); if (n == destsize && padding != 0 && cg_inlineable_size(destsize+padding)) args = mkArgList3(a1, a2, mkintconst(te_int, destsize+padding, 0)); else if (n >= MEMCPYQUANTUM) return NOT_OPEN_COMPILABLE; } x1 = mk_expr2(s_fnap, type_(x), sim.memcpyfn, args); return open_compilable(&x1, rsort, valneeded); } if (bindsym_(exb_(fname)) == bindsym_(exb_(arg1_(sim.realmemsetfn))) && narg == 3 && h0_(a2) == s_integer && intval_(a2) == 0 && h0_(a3) == s_integer && ((n = intval_(a3)) < MEMCPYQUANTUM || structptrlike(a1)) && 0) /* coming to exist */ { Expr *x1; Expr *args = (Expr *)exprfnargs_(x); if (!cg_inlineable_size(n)) { int32 padding; int32 destsize = sizeofpointee(a1, &padding); if (n == destsize && padding != 0 && cg_inlineable_size(destsize+padding)) args = mkArgList3(a1, a2, mkintconst(te_int, destsize+padding, 0)); else if (n >= MEMCPYQUANTUM) return NOT_OPEN_COMPILABLE; } x1 = mk_expr2(s_fnap, type_(x), sim.memsetfn, args); return open_compilable(&x1, rsort, valneeded); } /* At present the main thing that we do open compilation for is */ /* _memcpy() and _memset() and then only if it has just 3 args, the */ /* last of which is an integer with value >= 0 & a multiple of */ /* alignof_struct (@@@ this last comment becoming out-of-date). */ if (bindsym_(exb_(fname)) == bindsym_(exb_(arg1_(sim.memcpyfn))) && narg == 3 && h0_(a3) == s_integer && (n = intval_(a3)) >= 0 && (n < MEMCPYQUANTUM || cg_inlineable_size(n))) { VRegnum r1, r2; int32 align = alignofpointee(a1, 1); int32 al2 = alignofpointee(a2, 1); if (al2 < align) align = al2; if (align > MOVC_ALIGN_MAX) align = MOVC_ALIGN_MAX; if (n < MEMCPYQUANTUM || align >= MOVC_ALIGN_MIN) { int32 j_align = align & 1 ? J_ALIGN1 : align & 2 ? J_ALIGN2 : align & 4 ? J_ALIGN4 : J_ALIGN8; /* * Here we break pay the penalty for having pretended that the ARM has * a block move instruction - we have to deny it at this stage. */ { /* ARM experiment with MOVC underway. Copy of a single word is turned into LOAD+STORE, as easier for CSE to optimise away if appropriate. Actually, I suppose that this is a good idea for all targets. Longer moves get turned into a MOVC (which destroys its argument registers if the move is longer than the number of registers I'm prepared to guarantee available). WD: should we do this for 2 words (doubles) too? */ if (n >= 8) { procflags |= PROC_HASMOVC; spareregs += 2; r1 = cg_expr(a1); r2 = cg_expr(a2); spareregs -= 2; if (n <= 12) /* If there are enough spare registers, the expansion of MOVC needn't alter r1 and r2. (2 dedicated registers, plus the one holding the source address). */ emit(J_MOVC|j_align, r1, r2, n); /* must NOT corrupt r1 */ else { VRegnum r3 = fgetregister(INTREG); emitreg(J_MOVR, r3, GAP, r1); emit(J_MOVC|j_align, r3, r2, n); bfreeregister(r3); } } else { Binder *loadv = is_local_adcon(a2), *storev = is_local_adcon(a1); r1 = GAP; r2 = GAP; spareregs += 2; if (n < MEMCPYQUANTUM) { VRegnum r3; if (storev == NULL || (mcrepofexpr((Expr *)storev) & MCR_SORT_MASK) < MCR_SORT_FLOATING) r1 = cg_expr(a1); if (loadv == NULL || (mcrepofexpr((Expr *)loadv) & MCR_SORT_MASK) < MCR_SORT_FLOATING) r2 = cg_expr(a2); spareregs -= 2; r3 = fgetregister(MEMCPYREG); while (--n >= 0) { if (r2 != GAP) emit(J_LDRBK|J_ALIGN1, r3, r2, n); else emitvk(J_LDRBVK|J_ALIGN1, r3, n, loadv); if (r1 != GAP) emit(J_STRBK|J_ALIGN1, r3, r1, n); else emitvk(J_STRBVK|J_ALIGN1, r3, n, storev); } bfreeregister(r3); } else if (n == sizeof_int && !valneeded) { Expr *e = mk_expr2(s_assign, te_int, mk_expr1(s_content, te_int, optimise0(mk_expr1(s_cast, ptrtotype_(te_int), a1))), mk_expr1(s_content, te_int, optimise0(mk_expr1(s_cast, ptrtotype_(te_int), a2)))); cg_exprvoid(e); } else { VRegnum r3, r4; bool load_notvk = NO, store_notvk = NO; if (storev != NULL) { if ((mcrepofexpr((Expr *)storev) & MCR_SORT_MASK) < MCR_SORT_FLOATING) store_notvk = YES; } else r1 = cg_expr(a1); if (loadv != NULL) { if ((mcrepofexpr((Expr *)loadv) & MCR_SORT_MASK) < MCR_SORT_FLOATING) load_notvk = YES; } else r2 = cg_expr(a2); spareregs -= 2; /* WD - experiment: generate result delay scheduled code */ r3 = fgetregister(MEMCPYREG); r4 = fgetregister(MEMCPYREG); while ((n -= 2 * MEMCPYQUANTUM) >= 0) { if (loadv == NULL) { emit(J_memcpy(J_LDRK|J_ALIGN4), r3, r2, n); emit(J_memcpy(J_LDRK|J_ALIGN4), r4, r2, n + MEMCPYQUANTUM); } else if (load_notvk) { emitbinder(J_LDRV|J_ALIGN4, r3, loadv); emitbinder(J_LDRV|J_ALIGN4, r4, loadv); } else { emitvk(J_memcpy(J_LDRVK|J_ALIGN4), r3, n, loadv); emitvk(J_memcpy(J_LDRVK|J_ALIGN4), r4, n + MEMCPYQUANTUM, loadv); } if (storev == NULL) { emit(J_memcpy(J_STRK|J_ALIGN4), r3, r1, n); emit(J_memcpy(J_STRK|J_ALIGN4), r4, r1, n + MEMCPYQUANTUM); } else if (store_notvk) { emitbinder(J_STRV|J_ALIGN4, r3, storev); emitbinder(J_STRV|J_ALIGN4, r4, storev); } else { emitvk(J_memcpy(J_STRVK|J_ALIGN4), r3, n, storev); emitvk(J_memcpy(J_STRVK|J_ALIGN4), r4, n + MEMCPYQUANTUM, storev); } } bfreeregister(r4); n += 2 * MEMCPYQUANTUM; while ((n -= MEMCPYQUANTUM) >= 0) { if (loadv == NULL) emit(J_memcpy(J_LDRK|J_ALIGN4), r3, r2, n); else if (load_notvk) emitbinder(J_LDRV|J_ALIGN4, r3, loadv); else emitvk(J_memcpy(J_LDRVK|J_ALIGN4), r3, n, loadv); if (storev == NULL) emit(J_memcpy(J_STRK|J_ALIGN4), r3, r1, n); else if (store_notvk) emitbinder(J_STRV|J_ALIGN4, r3, storev); else emitvk(J_memcpy(J_STRVK|J_ALIGN4), r3, n, storev); } bfreeregister(r3); } } } bfreeregister(r2); return r1; } } /* * The following code does open compilation of "_memset" in the case * were there are 3 args and the second and third args are * zero and divisible by alignof_struct exactly. */ if (bindsym_(exb_(fname)) == bindsym_(exb_(arg1_(sim.memsetfn))) && narg == 3 && h0_(a2) == s_integer && intval_(a2) == 0 && h0_(a3) == s_integer && (n = intval_(a3)) >= 0 && (n < MEMCPYQUANTUM || cg_inlineable_size(n))) { VRegnum r1; /* @@@ currently _memset/J_CLRC implies at least J_ALIGN4. */ int32 align = alignofpointee(a1, 1); if (n < MEMCPYQUANTUM || !(align & 3)) { VRegnum r2; #if defined (TARGET_HAS_BLOCKMOVE) && !defined(TARGET_IS_ARM) if (n >= MEMCPYQUANTUM) { spareregs += 1; /* duh? */ r1 = cg_expr(a1); spareregs -= 1; emit(J_CLRC|J_ALIGN4, r1, GAP, n); /* must NOT corrupt r1? */ } #else /* TARGET_HAS_BLOCKMOVE */ /* For very short memset's I just do STORE sequences. For longer ones */ /* I synthesize a loop. */ #ifdef TARGET_IS_ARM if (n >= 8) { procflags |= PROC_HASMOVC; r1 = cg_expr(a1); if (n == 8) emit(J_CLRC|J_ALIGN4, r1, GAP, n); /* must NOT corrupt r1 */ else { r2 = fgetregister(INTREG); emitreg(J_MOVR, r2, GAP, r1); emit(J_CLRC|J_ALIGN4, r2, GAP, n); bfreeregister(r2); } } #else /* TARGET_IS_ARM */ if (n >= 10*MEMCPYQUANTUM) { LabelNumber *ll = nextlabel(); VRegnum r3; spareregs += 2; r1 = cg_expr(a1); r2 = MEMCPYREG==DBLREG ? cg_loadfpzero(DBLREG,0) : cg_expr(a2); spareregs -= 2; r3 = fgetregister(INTREG); emit(J_MOVK, r3, GAP, n-MEMCPYQUANTUM); #ifdef TARGET_LACKS_RR_STORE emit(J_ADDK, r1, r1, n); #endif start_new_basic_block(ll); #ifdef TARGET_LACKS_RR_STORE emit(J_SUBK, r1, r1, MEMCPYQUANTUM); emit(J_memcpy(J_STRK|J_ALIGN4), r2, r1, 0); #else emitreg(J_memcpy(J_STRR|J_ALIGN4), r2, r1, r3); #endif emit(J_SUBK, r3, r3, MEMCPYQUANTUM); emit(J_CMPK + Q_GE, GAP, r3, 0); emitbranch(J_B + Q_GE, ll); bfreeregister(r3); bfreeregister(r2); } #endif #endif /* TARGET_HAS_BLOCKMOVE */ else { Binder *storev = is_local_adcon(a1); r1 = GAP; spareregs += 2; if (n < MEMCPYQUANTUM) { if (storev == NULL || (mcrepofexpr((Expr *)storev) & MCR_SORT_MASK) < MCR_SORT_FLOATING) r1 = cg_expr(a1); r2 = cg_expr(a2); spareregs -= 2; while (--n >= 0) { if (r1 != GAP) emit(J_STRBK|J_ALIGN1, r2, r1, n); else emitvk(J_STRBVK|J_ALIGN1, r2, n, storev); } } else { bool store_notvk = NO; if (storev != NULL) { if ((mcrepofexpr((Expr *)storev) & MCR_SORT_MASK) < MCR_SORT_FLOATING) store_notvk = YES; } else r1 = cg_expr(a1); r2 = MEMCPYREG==DBLREG && !store_notvk ? cg_loadfpzero(DBLREG,0) : cg_expr(a2); spareregs -= 2; while ((n -= MEMCPYQUANTUM) >= 0) { if (storev == NULL) emit(J_memcpy(J_STRK|J_ALIGN4), r2, r1, n); else if (store_notvk) emitbinder(J_STRV|J_ALIGN4, r2, storev); else emitvk(J_memcpy(J_STRVK|J_ALIGN4), r2, n, storev); } } bfreeregister(r2); } return r1; } } if (bindsym_(exb_(fname)) == bindsym_(exb_(arg1_(sim.memcpyfn)))) { /* _memcpy which has failed to be expanded in-line (length or alignment wrong - can only happen with __packed structs). */ *xp = mk_expr2(s_fnap, type_(x), sim.realmemcpyfn, (Expr *)exprfnargs_(x)); return NOT_OPEN_COMPILABLE; } if (bindsym_(exb_(fname)) == bindsym_(exb_(arg1_(sim.memsetfn)))) { /* _memset which has failed to be expanded in-line (see above) */ *xp = mk_expr2(s_fnap, type_(x), sim.realmemsetfn, (Expr *)exprfnargs_(x)); return NOT_OPEN_COMPILABLE; } if (bindsym_(exb_(fname)) == bindsym_(exb_(arg1_(sim.inserted_word))) && narg == 1 && h0_(a1) == s_integer) { /* _word(nnn) will plant nnn in the code - for EXPERT/lunatic use only! */ emit(J_WORD, GAP, GAP, intval_(a1)); return R_A1; /* /* Resultregister wanted here? */ } if ((bindstg_(exb_(fname)) & bitofstg_(s_inline)) && !(var_cc_private_flags & 8192L)) { Expr *structresult = NULL; ExprList *args = exprfnargs_(x); if (returnsstructinregs_t(bindtype_(exb_(fname)))) if (h0_(x) != s_fnap) { structresult = exprcar_(args); args = cdr_(args); } return TryInlineRestore(exb_(fname), args, structresult, rsort, valneeded); } return NOT_OPEN_COMPILABLE; } /* jopcode generation for binding vars and args ... */ static Binder *gentempvar(TypeExpr *t, VRegnum r) { /* like gentempbinder, but pretends set_local_vregister called */ /* bindaddr_() is not set at this point, but will get filled */ /* in later (by cg_bindlist or explicit code) if it might be */ /* needed. There will be a syserr if an attempt is made to */ /* reference a spilt temporary that has not been completed */ /* properly. */ Binder *bb = gentempbinder(t); bindxx_(bb) = r; bindmcrep_(bb) = mcrepofexpr((Expr *)bb); return bb; } static TypeExpr *teofsort(RegSort sort) { switch (sort) { case FLTREG: return te_float; case DBLREG: return te_double; #ifdef ADDRESS_REG_STUFF case ADDRREG:return te_int; #endif default: return te_int; } } Binder *gentempvarofsort(RegSort sort) { return gentempvar(teofsort(sort), vregister(sort)); } static Binder *gentempvarwithname(TypeExpr *t, VRegnum r, char *name) { /* As gentempvar(), but prescribes the name to be given to the */ /* generated binder */ Binder *bb = gentempbinderwithname(t, name); bindxx_(bb) = r; bindmcrep_(bb) = mcrepofexpr((Expr *)bb); return bb; } Binder *gentempvarofsortwithname(RegSort sort, char *name) { return gentempvarwithname(teofsort(sort), vregister(sort), name); } static void set_local_vregister(Binder *b, int32 rep, bool isarg) { VRegnum r = GAP; int32 mode = rep >> MCR_SORT_SHIFT, len = rep & MCR_SIZE_MASK; if (isvolatile_type(bindtype_(b))) { /* treat volatile locals as 'address taken' for setjmp. */ bindstg_(b) = (bindstg_(b) & ~bitofstg_(s_register)) | b_spilt; } if (!(bindstg_(b) & b_spilt)) { /* try to put in a register */ if (mode == 0 || mode == 1) /* ADENART, was "&& len<=4". */ { #ifdef ADDRESS_REG_STUFF TypeExpr *t = princtype(bindtype_(b)); r = vregister(h0_(t) == t_content || h0_(t) == t_subscript ? ADDRREG : INTREG); #else r = vregister(INTREG); #endif /* J_INIT never generates code: it can be thought of as meaning */ /* "load this register with an undefined value" and it helps register */ /* allocation in the case that the user seems not to initialise the */ /* variable properly. E.g. it controls the trouble I get in code like: */ /* { int x; <thing not using x>; if (tautology) x = 1; <use x>; } */ if (!isarg) emitbinder(J_INIT, r, b); } else if (mode == 2 && len==4) { r = vregister(FLTREG); if (!isarg) emitbinder(J_INITF, r, b); } else if (mode == 2 && len==8) { r = vregister(DBLREG); if (!isarg) emitbinder(J_INITD, r, b); } } bindxx_(b) = r; bindmcrep_(b) = rep; if ((bindstg_(b) & bitofstg_(s_register)) && /* @@@ LDS 23Aug89 - Temporary: to be rationalised soon. Sorry */ !(var_cc_private_flags & 1L)) { regvar_binders = mkBindList(regvar_binders, b); /* discouragement of spilling now in regalloc */ } else local_binders = mkBindList(local_binders, b); } static void init_slave_reg( Binder *b, int32 argno, int32 nfltregwords, int32 nintregargs) /* b is the binder for a potentially registered argument variable. Load */ /* its initial value from the place where the relevant argument was */ /* passed - register a1 to a4 for simple cases and the stack otherwise. */ /* Oct 92: this code is in need of re-parameterisation. */ { /* bindaddr_(b) is known to be BINDADDR_ARG. */ int32 addr = bindaddr_(b) & ~BINDADDR_MASK; int32 n = addr / alignof_toplevel_auto; VRegnum v = bindxx_(b); if (v != GAP) { int32 ni = n - nfltregwords; int32 ir = ni; RegSort rsort = vregsort(v); #ifdef TARGET_STRUCT_RESULT_REGISTER if (b == result_variable) emitreg(J_MOVR, v, GAP, TARGET_STRUCT_RESULT_REGISTER); else #endif if (isintregtype_(rsort)) { /* @@@ The following lines need tidying (remember adenart stops */ /* collecting args when it sees a struct (parameterise!)). */ /* @@@ Are the other NARGREGS's below OK too? */ if (0 <= ni && ni < nintregargs) emitreg(J_MOVR, v, GAP, R_P1+ir); else emitbinder(J_LDRV1|J_ALIGN4V, v, b); } else if (rsort == FLTREG) /* This case does not currently happen in standard Norcroft compilers, */ /* since 'float' args are passed as double and callee-narrowed. */ /* J_MOVIFR has to copy a bit-pattern from an integer register into one */ /* of the FP registers. */ { if (ni < 0) emitreg(J_MOVFR, v, GAP, R_FP1+argno); else if (ir < NARGREGS) #ifdef TARGET_SHARES_INTEGER_AND_FP_REGISTERS emitreg(J_MOVFR, v, GAP, R_P1+ir); #else emitreg(J_MOVIFR, v, GAP, R_P1+ir); #endif else emitbinder(J_LDRFV1|J_ALIGN4V, v, b); } else /* If I have a double-precision arg the value is passed in two integers */ /* and here I must be prepared to move it into a doubleprecision FP */ /* register. */ { if (ni < 0) /* The following line assumes FPREGARGS are arranged to appear first... */ emitreg(J_MOVDR, v, GAP, R_FP1+argno); else if (ir < NARGREGS-1) emitreg(J_MOVIDR, v, R_P1+ir, R_P1+ir+1); else /* If a floating point arg straddles the boundary between where args are */ /* passed in registers & where they come on the stack I know that there */ /* are at least 5 words of args, so if I suppress the leaf-procedure */ /* optimisation I know that the args will get written to the stack as */ /* contiguous words. Then I can load the FP value easily. */ { if (ir == NARGREGS-1) procflags |= PROC_ARGPUSH; emitbinder(J_LDRDV1|J_ALIGN8, v, b); } } } } static void cg_bindlist(SynBindList *x, bool initflag) { /* initflag is 1 if J_INIT is not needed due to later explicit init. */ BindList *new_binders = active_binders; for (; x!=NULL; x = x->bindlistcdr) { Binder *b = x->bindlistcar; if (bindstg_(b) & bitofstg_(s_auto)) /* ignore statics */ /* N.B. register vars must also have auto bit set */ { int32 rep = mcrepofexpr((Expr *)b); set_local_vregister(b, rep, initflag); new_binders = mkBindList(new_binders, b); b->bindaddr.bl = new_binders; bindstg_(b) |= b_bindaddrlist; /* the next 3 line calculation should be done after regalloc, not here */ current_stackdepth = padtomcrep(current_stackdepth, rep) + padsize(rep & MCR_SIZE_MASK, alignof_toplevel_auto); if (current_stackdepth > greatest_stackdepth) greatest_stackdepth = current_stackdepth; } } emitsetsp(J_SETSPENV, new_binders); } static int32 cg_bindargs_size(BindList *args) { int32 argoff = 0; for (; args!=NULL; args=args->bindlistcdr) { Binder *b = args->bindlistcar; int32 rep = mcrepofexpr((Expr *)b); /* Things in an argument list can only have s_auto storage class */ if (!(bindstg_(b) & bitofstg_(s_auto))) syserr(syserr_nonauto_arg); argoff = padtomcrep(argoff, rep); set_local_vregister(b, rep, 1); bindaddr_(b) = argoff | BINDADDR_ARG; argoff += padsize(rep & MCR_SIZE_MASK, alignof_toplevel_auto); } return argoff; } /* One might worry here about functions that specify their formals with */ /* a type such as char, short or float. For language independence sem.c */ /* arranges that such things never occur by generating an explicit */ /* narrowing assignment in this case. */ static int32 cg_bindargs(BindList *args, bool ellipsis) /* Ellipsis is true if this function was defined with a '...' at the end */ /* of the list of formal pars it should accept. */ /* Returns number of argwords for possible use by codeseg_function_name(). */ /* Note that on some machines (e.g. the 88000) very strange things have to */ /* be done to support va_args (i.e. if '...' is indicated). Also in some */ /* cases integer, floating and structure args may be passed in different */ /* ways. */ { BindList *x; int32 argoff, lyingargwords; int32 nfltregargs = 0, nintregargs = 0, nfltregwords = 0; int32 argno = 0; /* If ANY argument has its address taken I mark ALL arguments as having */ /* their address taken, unless the user has declared them as registers. */ for (x = args; x!=NULL; x=x->bindlistcdr) { Binder *b = x->bindlistcar; if (bindstg_(b) & b_addrof) { for (x = args; x!=NULL; x=x->bindlistcdr) { b = x->bindlistcar; if (!(bindstg_(b) & bitofstg_(s_register))) bindstg_(b) |= b_addrof; } break; } } #ifdef TARGET_FP_ARGS_IN_FP_REGS if ((config & CONFIG_FPREGARGS)) { BindList *intargs = NULL, **intargp = &intargs, *fltregargs = NULL, **fltregargp = &fltregargs; for (x = args; x != NULL; x = x->bindlistcdr) { Binder *b = x->bindlistcar; BindList *newbl = mkBindList(NULL, b); int32 rep = mcrepofexpr((Expr *)b); if ((rep & MCR_SORT_MASK) == MCR_SORT_FLOATING && nfltregargs < NFLTARGREGS ) { int32 bytes = rep & MCR_SIZE_MASK; nfltregwords += (bytes > alignof_toplevel_auto ? bytes : alignof_toplevel_auto) / sizeof_int; nfltregargs++, *fltregargp = newbl, fltregargp = &newbl->bindlistcdr; } else *intargp = newbl, intargp = &newbl->bindlistcdr; } if (intargs != NULL) *fltregargp = intargs; args = fltregargs; argoff = cg_bindargs_size(args); nintregargs = intargs == NULL ? 0 : (argoff - (bindaddr_(intargs->bindlistcar) & ~BINDADDR_MASK))/4; } else #endif /* TARGET_FP_ARGS_IN_FP_REGS */ { argoff = cg_bindargs_size(args), nintregargs = argoff/alignof_toplevel_auto; } currentfunction.fltargwords = nfltregwords; if (nintregargs > NARGREGS) nintregargs = NARGREGS; max_argsize = argoff; #ifdef TARGET_STRUCT_RESULT_REGISTER if (result_variable != NULL) { int32 rep = mcrepofexpr((Expr *)result_variable); set_local_vregister(result_variable, rep, 1); /* * The bindaddr field would be inspected in init_slave_reg, but that * takes special action on result_variable so I can put junk in here. */ bindaddr_(result_variable) = BINDADDR_ARG; } #endif /* Note that with '...' a cautious entry sequence is needed: */ /* it suffices to tell the back-end that we need many arg words. */ /* The value 0x7fff is chosen for backwards compatibility and easy */ /* visibility in masks. It is subject to change and backends should */ /* check for a value outwith 0..255. */ lyingargwords = ellipsis ? K_ARGWORDMASK : argoff/alignof_toplevel_auto; /* The operand of J_ENTER is used to determine addressing of args */ /* on machines such as the ARM. */ emit(J_ENTER, GAP, GAP, /* note the first zero is dubious -- rely on regalloc.c not */ /* using it! */ k_argdesc_(lyingargwords, 0, nintregargs, nfltregargs, (int32)currentfunction.nresultregs, ellipsis ? K_VAFUNC : 0)); #ifdef TARGET_STRUCT_RESULT_REGISTER if (result_variable != NULL) init_slave_reg(result_variable, 0, 0, 0); #endif for (x=args; x!=NULL; x=x->bindlistcdr) init_slave_reg(x->bindlistcar, argno++, nfltregwords, nintregargs); active_binders = NULL; current_stackdepth = greatest_stackdepth = 0; start_new_basic_block(nextlabel()); return lyingargwords; } static void loadresultsfrombinder(Binder *x) { int32 n; for (n = 0; n < currentfunction.nresultregs; n++) emitvk(J_memcpy(J_LDRVK|J_ALIGN4), V_Presultreg(INTREG)+n, n*MEMCPYQUANTUM, x); } static void cg_return(Expr *x, bool implicitinvaluefn) { LabelNumber *retlab = (implicitinvaluefn ? RetImplLab : RetVoidLab); if (x!=0) { int32 mcrep = mcrepofexpr(x); /* Structure results are massaged here to give an assignment via a */ /* special variable. */ /* @@@ This all need updating for C++, but in the meantime note that */ /* CPLUSPLUS constructors in return statements give a non-omitted */ /* return expr of VOID type. */ if ((mcrep >> MCR_SORT_SHIFT) == 3) { TypeExpr *t = typeofexpr(x); if (currentfunction.nresultregs > 0) { if (h0_(x) == s_fnap && returnsstructinregs(arg1_(x))) { VRegnum r = cg_expr(mk_expr2(s_fnapstructvoid, te_void, arg1_(x), mkArg(exprfnargs_(x), NULL))); if (r != R_A1 && r != GAP) { int n; for (n = 0; n < currentfunction.nresultregs; n++) emitreg(J_MOVR, R_A1+n, GAP, r+n); } } else if (h0_(x) == s_binder && (bindstg_(exb_(x)) & bitofstg_(s_auto))) loadresultsfrombinder(exb_(x)); else { if (h0_(x) != s_fnap) { t = ptrtotype_(t); x = cg_optimise0(mk_expr1(s_addrof, t, x)); } if (h0_(t) != t_content) { BindList *sl = active_binders; int32 d = current_stackdepth; Binder *temp = gentempbinder(t); cg_bindlist(mkSynBindList(0, temp), 0); x = mk_expr2(s_assign, t, (Expr *)temp, x); cg_exprvoid(x); loadresultsfrombinder(temp); emitsetsp(J_SETSPENV, sl); current_stackdepth = d; } else { VRegnum r = cg_expr(x); int32 n; for (n = 0; n < currentfunction.nresultregs; n++) emit(J_memcpy(J_LDRK|J_ALIGN4), V_Presultreg(INTREG)+n, r, n * MEMCPYQUANTUM); bfreeregister(r); } } retlab = RetIntLab; } else { if (result_variable==NULL) syserr(syserr_struct_result); /* Return the result of a struct-returning fn. The result expn is a var, */ /* a fn call, or (let v in expn) if expn involves a struct-returning fn. */ if (h0_(x) == s_fnap) /* return f(...), so use the reult variable directly to get whizzy code. */ cg_exprvoid(mk_expr2(s_fnapstruct, te_void, arg1_(x), mkArg(exprfnargs_(x), result_variable))); else if (h0_(x) == s_let) /* Here we have a return (expn involving a struct-fn call). It's a pity */ /* that multiple such things can't be commoned up to share a single */ /* result copy operation. The problem is the scope of the binder in the */ /* let, absence of return expressions, and failure to distribute the */ /* missing return expressions through the tree appropriately (Sigh). */ { arg2_(x) = mk_expr2(s_assign, t, mk_expr1(s_content, t, (Expr *)result_variable), arg2_(x)); cg_exprvoid(x); } else /* There is some hope of commoning up the result copies, for example in */ /* return i ? x : y, where x and y are binders. Do this by using a ptr */ /* to the result value until a common tail of code in which *res = *val */ { TypeExpr *pt = ptrtotype_(t); cg_exprvoid( mk_expr2(s_assign, pt, (Expr *)result_temporary, /* @@@ LDS 22-Sep-89: use of optimise0() here is iffy, and anticipates */ /* the evolution of simplify into a properly specified tree transformer */ cg_optimise0(mk_expr1(s_addrof, pt, x)))); if (structretlab == NOTALABEL) { structretlab = nextlabel(); start_new_basic_block(structretlab); cg_exprvoid(mk_expr2(s_assign, t, mk_expr1(s_content, t, (Expr *)result_variable), mk_expr1(s_content, t, (Expr *)result_temporary))); } else { emitsetspgoto(active_binders, structretlab); emitbranch(J_B, structretlab); return; } } } } else { int32 mcmode = mcrep >> MCR_SORT_SHIFT; RegSort rsort = mcmode!=2 ? INTREG : (mcrep==0x02000004 ? FLTREG : DBLREG); /* The next line takes care of compiling 'correct' code for */ /* void f() { return g();} */ /* It now deals with C++ class returning functions (syn.c) */ if ((mcrep & MCR_SIZE_MASK) == 0) { cg_exprvoid(x); retlab = RetVoidLab; } else { VRegnum r = cg_expr(x); emitreg(floatyop(rsort, J_MOVR, J_MOVFR, J_MOVDR), V_Presultreg(rsort), GAP, r); bfreeregister(r); retlab = (rsort == DBLREG ? RetDbleLab : rsort == FLTREG ? RetFloatLab : RetIntLab); } } } else if (defining_main) { /* Within main() any return; is treated as return 0; - this */ /* is done because the value returned by main() is used as */ /* a success code by the library, but on some other C systems */ /* the value of main() is irrelevant... */ /* Users who go */ /* struct foo main(int argc, char *argv[]) { ... } */ /* are not protected here! */ /* AM: unfortunately this stops implicit return warnings... */ emit(J_MOVK, V_Presultreg(INTREG), GAP, 0); retlab = RetIntLab; } emitsetspenv(active_binders, (BindList *)NULL); /* Not emitsetsp, because we don't want to allow it to be optimised out */ /* See comments in the CSE code for the need for a SETSP just before */ /* every RETURN. function modifycode().... */ /* Do not optimise this away lightly! */ /* Note also that 'active_binders = NULL;' is, in some sense, missed */ /* out here, but because of the emitbranch() this is NECESSARY! */ emitbranch(J_B, retlab); } static bool SimpleTest(Expr const *test) { while (h0_(test) == s_boolnot) test = arg1_(test); return isrelational_(h0_(test)); /* (x) has already been turned into (x != 0) */ } static void cg_loop(Expr *init, Expr *pretest, Expr *step, Cmd *body, Expr *posttest) { /* Here I deal with all loops. Many messy things are going on! */ struct LoopInfo oloopinfo; bool once = at_least_once(init, pretest); /* A large amount of status belongs with loop constructs, and gets saved */ /* here so that it can be restored at the end of compiling the loop. */ oloopinfo = loopinfo; loopinfo.breaklab = loopinfo.contlab = 0; loopinfo.binders = active_binders; if (init != 0) cg_exprvoid(init); /* the initialiser (if any) */ cg_count(cmdfileline_(cg_current_cmd)); /* The variable once has been set true if, on the basis if looking at */ /* the initialiser and the pretest I can tell that the loop will be */ /* traversed at least once. In that case I will use the pretest as a */ /* posttest for better generated code. */ if (!usrdbg(DBG_LINE) || (pretest == 0 && step == 0)) { LabelNumber *bodylab = nextlabel(), *steplab = 0; if (!once) { if (body != NULL && h0_(body) != s_continue && SimpleTest(pretest) && !(config & CONFIG_OPTIMISE_SPACE)) cg_test(pretest, NO, loopinfo.breaklab = nextlabel()); else emitbranch(J_B, steplab = nextlabel()); } start_new_basic_block(bodylab); if (body != NULL) { cg_count(cmdfileline_(body)); cg_cmd(body); } if (loopinfo.contlab != 0) start_new_basic_block(loopinfo.contlab); if (step != 0) cg_exprvoid(step); if (steplab != 0) start_new_basic_block(steplab); /* When cg_loop is called there can NEVER be both a pretest and a post- */ /* test specified. Here I put out the (conditional) branch back up to */ /* the top of the loop. */ cg_count(cmdfileline_(cg_current_cmd)); if (pretest != 0) cg_test(pretest, YES, bodylab); else if (posttest != 0) cg_test(posttest, YES, bodylab); else emitbranch(J_B, bodylab); } else { LabelNumber *steplab, *bodylab = nextlabel(); LabelNumber *testlab = pretest == 0 ? 0 : nextlabel(); loopinfo.contlab = steplab = (step != 0) ? nextlabel() : testlab; if (pretest != 0) { start_new_basic_block(testlab); loopinfo.breaklab = nextlabel(); if (step == 0) cg_test(pretest, NO, loopinfo.breaklab); else { cg_test(pretest, YES, bodylab); emitbranch(J_B, loopinfo.breaklab); } } if (step != 0) { if (pretest == 0) emitbranch(J_B, bodylab); start_new_basic_block(steplab); if (exprfileline_(step) != 0) emitfl(J_INFOLINE, *exprfileline_(step)); cg_exprvoid(step); if (testlab != 0) emitbranch(J_B, testlab); } start_new_basic_block(bodylab); if (body != NULL) { cg_count(cmdfileline_(body)); cg_cmd(body); } cg_count(cmdfileline_(cg_current_cmd)); if (posttest != 0) cg_test(posttest, YES, steplab); else emitbranch(J_B, steplab); } if (loopinfo.breaklab != 0) start_new_basic_block(loopinfo.breaklab); loopinfo = oloopinfo; } static int32 dense_case_table(CasePair *v, int32 ncases) { /* This function provides a criterion for selection of a test-and-branch */ /* or a jump-table implementation of a case statement. Note that it is */ /* necessary to be a little careful about arithmetic overflow in this */ /* code, and that the constants here will need tuning for the target */ /* computer's instruction timing characteristics. */ int32 low_value = v[0].caseval, high_value = v[ncases-1].caseval; int32 halfspan = high_value/2 - low_value/2; /* cannot overflow */ #ifdef TARGET_SWITCH_isdense if (TARGET_SWITCH_isdense(ncases,halfspan)) return 1; /* tuneable */ #else if (halfspan < ncases && /* The next line reflects SUB required on many targets. */ /* Should the test be on span, not ncases? */ (ncases > 4 || ncases==4 && low_value==0)) return 1; /* good try? */ { int32 shift; int32 val = ~low_value; int32 n = ncases; while (--n != 0) val &= ~v[n].caseval; val += 1; shift = logbase2(val & (-val)); if (shift > 1) { if (low_value < 0 && high_value > 0) { unsigned32 uhigh; for (n = 0; n < ncases; n++) if (v[n].caseval >= 0) break; uhigh = just32bits_(v[n-1].caseval); if (uhigh >> (shift+1) < (uint32)ncases && ncases >= 4+3) return shift+1+J_UNSIGNED; } if ((halfspan >> shift) < ncases && /* 3 here reflects the required test that bottom <shift> */ /* bits are zero */ (ncases > 4+3 || (ncases == 4+3 && low_value == 0))) return shift+1; } } #endif return 0; } static void linear_casebranch(VRegnum r, CasePair *v, int32 ncases, LabelNumber *defaultlab) { while (--ncases >= 0) { emit(J_CMPK + Q_EQ, GAP, r, v->caseval); emitbranch(J_B + Q_EQ, v->caselab); v++; } emitbranch(J_B, defaultlab); } static void table_casebranch(VRegnum r, CasePair *v, int32 ncases, LabelNumber *defaultlab, int32 shift) { int32 m, n, i, size; LabelNumber **table; VRegnum r1 = r; int32 shtype = J_SIGNED; int32 casex = 0; if (shift & J_UNSIGNED) { shtype = J_UNSIGNED; shift &= ~J_UNSIGNED; for (; casex < ncases; casex++) if (v[casex].caseval >= 0) break; m = 0, n = just32bits_((unsigned32)v[casex-1].caseval) >> (shift-1); } else { m = v[0].caseval, n = v[ncases-1].caseval; if (shift > 1) { m = signed_rightshift_(m, (shift-1)); n = signed_rightshift_(n, (shift-1)); } } size = n - m + 1; if (m == 1) { /* Avoid a subtraction (and maybe need for an extra register) by making the switch table one larger */ size++; m = 0; } table = (LabelNumber **) BindAlloc((size+1) * sizeof(LabelNumber *)); if (m != 0 || shift > 1) { VRegnum r2 = r; r1 = fgetregister(INTREG); if (shift > 1) { emit(J_ANDK, r1, r, (1L << (shift-1)) - 1); emit(J_CMPK + Q_NE, GAP, r1, 0); emitbranch(J_B + Q_NE, defaultlab); bfreeregister(r1); r1 = fgetregister(INTREG); emit(J_SHRK + shtype, r1, r, shift-1); r2 = r1; } if (m != 0) emit(J_SUBK, r1, r2, m); } table[0] = defaultlab; for (i = 0; i < size; i++) if (just32bits_((i+m) << (shift-1)) == just32bits_(v[casex].caseval)) { table[i+1] = v[casex].caselab; /* arrange wraparound for unsigned case */ if (++casex == ncases) casex = 0; } else table[i+1] = defaultlab; /* It is important that literals are not generated so as to break up */ /* the branch table that follows - J_CASEBRANCH requests this. */ /* Type check kluge in the next line... */ emitcasebranch(J_CASEBRANCH, r1, table, size + 1); if (r1 != r) bfreeregister(r1); } static void casebranch(VRegnum r, CasePair *v, int32 ncases, LabelNumber *defaultlab) { if (ncases<5) linear_casebranch(r, v, ncases, defaultlab); else { int32 n = dense_case_table(v, ncases); if (n != 0) table_casebranch(r, v, ncases, defaultlab, n); else { int32 mid = ncases/2; LabelNumber *l1 = nextlabel(); #ifdef TARGET_LACKS_3WAY_COMPARE emit(J_CMPK + Q_GE, GAP, r, v[mid].caseval); emitbranch(J_B + Q_GE, l1); casebranch(r, v, mid, defaultlab); start_new_basic_block(l1); casebranch(r, &v[mid], ncases-mid, defaultlab); #else /* * CSE is told here not to move things which might set the condition code * between the two conditional branches below by setting BLKCCLIVE. */ /* The following line is a nasty hack. */ /* It is also not always optimal on such machines. */ emit(J_CMPK + Q_UKN, GAP, r, v[mid].caseval); blkflags_(bottom_block) |= BLKCCEXPORTED; emitbranch(J_B + Q_EQ, v[mid].caselab); blkflags_(bottom_block) |= BLKCCLIVE; emitbranch(J_B + Q_GT, l1); casebranch(r, v, mid, defaultlab); start_new_basic_block(l1); casebranch(r, &v[mid+1], ncases-mid-1, defaultlab); #endif } } } static void cg_case_or_default(LabelNumber *l1) /* Produce a label for a case or default label in a switch. Note that in */ /* general we must jump round a stack adjusting jopcode, but to save jop */ /* and block header space we test for the common case. */ { if (active_binders == switchinfo.binders) start_new_basic_block(l1); /* the next few lines of code take care of 'case's within blocks with */ /* declarations: switch(x) { case 1: { int v[10]; case 2: foo(); }} */ else { LabelNumber *l = nextlabel(); BindList *bl = active_binders; emitbranch(J_B, l); start_basic_block_at_level(l1, active_binders = switchinfo.binders); /* Amazing amount of fiddling about in case ICODE section may overflow. */ emitsetsp(J_SETSPENV, bl); start_new_basic_block(l); } cg_count(cmdfileline_(cg_current_cmd)); } static VRegnum cg_loadconst(int32 n, Expr *e) { /* void e if !=NULL and return n - used for things like f()*0 */ VRegnum r; if (e) (void)cg_exprvoid(e); #ifdef TARGET_HAS_CONST_R_ZERO if (n == 0) return R_ZERO; #endif emit(J_MOVK, r=fgetregister(INTREG), GAP, n); return r; } static void cg_cond1(Expr *e, bool valneeded, VRegnum targetreg, LabelNumber *l3, bool structload) { for (; h0_(e)==s_comma; e = arg2_(e)) cg_exprvoid(arg1_(e)); if (h0_(e)==s_cond) (void)cg_cond(e, valneeded, targetreg, l3, structload); else if (!valneeded) bfreeregister(cg_expr1(e, valneeded)); else { if (structload) { VRegnum r; emitreg(J_MOVR, targetreg, GAP, r = load_integer_structure(e)); bfreeregister(r); } else (void)cg_exprreg(e, targetreg); blkflags_(bottom_block) |= BLKREXPORTED; } emitbranch(J_B, l3); } static VRegnum cg_cond(Expr *c, bool valneeded, VRegnum targetreg, LabelNumber *l3, bool structload) { Expr *b = arg1_(c), *e1 = arg2_(c), *e2 = arg3_(c); LabelNumber *l1 = nextlabel(); if (usrdbg(DBG_LINE) && exprfileline_(c) != 0) emitfl(J_INFOLINE, *exprfileline_(c)); cg_test(b, 0, l1); cg_cond1(e1, valneeded, targetreg, l3, structload); start_new_basic_block(l1); cg_cond1(e2, valneeded, targetreg, l3, structload); return targetreg; } static int32 ispoweroftwo(Expr *x) { unsigned32 n, r; if (!integer_constant(x)) return 0; n = result2; r = n & (0-n); if (n == 0 || r != n) return 0; r = 0; while (n != 1) r++, n >>= 1; return r; } static void structure_assign(Expr *lhs, Expr *rhs, int32 length) { Expr *e; /* In a void context I turn a structure assignment into a call to the */ /* library function memcpy(). */ /* Note that casts between structure types are not valid (and so will */ /* have been filtered out earlier), but casts to the same structure type */ /* can be present (particularly around (a ? b : c) expressions) as an */ /* artefact of the behaviour of sem. Prune them off here. */ /* AM Nov 89: The present arrangement of forgeing a call to _memcpy() is */ /* not very satisfactory -- there are problems with tail recursion if */ /* not TARGET_HAS_BLOCKMOVE and problems with stack addresses if */ /* TARGET_STACK_MOVES_ONCE (being fixed). */ /* To this end, note that 'lhs' ultimately has take_address() and */ /* typeofexpr() applied to it (but beware the s_assign ref. below). */ while (h0_(rhs) == s_cast) rhs = arg1_(rhs); switch (h0_(rhs)) { case s_let: { BindList *sl = active_binders; int32 d = current_stackdepth; cg_bindlist(exprletbind_(rhs), 0); structure_assign(lhs, arg2_(rhs), length); emitsetsp(J_SETSPENV, sl); current_stackdepth = d; return; } case s_comma: /* Maybe this recursive call should just be the expansion: */ /* (a = (b,c)) ---> (b, a=c). */ cg_exprvoid(arg1_(rhs)); structure_assign(lhs, arg2_(rhs), length); return; case s_assign: /* A chain of assignments as in p = q = r get mapped as follows: */ /* ( LET struct *g, */ /* g = &q, */ /* *g = r, */ /* p = *g ) */ /* thus &q gets evaluated only once */ /* or to ( q = r, p = q ) if q is simple */ { TypeExpr *t = typeofexpr(rhs); if (!isvolatile_type(t) && issimplelvalue(arg1_(rhs))) { e = mk_expr2(s_comma, t, rhs, mk_expr2(s_assign, t, lhs, arg1_(rhs))); } else { Binder *gen = gentempbinder(ptrtotype_(t)); e = mk_exprlet(s_let, t, mkSynBindList(0, gen), mk_expr2(s_comma, t, mk_expr2(s_assign, ptrtotype_(t), (Expr *)gen, take_address(arg1_(rhs))), mk_expr2(s_comma, t, mk_expr2(s_assign, t, mk_expr1(s_content, t, (Expr *)gen), arg2_(rhs)), mk_expr2(s_assign, t, lhs, /* @@@rework */ mk_expr1(s_content, t, (Expr *)gen))))); } } break; case s_fnap: e = mk_expr2(s_fnapstruct, te_void, arg1_(rhs), mkArg(exprfnargs_(rhs), take_address(lhs))); break; case s_cond: /* Convert a = (b ? c : d) */ /* (LET struct *g, */ /* g = &a, */ /* b ? (*g = c) : (*g = d)) */ /* */ /* or to b ? (a = c) : (a = d) if a is simple */ { TypeExpr *t = typeofexpr(lhs); if (issimplelvalue(lhs)) { e = mk_expr3(s_cond, t, arg1_(rhs), mk_expr2(s_assign, t, lhs, arg2_(rhs)), mk_expr2(s_assign, t, lhs, arg3_(rhs))); } else { Binder *gen = gentempbinder(ptrtotype_(t)); e = mk_exprlet(s_let, t, mkSynBindList(0, gen), mk_expr2(s_comma, t, mk_expr2(s_assign, ptrtotype_(t), (Expr *)gen, take_address(lhs)), mk_expr3(s_cond, t, arg1_(rhs), mk_expr2(s_assign, t, mk_expr1(s_content, t, (Expr *)gen), arg2_(rhs)), mk_expr2(s_assign, t, mk_expr1(s_content, t, (Expr *)gen), arg3_(rhs))))); } } break; case s_binder: if (bindconst_(exb_(rhs)) != NULL) { if (LanguageIsCPlusPlus) syserr("bindconst $b got to cg.c", exb_(rhs)); rhs = bindconst_(exb_(rhs)); } default: e = mk_expr2(s_fnap, te_void, sim.memcpyfn, mkArgList3(take_address(lhs), take_address(rhs), mkintconst(te_int,length,0))); break; } if (debugging(DEBUG_CG)) { eprintf("Structure assignment: "); pr_expr_nl(e); } cg_exprvoid(e); } static VRegnum load_integer_structure(Expr *e) { /* e is a structure-valued expression, but one where the value is a */ /* one-word integer-like quantity. Must behave like cg_expr would but */ /* with special treatment for function calls. */ switch (h0_(e)) { case s_comma: cg_exprvoid(arg1_(e)); return load_integer_structure(arg2_(e)); case s_assign: return cg_storein(load_integer_structure(arg2_(e)), NULL, arg1_(e), s_assign); case s_fnap: { TypeExpr *t = type_(e); Binder *gen = gentempbinder(ptrtotype_(t)); bindstg_(gen) |= b_addrof; e = mk_expr2(s_fnap, te_void, arg1_(e), /* /* AM: s_fnapstruct here? */ mkArg(exprfnargs_(e), take_address((Expr *)gen))); e = mk_exprlet(s_let, t, mkSynBindList(0, gen), mk_expr2(s_comma, t, e, (Expr *)gen)); return cg_expr(e); } /* Since casts between structure-types are illegal the only sort of cast */ /* that can be present here is just one re-asserting the type of the */ /* expression being loaded. Hence I skip over the cast. This certainly */ /* happens with a structure version of (a = b ? c : d) where the type gets */ /* inserted to give (a = (structure)(b ? c : d)). */ case s_cast: return load_integer_structure(arg1_(e)); case s_cond: { LabelNumber *l3 = nextlabel(); VRegnum r = cg_cond(e, 1, reserveregister(INTREG), l3, 1); start_new_basic_block(l3); return getreservedreg(r); } default: return cg_expr(e); } } static VRegnum cg_expr1(Expr *x, bool valneeded) { AEop op = h0_(x); /* See the discussion in chroma_check() above. */ /* @@@ AM thinks that spilling probably oughtn't to start so late -- */ /* the code here allows 1 single expression to preempt many reg vars. */ /* *** RETHINK HERE *** */ /* To avoid running out of registers I do dreadful things here: */ #ifdef TARGET_IS_THUMB /* ECN: 3 is better for Thumb as 4 means it has no free V registers * when calling a function with 4 args. Maybe 2 would be even better */ if ((nusedregs >= (NTEMPREGS+NARGREGS+NVARREGS-spareregs-3) #else if ((nusedregs >= (NTEMPREGS+NARGREGS+NVARREGS-spareregs-4) #endif #ifndef TARGET_SHARES_INTEGER_AND_FP_REGISTERS /* AM has unilaterally decided that 2 spare FP regs should always be enough */ /* here (after he has changed the unsigned FIX code). Anyway, using 3 for */ /* for 2 on the next line hurts the 370 code generator as EVERY integer */ /* operation spills! Suggestion - only spill FP regs when we have a FP */ /* result - however beware machines like the VAX where FP=INT reg! */ || nusedfpregs >= (NFLTTEMPREGS+NFLTARGREGS+NFLTVARREGS-sparefpregs-2) #endif ) && (op!=s_binder && op!=s_integer && op!=s_floatcon && !isstring_(op))) { /* Here I seem a bit short on working registers, so I take drastic steps */ /* and flush all current registers to the stack, do this calculation and */ /* then reload things. Keeping everything straight is a bit of a mess */ /* since this breaks the usual abstractions about register allocation */ /* and usage. */ BindList *save_binders = active_binders; int32 d = current_stackdepth; RegList *saveused = usedregs, *saveusedfp = usedfpregs; int32 savebits = nusedregs, savefpbits = nusedfpregs; int32 spint = spareregs, spfp = sparefpregs; VRegnum r; SynBindList *things_to_bind = bindlist_for_temps(saveused, saveusedfp); #ifndef REGSTATS /* * REGSTATS is defined when ACN is building a private system to investigate * register allocation behaviour */ if (debugging(DEBUG_SPILL)) { cc_msg("Usedregs = %ld, spareregs = %ld\n", (long)nusedregs, (long)spareregs); #ifndef TARGET_SHARES_INTEGER_AND_FP_REGISTERS cc_msg("FP count = %ld, sparefpregs = %ld\n", (long)nusedfpregs, (long)sparefpregs); #endif } #endif /* First I must allocate binders on the stack & save all current */ /* register contents away. */ cg_bindlist(things_to_bind, 1); stash_temps(saveused, saveusedfp, things_to_bind, J_STRV|J_ALIGN4V, J_STRFV|J_ALIGN4V, J_STRDV|J_ALIGN8); nusedregs = nusedfpregs = 0; usedregs = usedfpregs = NULL; spareregs = sparefpregs = 0; /* Then compute the value of this expression. */ if (valneeded) { r = cg_expr2(x, 1); /* I must free the register here because I am about to monkey about with */ /* the tables that show what registers are where. Ugh. */ bfreeregister(r); } else { r = cg_expr2(x, 0); bfreeregister(r); r = GAP; } /* Switch back to the outer context of registers. */ usedregs = saveused, usedfpregs = saveusedfp; nusedregs = savebits, nusedfpregs = savefpbits; spareregs = spint, sparefpregs = spfp; /* The result of evaluating this expression must be moved to a newly */ /* allocated register to make sure it does not clash with anything. */ if (r != GAP) { RegSort rsort = vregsort(r); VRegnum r1 = fgetregister(rsort); /* Register r is no longer formally allocated (by the chromaticity count */ /* code) but it will still exist! */ emitreg(floatyop(rsort, J_MOVR, J_MOVFR, J_MOVDR), r1, GAP, r); r = r1; } /* Now restore register values */ stash_temps(saveused, saveusedfp, things_to_bind, J_LDRV|J_ALIGN4V, J_LDRFV|J_ALIGN4V, J_LDRDV|J_ALIGN8); while (things_to_bind) things_to_bind = freeSynBindList(things_to_bind); /* adjust stack pointer as necessary. */ emitsetsp(J_SETSPENV, save_binders); current_stackdepth = d; return r; } else if (valneeded) return cg_expr2(x, 1); else { VRegnum r = cg_expr2(x, 0); bfreeregister(r); return GAP; } } void cg_sub_reinit(void) { codebuf_reinit2(); flowgraph_reinit(); cse_reinit(); regalloc_reinit(); } static void topdec_init(void) { cg_sub_reinit(); local_binders = regvar_binders = NULL; integer_binder = gentempvarwithname(te_int, GAP, "IntBinder"); bindstg_(integer_binder) |= b_spilt; bindmcrep_(integer_binder) = MCR_SORT_SIGNED | alignof_toplevel_auto; double_pad_binder = gentempvarwithname(te_double, GAP, "PadBinder"); bindstg_(double_pad_binder) |= b_spilt; bindmcrep_(double_pad_binder) = MCR_SORT_STRUCT | MCR_ALIGN_DOUBLE | 0; active_binders = NULL; loopinfo.breaklab = loopinfo.contlab = NOTINLOOP; switchinfo.endcaselab = switchinfo.defaultlab = NOTINSWITCH; structretlab = NOTALABEL; #ifdef EXTENSION_VALOF valofinfo.binders = NULL; valofinfo.lab = NULL; valofinfo.r = 0; #endif top_block = start_new_basic_block(nextlabel()); procflags = 0; cg_infobodyflag = 0; cg_current_cmd = (Cmd *)DUFF_ADDR; usedregs = usedfpregs = NULL; nusedregs = nusedfpregs = 0; spareregs = sparefpregs = 0; nreservedregs = 0; } static void forcetostore(BindList *bl) { for (; bl != NULL; bl = bl->bindlistcdr) { Binder *b = bl->bindlistcar; /* Force all user-visible variables in bl to be in store, so that longjmp by register jamming has the pcc semantics. */ if (!isgensym(bindsym_(b))) bindxx_(b) = GAP; } } void cg_topdecl2(BindList *local_binders, BindList *regvar_binders) { BindList *split_binders = NULL, *invariant_binders = cse_eliminate(); /* Corrupt regvar_binders and local_binders to get */ /* a spill_order list for allocate_registers() */ drop_local_store(); /* what loopopt used */ split_binders = splitranges(local_binders, regvar_binders); drop_local_store(); lose_dead_code(); /* before regalloc */ if ((procflags & BLKSETJMP) && (feature & FEATURE_UNIX_STYLE_LONGJMP)) { forcetostore(local_binders); if (!(feature & FEATURE_LET_LONGJMP_CORRUPT_REGVARS)) forcetostore(regvar_binders); } allocate_registers( (BindList *)nconc((List *)invariant_binders, nconc((List *)split_binders, nconc((List *)local_binders, (List *)regvar_binders)))); drop_local_store(); /* what regalloc used */ phasename = "machinecode"; /* If (after register allocation etc) an argument is left active in */ /* memory (rather than being slaved in a register) I will do the full */ /* entry sequence. Force this by setting PROC_ARGPUSH in that case. */ /* Note that PROC_ARGADDR will thereby imply PROC_ARGPUSH, but they are */ /* different in that PROC_ARGADDR suppresses tail recursion (flowgraph.c)*/ /* Also if a big stack frame is needed I tell xxxgen.c to be cautious. */ if (greatest_stackdepth > 256) procflags |= PROC_BIGSTACK; { BindList *fb = argument_bindlist; for (; fb != NULL; fb = fb->bindlistcdr) { Binder *b1 = fb->bindlistcar; if (bindxx_(b1) == GAP) procflags |= PROC_ARGPUSH; } } /* Now, also set PROC_ARGPUSH if debugging of local variables is */ /* requested -- this will ensure that FP is set up. */ /* N.B. We could probably optimise this if no vars spill, i.e. the */ /* debugger *probably* does not need FP, but why bother?? */ if (usrdbg(DBG_VAR) && dbg_needsframepointer()) procflags |= PROC_ARGPUSH; /* This is the place where I put tables into the output stream for use */ /* by debugging tools - here are the names of functions. */ #ifndef TARGET_IS_ARM cg_fnname_offset_in_codeseg = (feature & FEATURE_SAVENAME) ? codeseg_function_name(currentfunction.symstr, currentfunction.argwords) : -1; show_entry(currentfunction.symstr, currentfunction.xrflags); #else /* This work is now done in arm/gen.c so that fn names are only dumped */ /* for functions which have stack frames. */ cg_fnname_offset_in_codeseg = -1; #endif linearize_code(); dbg_xendproc(currentfunction.fl); show_code(currentfunction.symstr); if (cgstate.block_cur > max_block) max_block = cgstate.block_cur; if (cgstate.icode_cur > max_icode) max_icode = cgstate.icode_cur; } /* After all code has been generated, we inspect it to remove b_addrof from binders which are not actually address-taken. This happens with arguments to inline functions, where eg __inline f(int *p) { *p = 1; } f(&x); turns into x = 1 but x has been marked address-taken. We go to this trouble in order to avoid the aliasing implications of address-taken. */ #define b_vk_addressed b_maybeinline #define b_really_addresstaken b_fnconst static void check_addrof2(BindList *bl) { for (; bl != NULL; bl = bl->bindlistcdr) if (bindstg_(bl->bindlistcar) & (b_vk_addressed|b_really_addresstaken)) syserr("check_addrof2"); } static void clear_addrof2(BindList *bl) { for (; bl != NULL; bl = bl->bindlistcdr) { Binder *b = bl->bindlistcar; if (bindstg_(b) & b_really_addresstaken) /* Address actually taken: leave addrof on the binder if it's there (need not be). */ bindstg_(b) &= ~b_really_addresstaken; /* Marked address taken, but address not in fact taken. Clear the mark. */ else if (bindstg_(b) & b_addrof) { bindstg_(b) &= ~b_addrof; if (debugging(DEBUG_CG)) cc_msg("Removing address-taken from $b:%p\n", b, b); } } } static void spill_addrof(BindList *bl) { for (; bl != NULL; bl = bl->bindlistcdr) { Binder *b = bl->bindlistcar; if (bindstg_(b) & (b_addrof | b_spilt | b_vk_addressed)) { if (bindstg_(b) & b_addrof) bindstg_(b) &= ~(b_spilt | b_vk_addressed); else bindstg_(b) &= ~b_vk_addressed; bindxx_(b) = GAP; } } } static void correct_addrof(BindList *local_binders, BindList *regvar_binders) { BindList *bl; BlockHead *b; check_addrof2(local_binders); check_addrof2(regvar_binders); for (b = top_block; b != NULL; b = blkdown_(b)) { int32 n = blklength_(b); Icode *ip = blkcode_(b); for (; --n >= 0; ip++) if ((ip->op & J_TABLE_BITS) == J_ADCONV) bindstg_(ip->r3.b) |= b_really_addresstaken; else if (vkformat(ip->op)) bindstg_(ip->r3.b) |= b_vk_addressed; } clear_addrof2(local_binders); clear_addrof2(regvar_binders); /* Now propagate address taken-ness across all args (unless register) */ for (bl = argument_bindlist; bl != NULL; bl = bl->bindlistcdr) { Binder *b = bl->bindlistcar; if (bindstg_(b) & b_addrof) /* Furthermore since in that case I will always need to write arguments */ /* in place on that stack it makes sense to use a full entry sequence. */ /* This of course must, in general, kill tail recursion optimisation. */ { procflags |= PROC_ARGADDR; for (bl = argument_bindlist; bl != NULL; bl = bl->bindlistcdr) { b = bl->bindlistcar; if (!(bindstg_(b) & bitofstg_(s_register))) bindstg_(b) |= b_addrof; } break; } } spill_addrof(local_binders); spill_addrof(regvar_binders); } void cg_topdecl(TopDecl *x, FileLine fl) { if (x == NULL || h0_(x) != s_fndef) syserr(syserr_cg_unknown, x == NULL ? 0L : (long)h0_(x)); { Binder *b = x->v_f.fn.name; SynBindList *formals = x->v_f.fn.formals; Cmd *body = x->v_f.fn.body; Symstr *name = bindsym_(b); TypeExpr *t = prunetype(bindtype_(b)), *restype; int32 resrep, old_profile_option = 0; fl.p = dbg_notefileline(fl); currentfunction.fl = fl; /* Object module generation may want to know if this module defines main() so that it can establish an entry point. Also while defining main() we should ensure that return; is mapped onto return 0; N.B. this latter really be done so that regalloc can warn first!! */ if (name == mainsym && (bindstg_(b) & bitofstg_(s_extern)) != 0) defining_main = has_main = YES; else defining_main = NO; /* disable profiling for compiler generated functions, vtables included */ if (bindstg_(b) & b_generated) { old_profile_option = var_profile_option; var_profile_option = 0; } if (h0_(t)!=t_fnap) { syserr(syserr_cg_topdecl); return; } procauxflags = typefnaux_(t).flags; topdec_init(); restype = prunetype(typearg_(t)); resrep = mcrepoftype(restype); currentfunction.nresultregs = 0; currentfunction.baseresultreg = GAP; result_variable = NULL; if ((resrep & MCR_SORT_MASK) == MCR_SORT_STRUCT) { if (returnsstructinregs_t(t)) { currentfunction.baseresultreg = R_P1result; currentfunction.nresultregs = (int)(((resrep & MCR_SIZE_MASK) + MEMCPYQUANTUM - 1)/ MEMCPYQUANTUM); } else { /* If a function returns a structure result I give it a hidden extra */ /* first argument that will point to where the result must be dumped. */ result_variable = currentfunction.structresult; if (result_variable == 0) syserr(syserr_cg_return_struct); if (usrdbg(DBG_VAR)) dbg_locvar(result_variable, cmdfileline_(body)); #ifndef TARGET_STRUCT_RESULT_REGISTER formals = mkSynBindList(formals, result_variable); #endif { TypeExpr *pt = bindtype_(result_variable); Binder *b = gentempbinder(pt); set_local_vregister(b, mcrepoftype(pt), 0); result_temporary = b; } } } else if ((resrep & MCR_SIZE_MASK) != 0) { int32 resmode = resrep & MCR_SORT_MASK; RegSort rsort = resmode != MCR_SORT_FLOATING ? INTREG : resrep == MCR_SORT_FLOATING+4 ? FLTREG : DBLREG; currentfunction.baseresultreg = V_Presultreg(rsort); } /* Here is a ugly mess - 'formals' has SynAlloc store, which is */ /* corrupted by drop_local_store(). It needs copying for both for the */ /* use below (PROC_ARGPUSH) and for its use in regalloc.c. */ argument_bindlist = (BindList *)binderise(formals); if (usrdbg(DBG_VAR)) { /* for the basic block started by J_ENTER in cg_bindargs() */ current_env = (BindListList *) binder_cons2(0, argument_bindlist); } currentfunction.argwords = cg_bindargs(argument_bindlist, x->v_f.fn.ellipsis); currentfunction.symstr = bindsym_(b); cg_cmd(body); #ifdef never /* the following code is maybe what AM would like */ if (!deadcode && !isprimtype_(restype, s_void)) cc_warn(cg_warn_implicit_return, symname_(name)); #endif /* we know here that fl.f != 0 */ if (!cg_infobodyflag) { #ifdef TARGET_HAS_PROFILE if (profile_option) emitfl(J_COUNT, fl); #endif if (usrdbg(DBG_PROC)) emit(J_INFOBODY, GAP, GAP, 0); cg_infobodyflag = 1; } if (usrdbg(DBG_LINE)) emitfl(J_INFOLINE, fl); cg_return(0, !isprimtype_(restype, s_void)); drop_local_store(); phasename = "loopopt"; /* Force inline functions to have internal linkage... the argument as to */ /* why this is a Good Thing is long and complicated... */ currentfunction.xrflags = bindstg_(b) & (bitofstg_(s_static) | bitofstg_(s_inline)) ? xr_code+xr_defloc : xr_code+xr_defext; correct_addrof(local_binders, regvar_binders); if ( !(bindstg_(b) & bitofstg_(s_inline)) || usrdbg(DBG_ANY) || !Inline_Save(b, local_binders, regvar_binders)) { cg_topdecl2(local_binders, regvar_binders); symext_(currentfunction.symstr)->usedregs = regmaskvec; } /* enable profile option, if necessary */ if (old_profile_option) var_profile_option = old_profile_option; } } void cg_init(void) { obj_init(); /* MUST precede codebuf_init() */ Inline_Init(); regalloc_init(); codebuf_init(); mcdep_init(); /* code for system dependent module header */ datasegbinders = (BindList *)global_cons2(SU_Other, 0, datasegment); max_icode = 0; max_block = 0; cse_init(); splitrange_init(); has_main = NO; #ifndef NO_OBJECT_OUTPUT if (objstream) obj_header(); #endif #ifndef NO_ASSEMBLER_OUTPUT if (asmstream) asm_header(); #endif dbg_init(); show_entry(bindsym_(codesegment), xr_code+xr_defloc); /* nasty here */ show_code(bindsym_(codesegment)); /* nasty here */ } void cg_reinit(void) { codebuf_reinit(); } void cg_tidy(void) { Inline_Tidy(); codebuf_tidy(); if (debugging(DEBUG_STORE)) { cc_msg("Max icode store %ld, block heads %ld bytes\n", (long)max_icode, (long)max_block); } regalloc_tidy(); cse_tidy(); /* Pad data segment to at least 4 byte multiple (to flush vg_wbuff), */ /* but pad to multiple of alignof_max if bigger. */ /* Do this irrespective of object module format. */ { int32 alignto = alignof_max > 4 ? alignof_max : 4; padstatic(alignto); #ifdef TARGET_HAS_BSS padbss(alignto); #endif #ifdef CONST_DATA_IN_CODE SetDataArea(DS_Const); padstatic(alignto); SetDataArea(DS_ReadWrite); #endif } /* maybe do dreverse(CodeXrefs+DataXrefs here one day? */ #ifndef NO_OBJECT_OUTPUT if (objstream) obj_trailer(); #endif #ifndef NO_ASSEMBLER_OUTPUT if (asmstream) asm_trailer(); #endif localcg_tidy(); } /* End of cg.c */
stardot/ncc
cfe/sem.h
/* * sem.c: semantic analysis phase of C compiler * Copyright (C) Codemist Ltd, 1988-1992. * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Advanced RISC Machines Ltd., 1990-1992. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _sem_h #define _sem_h #ifndef _defs_LOADED # include "defs.h" #endif #define isvolatile_expr(e) (isvolatile_type(typeofexpr(e))) #define isunaligned_expr(e) (isunaligned_type(typeofexpr(e))) #ifdef PASCAL /*ECN*/ #define ptrtotype_(t) ((TypeExpr *)syn_list5(t_content, (t), 0, 0, \ syn_list2(s_content, 0))) #else #define ptrtotype_(t) mk_typeexpr1(t_content, t, 0) #endif /* The next line is a type-check cheat -- casts of int to (TypeExpr *) !! */ #define primtype_(m) mk_typeexpr1(s_typespec, (TypeExpr *)(IPtr)(m), 0) #define primtype2_(m,b) \ mk_typeexpr1(s_typespec, (TypeExpr *)(IPtr)(m), (Expr *)(b)) #define isprimtype_(x,s) (h0_(x) == s_typespec && \ (typespecmap_(x) & bitoftype_(s))) #define isprimtypein_(x,set) (h0_(x) == s_typespec && \ (typespecmap_(x) & (set))) #define isclasstype_(x) isprimtypein_(x, CLASSBITS) #define isclassorenumtype_(x) isprimtypein_(x, ENUMORCLASSBITS) #define issimpletype_(x) (h0_(x) == s_typespec && \ !(typespecmap_(x) & CLASSBITS)) /* Note, in contexts where default promotions have been done, that */ /* the s_char/s_enum bits in the following tests are irrelevant. */ /* Apr 92: see the now finer grain coerceunary() for C++ (and C). */ #define INTEGRALTYPEBITS (bitoftype_(s_bool)|bitoftype_(s_char)|\ bitoftype_(s_int)|bitoftype_(s_enum)) #define ARITHTYPEBITS (INTEGRALTYPEBITS|bitoftype_(s_double)) #define isintegraltype_(x) isprimtypein_(x, INTEGRALTYPEBITS) #define isarithtype_(x) isprimtypein_(x, ARITHTYPEBITS) #define isfntype(x) (h0_(princtype(x)) == t_fnap) #define istypevar(x) (h0_(princtype(x)) == t_unknown) bool isvoidtype(TypeExpr *t); bool isptrtovoidtype(TypeExpr *t); bool isnullptrconst(const Expr *e); extern Expr *errornode; extern void typeclash(AEop op); extern bool issimplevalue(Expr *e); extern bool issimplelvalue(Expr *e); extern Expr *ensurelvalue(Expr *e, AEop op); extern TypeExpr *prunetype(TypeExpr *t), *princtype(TypeExpr *t); extern SET_BITMAP qualifiersoftype(TypeExpr *t); SET_BITMAP recursivequalifiers(TypeExpr *x); extern TypeExpr *mkqualifiedtype(TypeExpr *t, SET_BITMAP qualifiers); extern bool isvolatile_type(TypeExpr *x); extern bool isunaligned_type(TypeExpr *x); extern bool isbitfield_type(TypeExpr *x); extern TypeExpr *unbitfield_type(TypeExpr *x); extern TagBinder *isclassenumorref_type(TypeExpr *x); extern bool pointerfree_type(TypeExpr *t); extern TypeExpr *typeofexpr(Expr *x); extern SET_BITMAP typeofenumcontainer(TagBinder *tb); extern bool structfield(ClassMember *l, int32 sort, StructPos *p); /* Used to iterate over the fields of a structure (union). Returns fields in p describing the head field in l, and updates the internal fields in p to point past that element. */ extern void structpos_init(StructPos *p, TagBinder *tb); /* Prepare a StrucPos object for use by structfield */ extern int32 sizeofclass(TagBinder *b, bool *padded); extern int32 sizeoftypenotepadding(TypeExpr *x, bool *padded); #define sizeoftype(t) sizeoftypenotepadding(t, NULL) extern bool sizeoftypelegal(TypeExpr *x); /* !is_incompletetype, really */ extern int32 alignoftype(TypeExpr *x); /* equivtype functions return 0=differ, 1=equivalent for C, 2=identical */ extern int equivtype(TypeExpr *t1, TypeExpr *t2); extern int qualfree_equivtype(TypeExpr *t1, TypeExpr *t2); extern int widened_equivtype(TypeExpr *t1, TypeExpr *t2); extern TypeExpr *modify_formaltype(TypeExpr *t); extern TypeExpr *widen_formaltype(TypeExpr *t); extern TypeExpr *promoted_formaltype(TypeExpr *t); extern TypeExpr *modify_actualtype(TypeExpr *t, const Expr* e); extern Expr *mkintconst(TypeExpr *te, int32 n, Expr *e); extern Expr *fixflt(Expr *e); extern void moan_nonconst(Expr *e, msg_t nonconst_msg, msg_t nonconst1_msg, msg_t nonconst2_msg); extern Expr *coerceunary(Expr*); extern Expr *mkintegral(AEop op, Expr *a); extern Expr *mktest(AEop opreason, Expr *a); extern Expr *mkunary(AEop op, Expr *a); extern Expr *mkbinary(AEop op, Expr *a, Expr *b); extern Expr *mkfnap(Expr *e, ExprList *l); extern Expr *mkcast(AEop op, Expr *e, TypeExpr *tr); extern Expr *skip_invisible_or_cast(Expr *e); extern Expr *skip_invisible(Expr *e); Expr *mk1fnap(Expr *fn, ExprList *args); extern Expr *rooted_path(Expr *path, SET_BITMAP qualifiers, Expr *root); extern Expr *mkfieldselector(AEop op, Expr *e, ClassMember *mem); extern Expr *mkcond(Expr *a, Expr *b, Expr *c); extern void sem_init(void); #ifdef CPLUSPLUS extern TypeExpr *core_type(TagBinder *b); extern TagBinder *core_class(TagBinder *b); extern VfnList *vfn_list(TagBinder *cl); extern bool typehasctor(TypeExpr *t); extern Expr *thisify(Expr *e); extern ClassMember *type_derived_from(TypeExpr *tr, TypeExpr *te); extern Expr *mkopap(AEop op, TagBinder *tb, Expr *a, ExprList *l); extern Binder *class_has_conversion(TagBinder *b, TypeExpr *t, int pick_best); extern Binder *class_has_ctor(TagBinder *b, TypeExpr *t, const Expr *e, int pick_best); extern Binder *class_has_ctor_1(TagBinder *b, TypeExpr *t, const Expr *e, int pick_best, bool silent); extern Expr *user_conversion(Expr *e, TagBinder *b, TypeExpr *t); extern Expr *commacons(Expr *a, Expr *b); extern Expr *mkcommalist(Expr *a, ...); extern Expr *vbase_init(TagBinder *cl, Expr *var); extern Expr *vtab_init(TagBinder *cl, Expr *var); extern bool isarraytype(TypeExpr *t, TypeExpr **elmtype); extern int32 arraysize(TypeExpr *t, TypeExpr **elmtype); /* @@@ should return size_t */ extern Expr *mkctor_v(Expr *b, ExprList *init); extern Expr *mkctor_t(TypeExpr *t, ExprList *init); extern Expr *mkdtor_v(Expr *e); extern Expr *mkdtor_v_list(SynBindList *d); extern Cmd *mkthrow(FileLine fl, Expr *e); extern Cmd *mkexpop(FileLine fl); extern Cmd *mkextop(FileLine fl); extern Expr *mkexpush(FileLine fl, Expr* typeid, Expr* size); extern Expr *array_of_class_map_expr(Expr *p, Expr *nelts, int32 stride, Expr *mapfn); extern Expr *array_of_class_map(Expr *p, int32 nelts, int32 stride, bool up, Expr *mapfn, bool twoargmapfn); extern Expr *array_of_class_copy(Expr *to, Expr *fm, Expr *frmlimit, int32 stride, Binder *mapfn); extern Expr *mknew(TypeExpr *newt, TypeExpr *t, Binder *newgeneric, Expr* nelts, ExprList* placement, ExprList* init, bool forceglobal); extern Expr *mkdelete(Expr* e, TypeExpr* t, bool isarray, Binder *delgeneric, bool forceglobal); extern bool cfront_allows_pointercast(TypeExpr *te, TypeExpr *tr); extern TypeExpr *lvalue_type(Expr *x); extern void fixup_template_arg_type(TypeExpr *f, ClassMember *actuals); extern ScopeSaver globalize_template_arg_binders(ScopeSaver f, ExprList *a); extern bool contains_typevars(TypeExpr *t); extern bool has_template_parameter(ScopeSaver tformals); extern TypeExpr *type_deduction(TypeExpr *fntype, ExprList *args, ExprList *actuals, ScopeSaver *tformals, bool silent, bool *failed); extern TagBinder *class_template_reduce(TagBinder *primary, TagBindList *instances, ScopeSaver tactuals); extern void check_temp_arg_linkage(Expr *e); extern void check_temp_type_arg_linkage(TypeExpr *t); extern BindList *temp_reduce(BindList *temps, ExprList *l, ExprList *tactuals, Binder *bgeneric); extern int env_size(Binder *b); extern bool is_an_instance(BindList *ins, Binder *b); extern ScopeSaver dup_env_actuals(ScopeSaver tformals, ExprList *a); extern void add_instance(Binder *b, BindList **bl, bool su); extern bool is_dependent_type(TypeExpr *t); /* nasty: routines for overload.c */ extern Symstr *ovld_add_memclass(Symstr *sv, TagBinder *scope, bool staticfn); extern Symstr *ovld_instance_name(Symstr *sv, TypeExpr *t); extern Symstr *ovld_instance_name_1(const char *name, TypeExpr *t); extern Symstr *ovld_tmptfn_instance_name(Symstr *sv, ScopeSaver f); extern Expr *ovld_picknullary(Binder *bgeneric); extern List *mk_candidates(BindList *, int, int, List *); extern List *mk_operator_candidates(AEop, TypeExpr *, TypeExpr *, List *); extern Binder *ovld_reduce(Binder *b, List *, ExprList *l, ExprList *ll); extern Binder *ovld_resolve(Binder *b, BindList *alternatives, ExprList *l, ExprList *ll, bool silent); extern Symstr *specialized_name_of(TagBinder *tmptb); extern bool is_operator_name(Symstr *opname); extern Symstr *ovld_template_app(Symstr *sv, ScopeSaver f, ExprList *a); extern Symstr *ovld_function_template_name(Symstr *sv, TypeExpr *t); extern Symstr *operator_name(AEop op); extern Symstr *conversion_name(TypeExpr *t); extern String *exception_name(TypeExpr *t); extern Expr *allowable_boolean_conversion(Expr *); extern bool comparable_templates(TagBinder *tb1, TagBinder *tb2); extern void merge_default_template_args(ScopeSaver new, TagBinder *tempclass, Binder *tempfn); /* even nastier: really defined in xsyn.c... FIX LATER */ extern void diagnose_access(Symstr *sv, TagBinder *scope); extern Expr *cpp_mkbinaryorop(AEop, Expr*, Expr*); #else #define commacons(a,b) 0 #define core_type(b) 0 #define core_class(b) (b) #define vfn_list(cl) 0 #define typehasctor(t) 0 #define thisify(e) 0 #define type_derived_from(tr, te) 0 #define mkopap(opname, tb, a, l) 0 #define exists_conversion_sequence_from(tfm,tto) 0 #define mkfnap_cpp(e, l, curried, let, firstarg) (e) #define add_instance(a,b,c) ((void)0) #define is_dependent_type(a) 0 #define merge_default_template_args(a,b,c) 0 #define mkctor_v(b, init) 0 #define mkdtor_v(e) 0 #define mkdtor_v_list(d) 0 #define mkthrow(fn, e) 0 #define mkexpop(fl) 0 #define mkextop(fl) 0 #define mkexpush(fl,ti,ts) 0 #define cfront_allows_pointercast(te, tr) 0 /* nasty: routines for overload.c */ #define ovld_add_memclass(sv, scope, staticfn) 0 #define ovld_instance_name(sv, t) 0 #define ovld_resolve(b, alternatives, l, ll, silent) 0 #define operator_name(op) 0 #define conversion_name(t) 0 #define exception_name(t) 0 #define contains_typevars(t) 0 #define has_template_parameter(t) 0 #define type_deduction(a,b,c,d,e,f) (a) #define class_template_reduce(a,b,c) (a) #define fixup_template_arg_type(a,b) ((void)0) #define check_temp_type_arg_linkage(a) 0 #define check_temp_arg_linkage(a) 0 #define temp_reduce(a,b,c,d) a #define is_an_instance(a,b) 0 #define globalize_template_arg_binders(a,b) 0 #define specialized_name_of(a) 0 #endif #endif /* end of cfe/sem.h */
stardot/ncc
mip/aoutobj.c
/* * C compiler file mip/aoutobj.c * Copyright (C) <NAME>, 1987. * Copyright (C) Codemist Ltd., 1988. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 14x * Checkin $Date$ * Revising $Author$ */ /* Memo: AM is converting this file into a generic (target machine/os */ /* parameterised) a.out formatter. */ /* Note that #ifdef TARGET_IS are soon to become procedural interfaces. */ /* However, do the 88000 or 29000 32 from 64 bit references first. */ /* Memo: currently this formatter dies with calls of (data cast to code). */ #include "globals.h" /* for "target.h" via "host.h" */ /* * "target.h" (via globals.h) must be included before "aout.h", since our * private version of a header defining the a.out format is parameterised * wrt the type of target machine involved. If we are not cross compiling * and a host specific <a.out.h> is available it might be better to use * that rather than "aout.h". */ #ifdef TARGET_IS_AIH324 # define TARGET_IS_SPARC 1 /* rather a lie */ #endif #ifndef TARGET_HAS_BSS # define bss_size 0 #endif #ifndef __STDC__ #include <a.out.h> #include <strings.h> #include <sys/types.h> #define SEEK_SET 0 #else #include "aout.h" #include <string.h> #endif #define MAXNUMSYMS ((int32)1 << 24) /* limited by bit field in a.out.h */ #include "mcdep.h" /* #include "mcdpriv.h" */ #include "store.h" #include "codebuf.h" #include "xrefs.h" #include "errors.h" #include "builtin.h" /* All the code from all functions is buffered until the end of */ /* compilation so that local references can be resolved to avoid the */ /* linker bombing. AM vaguely remembers weasel words about a.out which */ /* might fix this. */ static int32 obj_fwrite_cnt; static void obj_fwrite(VoidStar buff, int32 n, int32 m, FILE *f) { if (debugging(DEBUG_OBJ) && 0) { int i; fprintf(f, "%.6lx:", (long)obj_fwrite_cnt); obj_fwrite_cnt += n*m; for (i=0; i<n*m; i++) fprintf(f, " %.2x", ((unsigned char *)buff)[i]); fprintf(f, "\n"); } else fwrite(buff, (size_t)n, (size_t)m, f); } void obj_common_start(Symstr *name) { /* No support in a.out for common definitions - just the block name as an exported label in the normal data area. */ labeldata(name); obj_symref(name, xr_data+xr_defext, data_size()); } void obj_common_end(void) { } /* * The compiler works quite happily on most machines, generating code * in the host byte sex. But this seems to be not quite what ald * expects on the SUN. Hence the frig below to explicitly swap the * byte sex on various bits of the output. */ #ifdef sun static void obj_specialfwrite(VoidStar buff, int32 n, int32 m, FILE *f) { m *= n; for (n = 0; n < m; n += 4) { char *p = ((char *)buff) + n; fputc(p[3], f); fputc(p[2], f); fputc(p[1], f); fputc(p[0], f); } } #define if_sun_swap(a, b) { char tmp = (a); (a) = (b); (b) = tmp; } #else #define obj_specialfwrite obj_fwrite #define if_sun_swap(a, b) #endif FILE *objstream; /* offset of first string in the string table section */ #define FIRST_STR 4 #define MAXEXTNAMELEN 256 /* * Imports: codebase, dataloc */ typedef struct StabList { struct StabList *next; struct nlist nlist; } StabList; static StabList *obj_stablist; static int32 ncoderelocs, ndatarelocs, obj_symcount, obj_stabcount; static int32 datastart; ExtRef *obj_symlist; CodeXref *codexrefs; /* DataXref *dataxrefs; -- now exported from codebuf.c as data.xrefs. */ DataXref *dbgxrefs; #ifdef COMPILING_ON_SMALL_MEMORY /* Buffer code in a temporary file */ FILE *obj_tmpfile; ____notyetfinished; #else /* !COMPILING_ON_SMALL_MEMORY */ /* Buffer code in memory */ #define MAXCODESEGS 256 /* AM: @@@ codesize seems simply to duplicate 'codebase' (q.v.). */ static int32 (*(xcodevec[MAXCODESEGS]))[CODEVECSEGSIZE], codesize; #define xcode_inst_(q) (*xcodevec[(q)>>(CODEVECSEGBITS+2)]) \ [((q)>>2)&(CODEVECSEGSIZE-1)] #ifdef TARGET_HAS_HALFWORD_INSTRUCTIONS /* A fix up for machines (like Clipper) which may have unaligned relocated */ /* words in opcodes. NB: needs improving for 386 (use memcpy to align?). */ /* (Or make xcode_inst_ optionally a halfword/byte vector as code_inst_). */ /* Also worry about cross compilation and byte sex here one day. */ # ifdef TARGET_IS_LITTLE_ENDIAN static void set_code(int32 q, int32 n) { if ((q&3)==0) xcode_inst_(q) = n; else { xcode_inst_(q) = ((xcode_inst_(q))&0xffff)+(n<<16); xcode_inst_(q+2) = ((xcode_inst_(q+2))&0xffff0000)+((unsigned32)n>>16); } } static int32 get_code(int32 q) { return ((q&3)==0 ? xcode_inst_(q) : ((xcode_inst_(q+2))<<16) + (((unsigned32)xcode_inst_(q))>>16)); } # endif # ifdef TARGET_IS_BIG_ENDIAN static void set_code(int32 q, int32 n) { if ((q&3)==0) xcode_inst_(q) = n; else { xcode_inst_(q) = ((xcode_inst_(q))&0xffff0000)+((unsigned32)n>>16); xcode_inst_(q+2) = ((xcode_inst_(q+2))&0xffff)+(n<<16); } } static int32 get_code(int32 q) { return ((q&3)==0 ? xcode_inst_(q) : ((xcode_inst_(q))<<16) + (((unsigned32)xcode_inst_(q+2))>>16)); } # endif #else # define get_code(q) xcode_inst_(q) # define set_code(q,n) xcode_inst_(q)=n #endif #define FileOffsetOfSym(x) \ (x->extoffset + ((x->extflags & xr_code) ? 0 : \ (x->extflags & xr_data) ? datastart : datastart+data_size())) static void buffer_code(int32 *src, int32 nwords) { int32 *p; for (p = src; nwords > 0; --nwords) { int32 hi = codesize >> (CODEVECSEGBITS+2); int32 lo = (codesize >> 2) & (CODEVECSEGSIZE-1); if (lo == 0) { /* need another segment */ if (hi >= MAXCODESEGS) cc_fatalerr(aout_fatalerr_toobig); xcodevec[hi] = (int32(*)[CODEVECSEGSIZE]) GlobAlloc( SU_Other, sizeof(*xcodevec[0])); } (*xcodevec[hi])[lo] = *p++; codesize += 4; } } static void relocate_code_refs_to_locals(void) { /* This proc. should soon callback to a routine in gen.c: */ CodeXref *cxr; for (cxr = codexrefs; cxr != NULL; cxr = cxr->codexrcdr) { Symstr *s = cxr->codexrsym; ExtRef *x = symext_(s); int32 codeoff = cxr->codexroff & 0xffffff; int32 w = get_code(codeoff); switch (cxr->codexroff & 0xff000000) { #ifdef TARGET_IS_SPARC case X_absreloc: if (x->extflags & (xr_defloc | xr_defext)) { /* * code ref to local code or data via address literal... * (or clipper/vax absolute 32 bit branch). * Unix linker cannot cope with filling in the address literal * with the value of a locally defined symbol: we have to convert * it into a reference relative to v$codeseg or v$dataseg. * AM: note that we do take notice of the old value here. */ set_code(codeoff, w + FileOffsetOfSym(x)); } break; case X_PCw30reloc: if (x->extflags & (xr_defloc | xr_defext)) { /* defined in this compilation unit so relocate... */ set_code(codeoff, (w & 0xc0000000) | (((x->extoffset-codeoff) >> 2) & 0x3fffffff)); } if (debugging(DEBUG_OBJ)) cc_msg("Fixup %.8lx extoff=%.8lx, codeoff=%.8lx, make %.8lx\n", (long)w, (long)x->extoffset, (long)codeoff, (long)get_code(codeoff)); break; case X_DataAddr: set_code(codeoff, w & 0xffc00000); /* Remove the immediate field */ break; case X_DataAddr1: set_code(codeoff, w & 0xffffe000); /* Remove the immediate field */ break; #else case X_PCreloc: /* pcrelative code ref (presumed to) to code. */ /* @@@ cast of array to code pointer causes the following */ /* syserr(). Needs fixing properly. */ if (!(x->extflags & xr_code)) syserr(syserr_aout_reloc); if (x->extflags & (xr_defloc | xr_defext)) { /* defined in this compilation unit so relocate... */ /* @@@ AM: before 'rationalising' this code, it is IMPORTANT to build */ /* in the 29000 or 88000 32 bits in 64 bits relocation modes. */ /* AM: note that in all the following cases any offset in the code is */ /* ignored and simply overwritten. Change this one day? */ #ifdef TARGET_IS_ARM /* On the ARM relocate a B or BL; offset in WORDs; prefetch 8 bytes. */ #define obj_codeupdate(n) \ set_code(codeoff, (w & 0xff000000) | (((n)-8) >> 2) & 0x00ffffff) #endif #ifdef TARGET_IS_88000 /* For the 88000 use no prefetch but word offset. */ #define obj_codeupdate(n) \ set_code(codeoff, (w & 0xfc000000) | ((n) >> 2) & 0x03ffffff); #endif #ifdef TARGET_IS_I860 /* /* (check) For the I860 use no prefetch but word offset. */ #define obj_codeupdate(n) \ set_code(codeoff, (w & 0xfc000000) | ((n) >> 2) & 0x03ffffff); #endif #ifdef TARGET_IS_AMD /* For the AMD 29000 I use something which is WRONG!!! */ #define obj_codeupdate(n) \ set_code(codeoff, (w & 0xfc000000) | ((n) >> 2) & 0x03ffffff); #endif #ifdef TARGET_IS_CLIPPER /* On clipper relocate the whole 32 bit word with a byte offset. */ /* Note that the clipper version does not yet (Dec 88) use X_PCreloc. */ #define obj_codeupdate(n) \ set_code(codeoff, (w & 0) | (n) & 0xffffffff) #endif #ifdef TARGET_IS_GOULD /* On Gould relocate the whole 32 bit word with a byte offset. */ #define obj_codeupdate(n) \ set_code(codeoff, (w & 0) | (n) & 0xffffffff) #endif #ifdef TARGET_IS_68000 /* On M68K relocate the whole 32 bit word with a byte offset. */ #define obj_codeupdate(n) \ set_code(codeoff, (w & 0) | (n) & 0xffffffff) #endif #ifdef TARGET_IS_KCM /* This is a fake */ #define obj_codeupdate(n) \ set_code(codeoff, (w & 0) | (n) & 0xffffffff) #endif #ifdef obj_codeupdate obj_codeupdate(x->extoffset-codeoff); #else #error Missing a.out self-relocation code (unknown target machine). #endif } else { /* Branch to external symbol. Most Unices expect to be */ /* tight branch to self. (On the ARM, the Unix linker */ /* expects unrelocated branch to be -2 words, */ obj_codeupdate(0); } if (debugging(DEBUG_OBJ)) cc_msg("Fixup %.8lx extoff=%.8lx, codeoff=%.8lx, make %.8lx\n", (long)w, (long)x->extoffset, (long)codeoff, (long)get_code(codeoff)); break; case X_absreloc: case X_backaddrlit: /* abs ref to external */ if (x->extflags & (xr_defloc | xr_defext)) { /* * code ref to local code or data via address literal... * (or clipper/vax absolute 32 bit branch). * Unix linker cannot cope with filling in the address literal * with the value of a locally defined symbol: we have to convert * it into a reference relative to v$codeseg or v$dataseg. * AM: note that we do take notice of the old value here. */ set_code(codeoff, w + FileOffsetOfSym(x)); } break; #endif } } } static void obj_writecode(void) { int i = 0; #if (alignof_double > 4) /* TARGET_ALIGNS_DOUBLES */ if (codesize & 7) { static int32 pad[] = {0}; buffer_code(pad, 1); /* Double word aligned */ } #endif relocate_code_refs_to_locals(); #ifdef TARGET_IS_SPARC /* We need to remove bits 12, 11 and 10 from lo10 words; hence the junk in relocate_code_refs_to_locals */ #endif while ((codesize>>2) - CODEVECSEGSIZE*i > CODEVECSEGSIZE) obj_specialfwrite(xcodevec[i++], 4, CODEVECSEGSIZE, objstream); obj_specialfwrite(xcodevec[i], 4,(codesize>>2)-CODEVECSEGSIZE*i, objstream); if (ferror(objstream)) cc_fatalerr(obj_fatalerr_io_object); } #endif /* COMPILING_ON_SMALL_MEMORY */ static void obj_outsymtab(void) { ExtRef *x; StabList *p; int obj_stringpos = FIRST_STR; struct nlist n; obj_symlist = (ExtRef *)dreverse((List *)obj_symlist); /* oldest = smallest numbered first */ memset(&n, 0, sizeof(n)); /* * Output the symbol table. */ for (x = obj_symlist; x != 0; x = x->extcdr) { Symstr *s = x->extsym; int flags = x->extflags; int type; if (debugging(DEBUG_OBJ)) cc_msg("sym'%s'%lx/%x ", symname_(s), (long)x->extindex, flags); if (x->extindex >= 0) { /* not internal symbol ... */ n.n_un.n_strx = obj_stringpos; n.n_value = x->extoffset; if (flags & (xr_defloc | xr_defext)) { if (flags & xr_code) { type = N_TEXT; } else if (flags & xr_data) { type = N_DATA; n.n_value += datastart; } else { #ifdef TARGET_IS_SPARC type = N_UNDF | N_EXT; { ExtRef *y = obj_symlist; int32 base = bss_size; /* This is an appalling loop searching all symbols for the next BSS location */ while(y!=NULL) { if (y != x && y->extflags & xr_bss && y->extoffset > x->extoffset && y->extoffset < bss_size) base = y->extoffset; y=y->extcdr; } n.n_value = base - x->extoffset; } #else type = N_BSS; n.n_value += datastart+data_size(); #endif } } else { type = N_UNDF; n.n_value = (n.n_value + 3) & ~3; /* n.n_value is 0 except for pcc-style common things. */ /* Round up their size to a word multiple to ensure */ /* the assumed word alignment. */ } if (!(flags & xr_defloc)) type |= N_EXT; n.n_type = type; obj_fwrite(&n, sizeof(struct nlist), 1, objstream); obj_stringpos += strlen(symname_(s)) + 2; } } obj_stablist = (StabList *)dreverse((List *)obj_stablist); for (p = obj_stablist; p != 0; p = p->next) { char *name = p->nlist.n_un.n_name; if (name != 0) { p->nlist.n_un.n_strx = obj_stringpos; obj_stringpos += strlen(name) + 1; } if ((p->nlist.n_type & N_TYPE) == N_DATA) { p->nlist.n_value += datastart; } else if ((p->nlist.n_type & N_TYPE) == N_BSS) p->nlist.n_value += datastart+data_size(); obj_fwrite(&p->nlist, sizeof(p->nlist), 1, objstream); p->nlist.n_un.n_name = name; /* @@@ totally spurious */ } /* * Output the string table. */ /* first output the length... */ obj_fwrite(&obj_stringpos, sizeof(obj_stringpos), 1, objstream); /* then the contents of the string table */ for (x = obj_symlist; x != 0; x = x->extcdr) { Symstr *s = x->extsym; int l; char *name, extname[MAXEXTNAMELEN]; /* ...construct '_'name then write it out... */ extname[0] = '_'; if (x->extindex >= 0) { l = strlen(name = symname_(s)); if (l > (MAXEXTNAMELEN-2)) l = MAXEXTNAMELEN-2; #ifdef TARGET_IS_UNIX if (strncmp( name,"x$",2 ) != 0) { #endif strncpy(extname+1, name, l); extname[l+1] = 0; #ifdef TARGET_IS_UNIX } else { strncpy(extname, & name[2], l-2); extname[l-2] = 0; } #endif obj_fwrite(extname, 1, (int32)l+2, objstream); } } for (p = obj_stablist; p != 0; p = p->next) { char *name = p->nlist.n_un.n_name; if (name != 0) { obj_fwrite(name, 1, (int32)strlen(name)+1, objstream); } } } static int32 obj_checksym(Symstr *s) { ExtRef *x = symext_(s); if (x != 0) { int32 idx = x->extindex; int flags = x->extflags; if (flags & (xr_defloc | xr_defext)) { return (flags & xr_code) ? -N_TEXT : (flags & xr_data) ? -N_DATA : #ifdef TARGET_IS_SPARC (int)idx; /* SPARC must avoid BSS */ #else -N_BSS; #endif } return (int)x->extindex; } syserr(syserr_aout_checksym, symname_(s)); return 0; /* just to keep dataflow happy. */ } static void obj_coderelocation(void) { CodeXref *x; struct relocation_info r; ncoderelocs = 0; #ifdef TARGET_IS_SPARC codexrefs = (CodeXref*)dreverse((List*)codexrefs); #endif memset(&r, 0, sizeof(r)); for (x = codexrefs; x != NULL; x = x->codexrcdr) { Symstr *s = x->codexrsym; int sno = obj_checksym(s); r.r_address = (int)x->codexroff & 0xffffff; if (sno >= 0) { r.r_extern = 1; r.r_symbolnum = sno; } else { r.r_extern = 0; r.r_symbolnum = -sno; } switch (x->codexroff & 0xff000000) #ifdef TARGET_IS_SPARC { case X_absreloc: r.r_type = RELOC_32; r.r_addend = (sno == -N_DATA ? datastart : sno == -N_TEXT ? FileOffsetOfSym(symext_(s)) : 0) + x->codexrlitoff; obj_fwrite(&r, sizeof(r), 1, objstream); if (debugging(DEBUG_OBJ)) cc_msg("addreloc '%s' ",symname_(s)); if (debugging(DEBUG_OBJ)) cc_msg("\ r_address=%x, r_symbolnum=%x, r_extern=%d, r_type=%d, r_addend=%x, sno=%d\n", r.r_address, r.r_symbolnum, r.r_extern, r.r_type, r.r_addend, sno); ncoderelocs++; break; case X_DataAddr: r.r_type = RELOC_HI22; r.r_addend = (sno == -N_DATA ? FileOffsetOfSym(symext_(s)) : sno == -N_TEXT ? FileOffsetOfSym(symext_(s)) : 0) + x->codexrlitoff; /* If not dataseg then need to add offset */ obj_fwrite(&r, sizeof(r), 1, objstream); if (debugging(DEBUG_OBJ)) cc_msg("addreloc-hi '%s'%lx\n",symname_(s), x->codexrlitoff); if (debugging(DEBUG_OBJ)) cc_msg("\ r_address=%x, r_symbolnum=%x, r_extern=%d, r_type=%d, r_addend=%x, sno=%d\n", r.r_address, r.r_symbolnum, r.r_extern, r.r_type, r.r_addend, sno); ncoderelocs++; break; case X_DataAddr1: r.r_type = RELOC_LO10; r.r_addend = (sno == -N_DATA ? FileOffsetOfSym(symext_(s)) : sno == -N_TEXT ? FileOffsetOfSym(symext_(s)) : 0) + x->codexrlitoff; /* If not dataseg then need to add offset */ obj_fwrite(&r, sizeof(r), 1, objstream); if (debugging(DEBUG_OBJ)) cc_msg("addreloc-lo '%s'%lx\n",symname_(s), x->codexrlitoff); if (debugging(DEBUG_OBJ)) cc_msg("\ r_address=%x, r_symbolnum=%x, r_extern=%d, r_type=%d, r_addend=%x, sno=%d\n", r.r_address, r.r_symbolnum, r.r_extern, r.r_type, r.r_addend, sno); ncoderelocs++; break; case X_PCw30reloc: r.r_type = RELOC_WDISP30; r.r_addend = - r.r_address; if (debugging(DEBUG_OBJ)) cc_msg("W30reloc '%s'\n",symname_(s)); if (debugging(DEBUG_OBJ)) cc_msg("\ r_address=%8x, r_symbolnum=%6x, r_extern=%d, r_type=%d, r_addend=%x, sno=%d\n", r.r_address, r.r_symbolnum, r.r_extern, r.r_type, r.r_addend, sno); if (sno >= 0) { /* really external */ obj_fwrite(&r, sizeof(r), 1, objstream); ncoderelocs++; } break; default: syserr(syserr_aout_reloc1, (long)x->codexroff); break; } #else { case X_PCreloc: /* PC rel ref to external */ r.r_pcrel = 0; /* not yet relocated PC-relative */ #ifdef TARGET_IS_ARM r.r_length = 3; /* ARM Branch */ #else r.r_length = 2; /* long */ #endif if (debugging(DEBUG_OBJ)) cc_msg("pcreloc '%s'",symname_(s)); if (debugging(DEBUG_OBJ)) cc_msg("\ r_address=%8x, r_symbolnum=%6x, r_pcrel=%d, \ r_length=%d, r_extern=%d, r_neg=%d sno=%d\n", r.r_address, r.r_symbolnum, r.r_pcrel, r.r_length, r.r_extern, r.r_neg, sno); if (sno >= 0) { /* really external */ obj_fwrite(&r, sizeof(r), 1, objstream); ncoderelocs++; } break; case X_absreloc: case X_backaddrlit: /* abs ref to external */ r.r_pcrel = 0; r.r_length = 2; /* long */ obj_fwrite(&r, sizeof(r), 1, objstream); if (debugging(DEBUG_OBJ)) cc_msg("addreloc '%s' ",symname_(s)); if (debugging(DEBUG_OBJ)) cc_msg("\ r_address=%8x, r_symbolnum=%6x, r_pcrel=%d, \ r_length=%d, r_extern=%d, r_neg=%d sno=%d\n", r.r_address, r.r_symbolnum, r.r_pcrel, r.r_length, r.r_extern, r.r_neg, sno); ncoderelocs++; break; default: syserr(syserr_aout_reloc1, (long)x->codexroff); break; } #endif } } static int32 obj_datarelocation(DataXref *x, int32 offset) { struct relocation_info r; int32 n = 0; memset(&r, 0, sizeof(r)); #ifndef TARGET_IS_SPARC r.r_length = 2; /* long */ #else r.r_type = RELOC_32; #endif for (; x != NULL; x = x->dataxrcdr, n++) { Symstr *s = x->dataxrsym; int sno = obj_checksym(s); /* all data relocs are X_backaddrlit (abs ref) so far ? */ r.r_address = (int)x->dataxroff; if (sno >= 0) { r.r_extern = 1; r.r_symbolnum = sno; } else { r.r_extern = 0; r.r_symbolnum = -sno; } #ifdef TARGET_IS_SPARC { DataInit *p; int32 i; /* cc_msg("Looking for %x\n", r.r_address); */ for (i = 0, p = datainitp; i!=r.r_address; i += (p->rpt) * (p->sort == LIT_ADCON ? 4 : p->len), p = p->datacdr); /* cc_msg("Found: rpt, sort, len, val = %ld, %ld, %ld, %lx\n", p->rpt, p->sort, p->len, p->val); */ if (p->sort != LIT_ADCON) cc_msg("Not ADCON in Data Reloc %ld\n", p->sort); r.r_addend = p->val + (sno>=0 ? 0 : (sno== -N_TEXT? FileOffsetOfSym(symext_(s)) :datastart)); } #endif /* * Unix linker can't handle relocations relative to things * defined locally... checksym converts to text/data relative. */ obj_fwrite(&r, sizeof(r), 1, objstream); if (debugging(DEBUG_OBJ)) cc_msg("data reloc '%s'", symname_(s)); } return n; } static void obj_writedata(DataInit *p) /* follows gendc exactly! */ { for (; p != 0; p = p->datacdr) { int32 rpt, sort, len, val; FloatCon *fc; rpt = p->rpt, sort = p->sort, len = p->len, val = p->val; switch (sort) { case LIT_LABEL: /* name only present for c.xxxasm */ break; default: syserr(syserr_aout_gendata, (long)sort); /* * Beware of cross-compilation between machines of different * bytesex in the following stuff. Currently this is protected * by #ifdef sun (see top of file), but it's all very dubious. */ case LIT_BBBB: while (rpt-- != 0) obj_fwrite(&val, len, 1, objstream); break; case LIT_HH: { char *p = (char *)&val; if_sun_swap(p[0], p[1]); if_sun_swap(p[2], p[3]); while (rpt-- != 0) obj_fwrite(p, len, 1, objstream); } break; case LIT_BBH: { char *p = (char *)&val; if_sun_swap(p[2], p[3]); while (rpt-- != 0) obj_fwrite(p, len, 1, objstream); } break; case LIT_HBB: { char *p = (char *)&val; if_sun_swap(p[0], p[1]); while (rpt-- != 0) obj_fwrite(p, len, 1, objstream); } break; case LIT_NUMBER: if (len != 4) syserr(syserr_aout_datalen, (long)len); /* beware: sex dependent... */ while (rpt-- != 0) obj_specialfwrite(&val, len, 1, objstream); break; case LIT_FPNUM: fc = (FloatCon *)val; /* do we need 'len' when the length is in fc->floatlen?? */ if (len == 4 || len == 8); else syserr(syserr_aout_data, (long)rpt, (long)len, fc->floatstr); while (rpt-- != 0) obj_specialfwrite(&(fc->floatbin), len, 1, objstream); break; case LIT_ADCON: /* (possibly external) name + offset */ { Symstr *sv = (Symstr *)len; /* this reloc also in dataxrefs */ ExtRef *xr = symext_(sv); int sno = obj_checksym(sv); if (sno == -N_DATA) val += datastart; else if (sno == -N_BSS) val += datastart+data_size(); if (xr->extflags & (xr_defloc|xr_defext)) val += xr->extoffset; /* beware: sex dependent... */ while (rpt-- != 0) obj_specialfwrite(&val, 4, 1, objstream); break; } } } } /* exported functions... */ int32 obj_symref(Symstr *s, int flags, int32 loc) { ExtRef *x; if ((x = symext_(s)) == 0) /* saves a quadratic loop */ { if (obj_symcount >= MAXNUMSYMS) cc_fatalerr(aout_fatalerr_toomany); x = (ExtRef *) GlobAlloc(SU_Xsym, sizeof(ExtRef)); x->extcdr = obj_symlist, x->extsym = s, x->extindex = obj_symcount++, x->extflags = 0, x->extoffset = 0; obj_symlist = symext_(s) = x; } /* The next few lines cope with further ramifications of the abolition of */ /* xr_refcode/refdata in favour of xr_code/data without xr_defloc/defext */ /* qualification. This reduces the number of bits, but needs more */ /* checking in that a symbol defined as data, and then called via */ /* casting to a code pointer may acquire defloc+data and then get */ /* xr_code or'ed in. Suffice it to say this causes confusion. */ /* AM wonders if gen.c ought to be more careful instead. */ if (flags & (xr_defloc+xr_defext)) { if (x->extflags & (xr_defloc+xr_defext)) { /* can only legitimately happen for a tentatively defined object */ /* in which case both flags and x->extflags should have type */ /* xr_data. Perhaps I should check ? */ } else x->extflags &= ~(xr_code+xr_data); } else if (x->extflags & (xr_defloc+xr_defext)) flags &= ~(xr_code+xr_data); /* end of fix. */ x->extflags |= flags; if (flags & xr_defloc+xr_defext) { /* private or public data */ x->extoffset = loc; } else if ((loc > 0) && !(flags & xr_code) && !(x->extflags & xr_defloc+xr_defext)) { /* common data, not already defined */ if (loc > x->extoffset) x->extoffset = loc; } #ifdef TARGET_IS_KCM return -1; #else /* The next line returns the offset of a function in the codesegment */ /* if it has been previously defined -- this saves store on the arm */ /* and allows short branches on other machines. Otherwise it */ /* returns -1 for undefined objects or data objects. */ return ((x->extflags & (xr_defloc+xr_defext)) && (x->extflags & xr_code) ? x->extoffset : -1); #endif } /* Add a symbol even if it already exists */ int32 obj_symdef(Symstr *s, int flags, int32 loc) { symext_(s) = NULL; return obj_symref(s, flags, loc); } void obj_init(void) { ncoderelocs = 0; ndatarelocs = 0; obj_symcount = 0; obj_symlist = 0; obj_stabcount = 0; obj_stablist = 0; codexrefs = 0; dbgxrefs = 0; codesize = 0; } /* Rearrangement of function between aoutobj and dbx here - dbx data are now buffered (in global store) in dbx, and only handed to aoutobj at compilation unit end (as distinct from handed over at the end of each unit, and buffered in aoutobj). */ void obj_stabentry(struct nlist *p) { StabList *stab; stab = (StabList *)SynAlloc(sizeof(StabList)); stab->next = obj_stablist; obj_stablist = stab; stab->nlist = *p; ++obj_stabcount; } void obj_codewrite(Symstr *name) { /* Called after each routine is compiled -- code_instvec (doubly */ /* indexed) has codep (multiple of 4) bytes of code. */ /* In BSD a.out, this has to be buffered to the end of compilation */ /* so that the BSD linker can be cow-towed to. */ /* #define COMPILING_ON_SMALL_MEMORY can be used to buffer on disc. */ int32 i, nwords; IGNORE(name); for (i = 0, nwords = codep>>2; nwords > 0; ++i) { int32 seg = nwords > CODEVECSEGSIZE ? CODEVECSEGSIZE : nwords; /* @@@ When cross compiling we really ought to swap byte sex here */ /* (by consulting code_flagvec_) because we are just about to throw */ /* away the information of how to swap bytes. */ buffer_code(code_instvec_(i), seg); nwords -= seg; } } void obj_header(void) { } static void obj_writeheader() { struct exec h; memclr(&h, sizeof(h)); /* clear any extra fields (e.g. Clipper bsd) */ h.a_magic = OMAGIC; h.a_text = datastart; /* actually the next virtual code location... */ h.a_data = data_size(); /* actually the next virtual data location... */ #ifdef TARGET_IS_SPARC h.a_bss = 0; /* SPARC just does not have a working BSS */ #else h.a_bss = bss_size; #endif h.a_syms = (obj_symcount+obj_stabcount) * sizeof(struct nlist); #ifdef TARGET_IS_SPARC #define M_SPARC 3 /* /* This needs to be fixed */ h.a_machtype = M_SPARC; h.a_toolversion = 1; /* /* I do not know why */ #endif h.a_entry = 0; h.a_trsize = ncoderelocs * sizeof(struct relocation_info); h.a_drsize = ndatarelocs * sizeof(struct relocation_info); obj_fwrite_cnt = 0; obj_fwrite(&h, sizeof(h), 1, objstream); } void obj_trailer() { int32 constdatabase = 0; obj_writeheader(); if (debugging(DEBUG_OBJ)) cc_msg("writecode at %lx\n", ftell(objstream)); datastart = codesize; #if (alignof_double > 4) /* TARGET_ALIGNS_DOUBLES */ if (codesize & 4) datastart += 4; #endif #ifdef CONST_DATA_IN_CODE if (constdata_size() != 0) { constdatabase = datastart; obj_symref(bindsym_(constdatasegment), xr_code+xr_defloc, constdatabase); datastart += constdata_size(); #if (alignof_double > 4) /* TARGET_ALIGNS_DOUBLES */ if (datastart & 4) datastart += 4; #endif } #endif obj_writecode(); constdatabase = codebase; #ifdef CONST_DATA_IN_CODE if (constdata_size() != 0) obj_writedata(constdata_head()); #endif if (debugging(DEBUG_OBJ)) cc_msg("writedata at %lx\n", ftell(objstream)); obj_writedata(data_head()); if (debugging(DEBUG_OBJ)) cc_msg("codereloc at %lx\n", ftell(objstream)); obj_coderelocation(); #ifdef CONST_DATA_IN_CODE if (constdata_size() != 0) ncoderelocs += obj_datarelocation(constdata_xrefs(), constdatabase); #endif if (debugging(DEBUG_OBJ)) cc_msg("datareloc at %lx\n", ftell(objstream)); ndatarelocs = obj_datarelocation(data_xrefs(), 0L); if (debugging(DEBUG_OBJ)) cc_msg("symtab at %lx\n", ftell(objstream)); #ifdef TARGET_HAS_DEBUGGER /* * c.armdbx calls back to obj_writedebug to add things to the symbol table. */ dbg_writedebug(); #endif obj_outsymtab(); if (debugging(DEBUG_OBJ)) cc_msg("rewind\n"); /* * It is (unexpectedly) vital to use fseek here rather than rewind, since * rewind clears error flags. Note further that if there is a partially * full buffer just before the rewind & flushing that data causes an error * (e.g. because there is no room on disc for it) this error seems to get * lost. This looks to me like a shambles in the October 1986 ANSI draft! */ fseek(objstream, 0L, SEEK_SET); /* works for hex format too */ /* * The next line represents a balance between neurotic overchecking and * the fact that it would be nice to detect I/O errors before the end of * compilation. */ if (ferror(objstream)) cc_fatalerr(obj_fatalerr_io_object); if (debugging(DEBUG_OBJ)) cc_msg("rewriting header\n"); obj_writeheader(); /* re-write header at top of file */ /* * file now closed in main() where opened */ } /* end of mip/aoutobj.c */
stardot/ncc
armthumb/asd.c
/* * C compiler file arm/asd.c, version 6c * Copyright (C) Codemist Ltd, 1988 * Copyright (C) Acorn Computers Ltd., 1988 * Copyright: (C) 1991, 1994, Advanced RISC Machines Limited. All rights reserved. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ /* This file contains routines to buffer infomation which is required for */ /* Acorn's source-level debugger. */ /* NOTA BENE: at several points this code refers to inadequacies of */ /* the TopExpress draft specification. See text file for further details */ /* of these criticisms. */ /* Memo: 1. redo s_typedefname DONE? 2. check spurious tests of DBG_XXX (done). 4. The filedate field is left as 0 as TopExpress do not use it and no format is specified. 5. Since we only save the file position of the start of each command, the end of a command is identified with the start of the next one. Find the word 'sentinel' to check. 6. Shame that the sectionflags field (see DEB_SECTION) cannot distinguish toplevel and local var table entries. 7. Shame that the 16+16 coding of DEB_FILEINFO + length overflows when compiling the compiler. 8+24 better? Yes, but TopExpress hack by requiring setting length to 0 if too big to fit. */ #ifdef __STDC__ # include <string.h> #else # include <strings.h> #endif #include <stddef.h> #include "globals.h" #ifdef TARGET_HAS_MULTIPLE_DEBUG_FORMATS #define dbg_tableindex asd_tableindex #define dbg_notefileline asd_notefileline #define dbg_addcodep asd_addcodep #define dbg_scope asd_scope #define dbg_topvar asd_topvar #define dbg_type asd_type #define dbg_proc asd_proc #define dbg_locvar asd_locvar #define dbg_locvar1 asd_locvar1 #define dbg_commblock asd_commblock #define dbg_enterproc asd_enterproc #define dbg_bodyproc asd_bodyproc #define dbg_return asd_return #define dbg_xendproc asd_xendproc #define dbg_define asd_define #define dbg_undef asd_undef #define dbg_include asd_include #define dbg_notepath asd_notepath #define dbg_init asd_init #define dbg_finalise asd_finalise #define dbg_final_src_codeaddr asd_final_src_codeaddr #define dbg_setformat asd_setformat #define dbg_needsframepointer asd_needsframepointer #define obj_notefpdesc asd_notefpdesc #define dbg_debugareaexists asd_debugareaexists #define dbg_writedebug asd_writedebug #endif #include "mcdep.h" #include "mcdpriv.h" #include "aeops.h" #include "aetree.h" /* evaluate */ #include "errors.h" #include "xrefs.h" #include "store.h" #include "codebuf.h" #include "regalloc.h" #include "util.h" #include "sem.h" /* alignoftype, sizeoftype, structfield */ #include "builtin.h" /* te_xxx, xxxsegment */ #include "bind.h" #include "simplify.h" /* mcrep */ #include "asdfmt.h" #ifdef TARGET_HAS_DEBUGGER #ifdef TARGET_HAS_ASD static bool oldformat; #define OldAsdTables oldformat #ifndef TARGET_HAS_MULTIPLE_DEBUG_FORMATS char dbg_name[] = "ASD"; int usrdbgmask; #endif #define DEBUGAREANAME "C$$debug" #define FPMAPAREANAME "C$$fpmap" static void dbg_sub_init(void); static bool dbg_init_done, dbg_sub_init_done; #define DbgAlloc(n) GlobAlloc(SU_Dbg, n) /* See also magic numbers coded as required in dbg_typerep() */ typedef struct Dbg_Structelt Dbg_Structelt; typedef struct Dbg_Enumelt Dbg_Enumelt; typedef struct Dbg_Return Dbg_Return; struct Dbg_Structelt { Dbg_Structelt *cdr; /* must be first for dreverse */ int32 offset; int32 type; char *name; }; struct Dbg_Enumelt { Dbg_Enumelt *cdr; /* must be first for dreverse */ int32 val; char *name; }; struct Dbg_Return { Dbg_Return *cdr; int32 car; }; static Dbg_Return *dbg_returnlist; /* The next macro seems to indicate a lack to do this portably in ANSI-C */ /* Are discriminated unions second class objects? */ #define DbgListAlloc(variant) \ ((DbgList *)DbgAlloc((size_t)(sizeof(dbglist->car.variant)+offsetof(DbgList,car)))) /* The following is the *internal* data structure in which debug info. */ /* is buffered. It differs from AOF format in keeping pointers to */ /* strings instead of bcpl-style strings themselves to save space. */ typedef struct DbgList DbgList; struct DbgList { DbgList *cdr; int32 debsort; union { struct { char const *name; Symstr *codeseg; int32 codesize; } DEB_SECTION; struct { int32 type; int32 args; int32 sourcepos; int32 entryaddr, bodyaddr; /* see dbg_bodyproc */ int32 endproc; /* a (Deb_filecoord *) next line may subsume sourcepos too */ char const *fileentry; char const *name; Symstr *codeseg; } DEB_PROC; struct { int32 sourcepos; int32 endaddr; /* a (Deb_filecoord *) next line may subsume sourcepos too */ char const *fileentry; Dbg_Return *retaddrs; Symstr *codeseg; } DEB_ENDPROC; struct { int32 type; int32 sourcepos; unsigned32 stgclass; int32 location; Symstr *sym; Symstr *base; } DEB_VAR; struct { int32 type; TypeExpr *typex; int32 loc; char const *name; } DEB_TYPE; struct { int32 size; int32 arrayflags; int32 basetype; int32 lowerbound; int32 upperbound; } DEB_ARRAY; struct { int32 typeword; int32 space; int32 container; Dbg_Enumelt *elts; } DEB_ENUM; struct { int32 typeword; int32 space; int32 size; Dbg_Structelt *elts; } DEB_STRUCT; struct { DbgList *nextstruct; int32 *typeref; int32 ptrcnt; SET_BITMAP sort; } DEB_FREF; struct { union { DbgList *next; int32 codeaddr; } s; Symstr *codeseg; } DEB_SCOPE; struct { int32 type; /* of the extracted value */ int32 container; unsigned8 size, offset, pad1, pad2; } DEB_BF; struct { int32 space; char const *name; int32 argcount; char const *body; dbg_ArgList const *arglist; FileLine fl; } DEB_DEFINE; struct { char const *name; FileLine fl; } DEB_UNDEF; } car; }; static int32 dbgloc; static DbgList *dbglist, *dbglistproc; typedef struct DbgList Dbg_TypeFRef; #define fr_nextstruct_(p) ((p)->car.DEB_FREF.nextstruct) #define fr_typeref_(p) ((p)->car.DEB_FREF.typeref) #define fr_ptrcnt_(p) ((p)->car.DEB_FREF.ptrcnt) #define fr_sort_(p) ((p)->car.DEB_FREF.sort) static Dbg_TypeFRef *dbg_structRefs; typedef struct Dbg_LocList Dbg_LocList; struct Dbg_LocList { Dbg_LocList *cdr; Binder *name; int32 pos; int32 typeref; int32 size; Dbg_TypeFRef *typefrefs; }; static Dbg_LocList *dbg_loclist; static struct { Symstr *sym; int32 len; } baseseg; static DataXref *dbg_relocate(DataXref *xrefs, int32 where, Symstr *symbol) { return (DataXref*)global_list3(SU_Xref, xrefs, where, symbol); } /* For some strange reason, AOF debugger info has bcpl-format strings */ /* in spite of the fact that the rest of AOF uses C format ones. */ static size_t bcpl_string(char *b, char const *c) { size_t n = strlen(c); if (n > 255) n = 255; b[0] = n; memcpy(b+1, c, n); memclr(b+n+1, 3-(n&3)); /* for neatness */ return (size_t)padstrlen(n); } static int32 dbg_check(int32 offset) { if (offset > 0x800000L) cc_fatalerr(armdbg_fatalerr_toobig); return -offset; } /* First structs and code for buffering file/line co-ordinates. */ /* BEWARE: believing the debugging is usually done on small programs, */ /* and not in production runs, the following data structures are */ /* naive rather than efficient and often require quadratic algorithms. */ /* If it worries you, then the solution is obvious, but given the */ /* complexity of the debugger tables question the need first! */ /* We have one of these for every file we see. BUT because a file may */ /* validly be included more than once in a C program, we had better do */ /* pointer, not string, equality on names, and rely on pp.c behaviour. */ typedef struct Deb_filecoord Deb_filecoord; typedef struct Deb_filelist Deb_filelist; struct Deb_filelist { Deb_filelist *nextfile; char const *filename; int32 filelistoffset; /* filename's ->fileentry offset for DEB_PROC */ unsigned lastline; Deb_filecoord *linelist; /* reverse sorted via nextinfile */ }; /* For putting out TopExpress-style line number info here we have to do */ /* a fair amount of work. 'nextinfile' is the next command start in a */ /* file and 'nextincode' the chain in order of code addresses. */ /* 'nextincode' is in ascending order, and 'nextinfile' in descending */ /* but the latter is 'dreversed' before use. */ /* When they coincide, we can group fragments (see TopExpress doc). */ struct Deb_filecoord { Deb_filecoord *nextinfile, *nextincode; /* @@@ dreverse pun */ Deb_filelist *file; unsigned16 line, col; int32 codeaddr; Symstr *codeseg; }; static Deb_filelist *dbg_filelist; /* The next two vars are (code order) list (->nextincode) & tail pointer */ static Deb_filecoord *dbg_coord_p, *dbg_coord_q; static Deb_filecoord dbg_coord_sentinel = { 0, 0, /* nextinfile, nextincode */ 0, /* file */ 65535, 0, 0x00ffffff /* line, col, codeaddr(set by dbg_fileinfo).*/ }; static int32 asd_tablesize(void) { return dbgloc; } int32 dbg_tableindex(int32 dt_number) { IGNORE(dt_number); return 0; } VoidStar dbg_notefileline(FileLine fl) { Deb_filelist *x; if (!dbg_sub_init_done) dbg_sub_init(); x = dbg_filelist; while (x != NULL && x->filename != fl.f) x = x->nextfile; if (x == NULL) { x = (Deb_filelist *) DbgAlloc(sizeof(Deb_filelist)); x->nextfile = dbg_filelist, x->filename = fl.f, x->filelistoffset = 0, x->linelist = 0; dbg_filelist = x; } if (usrdbg(DBG_LINE)) { Deb_filecoord *l = x->linelist; /* There used to be a syserr here if (l != NULL && l->line > fl.l), but it can be triggered by #line (though not #line n file, which won't give equality of filename): the CVS has an example. Also, it fails if functions are taken out of file order, as in the out-of-line expansion of inline functions. */ l = (Deb_filecoord *) DbgAlloc(sizeof(Deb_filecoord)); l->nextinfile = x->linelist, l->nextincode = 0, l->file = x, l->line = fl.l, l->col = fl.column, l->codeaddr = -1; l->codeseg = dbg_init_done ? bindsym_(codesegment) : 0; x->linelist = l; x->lastline = fl.l; return (VoidStar) l; } return DUFF_ADDR; } static DbgList *dbglistscope; /* The 'dbgaddr' arg has type 'void *' to keep the debugger types local to */ /* this file. This does not make it any less of a (ANSI approved) hack. */ void dbg_addcodep(VoidStar dbgaddr, int32 codeaddr) { if (dbgaddr == NULL) { /* J_INFOSCOPE */ /* c.flowgraf outputs a J_INFOSCOPE immediately after calling * dbg_scope, to mark the relevant code address. */ if (debugging(DEBUG_Q)) cc_msg("-- scope at 0x%lx\n", codeaddr); { DbgList *p = dbglistscope; while (p != NULL) { DbgList *next = p->car.DEB_SCOPE.s.next; p->car.DEB_SCOPE.s.codeaddr = codeaddr; p = next; } dbglistscope = NULL; } } else if (usrdbg(DBG_LINE)) { Deb_filecoord *p = (Deb_filecoord *)dbgaddr; if (debugging(DEBUG_Q)) cc_msg("%p ('%s' line %u/%u) @ %.6lx\n", (VoidStar )p, p->file->filename, p->line, p->col, (long)codeaddr); /* The following test avoids setting nextincode/codeaddr twice */ /* This is currently needed in case FileLine's are duplicated. */ if (p->codeaddr == -1) { p->codeaddr = codeaddr; if (dbg_coord_p) dbg_coord_q = dbg_coord_q->nextincode = p; else dbg_coord_p = dbg_coord_q = p; } #ifdef never else syserr(syserr_addcodep); #endif } } static int32 dbg_filetooffset(char const *filename) { Deb_filelist *x; for (x = dbg_filelist; x != NULL; x = x->nextfile) if (x->filename == filename) return x->filelistoffset; /* The next line should not happen if dbg_notefileline is working. */ syserr(syserr_filetooffset, filename); return 0; } static void dbg_hdr(int itemsort, size_t length) { int32 w = ((int32)length << 16) | itemsort; obj_writedebug(&w, 1+DBG_INTFLAG); } typedef struct { int32 codebytes; int infosize; unsigned lines; unsigned col; } Dbg_LineInfoItem; static bool dbg_GetLineInfoDescription(bool first, Deb_filecoord *l, Dbg_LineInfoItem *item) { Deb_filecoord *nc = l->nextincode; Deb_filecoord *nf = l->nextinfile; if (nf!=NULL && nc!=NULL && nf->file==nc->file) { Deb_filecoord *nnf = nf; while (nnf!=NULL) { if (nnf==nc) { nf=nc; break; } if (nnf->codeaddr!=-1 && nnf->codeaddr!=l->codeaddr) break; nnf = nnf->nextinfile; } } item->codebytes = nc->codeseg == l->codeseg ? nc->codeaddr - l->codeaddr : 0; if (nf == NULL) item->lines = l->file->lastline - l->line, item->col = 0; else if (nf != nc ? nf->codeaddr != -1 : nc->line < l->line) item->lines = 1, item->col = 0; else item->lines = nf->line - l->line, item->col = (item->lines == 0) ? (first ? nf->col - 1 : nf->col - l->col) : (nf->col == 1) ? 0 : nf->col; if (item->codebytes==0 && item->lines == 0 && item->col == 0) item->infosize = 0; else if (item->codebytes<256 && (OldAsdTables ? item->lines < 256 : ( (item->lines == 0 && item->col < (255-Asd_LineInfo_Short_MaxLine)) || (item->col == 0 && item->lines <= Asd_LineInfo_Short_MaxLine)))) item->infosize = 2; else if (OldAsdTables) item->infosize = 6; else if (item->lines == 0) { item->col += l->col; if (item->col <= 1) item->col = 0, item->infosize = 6; else item->infosize = 8; } else if (item->col == 0) item->infosize = 6; else item->infosize = 8; return nf==NULL || nf != nc || nc->line < l->line || nc->codeseg != l->codeseg; } static int32 dbg_padtoword(int32 loc) { if ((loc & 2) == 0) return loc; else { int w = 0; obj_writedebug(&w, 2); return loc + 2; } } /* dbg_fileinfo() writes out the DEB_FILEINFO table. However, due */ /* to the poxy requirement to write the length first we have to do two */ /* passes (and ditto for fragments within). */ static int32 dbg_fileinfo(bool writing, int32 predictedbytes, int32 loc, DataXref **xrefp) { int32 totalbytes = 4; /* loc and totalbytes can probably merge */ Deb_filelist *x; DataXref *xrefs = *xrefp; if (!usrdbg(DBG_ANY)) return 0; /* nominally totalbytes */ if (writing) { dbg_hdr(ITEMFILEINFO, predictedbytes < 0x10000 ? (unsigned)predictedbytes : 0); loc += 4; } for (x = dbg_filelist; x != NULL; x = x->nextfile) { Deb_filecoord *l; Dbg_LineInfoItem item; int32 nfrags = 0, nfragbytes = 0; bool discontinuity = YES; if (!writing) /* first pass - do a dreverse (on ->nextinfile). */ (x->linelist = (Deb_filecoord *)dreverse((List *)x->linelist), x->filelistoffset = totalbytes); /* save for DEB_PROC/ENDPROC */ /* Note that ->nextincode has a sentinel to flush last fileline. */ for (l = x->linelist; l != NULL; l = l->nextinfile) { if (l->codeaddr != -1) { /* we generated code for this construct */ bool nextdiscontinuity = dbg_GetLineInfoDescription(discontinuity, l, &item); if (item.infosize!=0) { if (discontinuity) { nfrags++; nfragbytes = (nfragbytes+2)&(-4); /* round up to word boundary */ nfragbytes += (int32)item.infosize+20; discontinuity = NO; } else { nfragbytes += item.infosize; } } discontinuity = discontinuity | nextdiscontinuity; } } { char c[256]; size_t n = bcpl_string(c, x->filename); int32 size = (int32)n + 12 + ((nfragbytes+2)&(-4)); if (writing) { bool discontinuity = YES; int32 w[5]; w[0] = size; w[1] = 0; /* @@@ file date one day */ obj_writedebug(w, 2+DBG_INTFLAG); obj_writedebug(c, n); obj_writedebug(&nfrags, 1+DBG_INTFLAG); loc += (int32)n + 12; for (l = x->linelist; l != NULL; l = l->nextinfile) if (l->codeaddr != -1) { bool nextdiscontinuity = dbg_GetLineInfoDescription(discontinuity, l, &item); if (item.infosize!=0) { if (discontinuity) { int32 codebytes = 0; int32 lines = 0; int32 infosize = 0; loc = dbg_padtoword(loc); { Deb_filecoord *nl = l; bool ended = YES; Dbg_LineInfoItem li; do { ended = dbg_GetLineInfoDescription(ended, nl, &li); codebytes += li.codebytes; lines += li.lines; infosize += li.infosize; nl = nl->nextincode; } while (!ended); } w[0] = 20+infosize; w[1] = l->line; w[2] = l->line+lines; w[3] = l->codeaddr; xrefs = dbg_relocate(xrefs, loc+12, l->codeseg); w[4] = codebytes; obj_writedebug(w, 5+DBG_INTFLAG); loc += 20; discontinuity = NO; } if (item.infosize==2) { c[0] = (char)item.codebytes; c[1] = (item.lines != 0 | OldAsdTables) ? (char)item.lines : (char)(item.col+1+Asd_LineInfo_Short_MaxLine); obj_writedebug(c, 2); loc += 2; } else { /* long format (now in two flavours) */ unsigned16 s[3]; c[0] = c[1] = 0; s[0] = (unsigned16)item.lines; s[1] = (unsigned16)item.codebytes; if (item.infosize == 8) { s[2] = (short)item.col; c[1] = Asd_LineInfo_Short_MaxLine+1; } obj_writedebug(c, 2); obj_writedebug(s, ((int32)item.infosize-2)/2 + DBG_SHORTFLAG); loc += item.infosize; } } discontinuity = discontinuity | nextdiscontinuity; } loc = dbg_padtoword(loc); } totalbytes += size; } } if (writing) { int32 v[1]; v[0] = 0; obj_writedebug(v, 4); loc += 4; } *xrefp = xrefs; return totalbytes+4; } /* End of file/line co-ordinate code */ static void dbg_typerep(TypeExpr *, int32 *typep); static int32 dbg_arrayrep(TypeExpr *t, Expr *e) { /* e is the array size. Since C arrays start at 0, the upper bound is */ /* one less */ DbgList *p = DbgListAlloc(DEB_ARRAY); p->debsort = ITEMARRAY; p->car.DEB_ARRAY.arrayflags = (e ? 10:6); dbg_typerep(t, &p->car.DEB_ARRAY.basetype); p->car.DEB_ARRAY.lowerbound = 0; p->car.DEB_ARRAY.upperbound = e ? evaluate(e)-1:0; p->car.DEB_ARRAY.size = sizeoftype(t); p->cdr = dbglist; /* do this last (typerep above) */ dbglist = p; dbgloc += 24; return dbg_check(dbgloc-24); } #define dbg_mk_typerep(code,ptrc) TYPE_TYPEWORD((int32)(code), ptrc) static int32 dbg_structentry( SET_BITMAP sort, ClassMember *members, int32 size, Dbg_TypeFRef *refs, TagBinder *b) { ClassMember *l; DbgList *resultstruct; Dbg_Structelt *elts = 0; int32 space = 12; int32 entry; for (l = members; l != 0; l = memcdr_(l)) { if (memsv_(l) && is_datamember_(l)) { /* note that memsv is 0 for padding bit fields */ space += 8 + padstrlen(strlen(symname_(memsv_(l)))); } } /* The next line notes the struct definition in the debug table, */ /* thereby avoiding problems with circular types. */ dbgloc += space; entry = dbg_check(dbgloc-space); { DbgList *p = DbgListAlloc(DEB_STRUCT); p->debsort = sort == bitoftype_(s_struct) ? ITEMSTRUCT : sort == bitoftype_(s_union) ? ITEMUNION : ITEMCLASS; p->car.DEB_STRUCT.typeword = entry; p->car.DEB_STRUCT.space = space; p->car.DEB_STRUCT.size = 0; /* filled in later */ p->car.DEB_STRUCT.elts = 0; /* filled in later */ p->cdr = dbglist; resultstruct = dbglist = p; if (b != NULL) b->tagbinddbg = (IPtr)p; } { StructPos sp; structpos_init(&sp, b); for (l = members; l != 0; l = memcdr_(l)) { if (!structfield(l, sort, &sp)) continue; if (memsv_(l)) { /* note that memsv is 0 for padding bit fields */ Dbg_Structelt *el = (Dbg_Structelt *) DbgAlloc(sizeof(Dbg_Structelt)); cdr_(el) = elts; el->offset = sp.woffset; if (sp.bsize == 0) { dbg_typerep(memtype_(l), &el->type); } else { DbgList *p = DbgListAlloc(DEB_BF); TypeExpr te; te = *memtype_(l); typespecmap_(&te) &= ~BITFIELD; dbgloc += 16; el->type = dbg_mk_typerep(dbg_check(dbgloc-16), 0); p->debsort = ITEMBITFIELD; p->car.DEB_BF.offset = (unsigned8)(target_lsbitfirst ? memboff_(l) : MAXBITSIZE-membits_(l)-memboff_(l)); p->car.DEB_BF.size = (unsigned8)membits_(l); p->car.DEB_BF.pad1 = p->car.DEB_BF.pad2 = 0; p->cdr = dbglist; dbglist = p; dbg_typerep(&te, &p->car.DEB_BF.type); dbg_typerep(te_int, &p->car.DEB_BF.container); } el->name = symname_(memsv_(l)); elts = el; } } } resultstruct->car.DEB_STRUCT.size = size; resultstruct->car.DEB_STRUCT.elts = (Dbg_Structelt*)dreverse((List*)elts); /* if the structure was forward-referenced, fill in the references */ for (; refs != 0; refs = cdr_(refs)) { *(fr_typeref_(refs)) = dbg_mk_typerep(entry, fr_ptrcnt_(refs)); fr_typeref_(refs) = 0; /* mark it as handled */ } return entry; } static int32 dbg_enumentry(BindList *members, Dbg_TypeFRef *refs, TagBinder *b) { Dbg_Enumelt *elts = 0; int32 space = 12; int32 entry; int32 count = 0; bool contiguous = YES; int32 last = 0; for (; members != 0; members = members->bindlistcdr, count++) { Dbg_Enumelt *p = (Dbg_Enumelt *)DbgAlloc(sizeof(Dbg_Enumelt)); Binder *elt = members->bindlistcar; cdr_(p) = elts; p->name = symname_(bindsym_(elt)); p->val = bindenumval_(elt); if (contiguous) { if (count != 0 && p->val != last+1) contiguous = NO; last = p->val; } space += padstrlen(strlen(symname_(bindsym_(elt)))); elts = p; } elts = (Dbg_Enumelt *)dreverse((List *)elts); if (contiguous) space += 4; else space += count*4; dbgloc += space; entry = dbg_check(dbgloc-space); { DbgList *p = DbgListAlloc(DEB_ENUM); static int32 const c[] = { TYPE_TYPEWORD(TYPESBYTE, 0), TYPE_TYPEWORD(TYPESHALF, 0), TYPE_TYPEWORD(TYPESWORD, 0), TYPE_TYPEWORD(TYPESWORD, 0), TYPE_TYPEWORD(TYPEUBYTE, 0), TYPE_TYPEWORD(TYPEUHALF, 0), TYPE_TYPEWORD(TYPEUWORD, 0), TYPE_TYPEWORD(TYPEUWORD, 0) }; p->debsort = contiguous ? ITEMENUMC : ITEMENUMD; p->car.DEB_ENUM.typeword = entry; p->car.DEB_ENUM.space = space; p->car.DEB_ENUM.container = c[(tagbindbits_(b) & TB_CONTAINER) >> TB_CONTAINER_SHIFT]; p->car.DEB_ENUM.elts = elts; p->cdr = dbglist; dbglist = p; if (b != NULL) b->tagbinddbg = (IPtr)p; } /* if the structure was forward-referenced, fill in the references */ for (; refs != 0; refs = cdr_(refs)) { *(fr_typeref_(refs)) = dbg_mk_typerep(entry, fr_ptrcnt_(refs)); fr_typeref_(refs) = 0; /* mark it as handled */ } return entry; } static int32 dbg_structrep(TagBinder *b, int32 size) { /* * Note that the TopExpress definition cannot cope with undefined * structs as required by C. */ if (!(tagbindbits_(b) & TB_DEFD)) return 0; /* presumably a forward reference */ /* (b->tagbinddbg is a pointer to the structure's forward reference chain while it's not defined, and a pointer to its DbgList entry when it is */ { Dbg_TypeFRef *frefs = (Dbg_TypeFRef *)b->tagbinddbg; if (frefs == NULL || frefs->debsort == 0) { /* not yet defined */ if (tagbindbits_(b) & bitoftype_(s_enum)) dbg_enumentry(tagbindenums_(b), frefs, b); else dbg_structentry(tagbindbits_(b) & CLASSBITS, tagbindmems_(b), size, frefs, b); } } return ((DbgList *)b->tagbinddbg)->car.DEB_STRUCT.typeword; } static Dbg_TypeFRef *addtypefref(Dbg_TypeFRef *next, int32 *typep, int32 ptrcnt) { Dbg_TypeFRef *fr = DbgListAlloc(DEB_FREF); cdr_(fr) = next; fr->debsort = 0; fr_typeref_(fr) = typep; fr_ptrcnt_(fr) = ptrcnt; *typep = 0; return fr; } static void struct_typerep(TypeExpr *x, int32 *typep, int32 ptrcnt) { TagBinder *b = typespectagbind_(x); int32 size = tagbindbits_(b) & TB_DEFD ? sizeoftype(x) : 0; int32 structrep = dbg_structrep(b, size); /* if there's a real definition of the structure, structrep will ensure that an entry for it has been generated (and returns the negated offset of the entry within the debug data) */ if (typep != NULL) { if (structrep != 0) { *typep = dbg_mk_typerep(structrep, ptrcnt); return; } else { /* no real definition of the structure yet. Add an entry to its forward references. */ Dbg_TypeFRef *p = addtypefref((Dbg_TypeFRef*)b->tagbinddbg, typep, ptrcnt); fr_nextstruct_(p) = dbg_structRefs; fr_sort_(p) = tagbindbits_(b) & ENUMORCLASSBITS; b->tagbinddbg = (IPtr)p; dbg_structRefs = p; return; } } } static int typename_match(char const *mangled, char const *generic) { int l = strlen(generic); if (mangled == generic) return 1; if (StrnEq(mangled, generic, l) && StrnEq(mangled+l, "__", 2)) return 1; return 0; } static void dbg_typerep(TypeExpr *x, int32 *typep) { /* note that we do NOT call prunetype() here so we still see typedefs */ /* BEWARE: this routine uses TopExpress magic numbers as type codes. */ int32 ptrcnt = 0; int32 restype = 0; for (;;) { switch (h0_(x)) { case t_content: case t_ref: /* @@@ OK? */ ptrcnt++; x = typearg_(x); /* TopExpress spec cannot express const/volatile pointers */ continue; case t_subscript: restype = dbg_mk_typerep(dbg_arrayrep(typearg_(x), typesubsize_(x)), ptrcnt); break; case t_fnap: restype = dbg_mk_typerep(TYPEFUNCTION, ptrcnt); /* TopExpress cannot say more */ break; case s_typespec: { SET_BITMAP m = typespecmap_(x); switch (m & -m) { /* LSB - unsigned32/long etc. are higher */ case bitoftype_(s_enum): struct_typerep(x, typep, ptrcnt); return; case bitoftype_(s_struct): case bitoftype_(s_class): case bitoftype_(s_union): struct_typerep(x, typep, ptrcnt); return; case bitoftype_(s_typedefname): { Binder *b = typespecbind_(x); /* is there already a table entry for it ? */ { DbgList *p; for ( p = dbglist ; p!=NULL ; p = p->cdr ) if ( p->debsort==ITEMTYPE && p->car.DEB_TYPE.typex==bindtype_(b) && typename_match(p->car.DEB_TYPE.name, symname_(bindsym_(b)))) { restype = dbg_mk_typerep(-(p->car.DEB_TYPE.loc), ptrcnt); break; } /* if not, is there a pending one? */ if (p == NULL && typep != NULL) { Dbg_LocList *l; for (l = dbg_loclist; l != NULL; l = cdr_(l)) if (l->name == b) { l->typefrefs = addtypefref(l->typefrefs, typep, ptrcnt); return; } syserr("typedef"); } } break; } case bitoftype_(s_char): { int32 mcr = mcrepoftype(x); restype = dbg_mk_typerep((mcr & MCR_SORT_MASK) == MCR_SORT_SIGNED ? TYPESBYTE : TYPEUBYTE, ptrcnt); break; } case bitoftype_(s_int): if (m & BITFIELD) syserr(syserr_dbg_bitfield); { int32 mcr = mcrepoftype(x); int32 tc; switch (mcr & MCR_SIZE_MASK) { case 2: tc = TYPEUHALF; break; case 8: tc = TYPEUDWORD; break; default: tc = TYPEUWORD; break; } if ((mcr & MCR_SORT_MASK) == MCR_SORT_SIGNED) tc += (TYPESBYTE - TYPEUBYTE); restype = dbg_mk_typerep(tc,ptrcnt); break; } case bitoftype_(s_double): restype = dbg_mk_typerep((m & bitoftype_(s_short)) ? TYPEFLOAT : TYPEDOUBLE, ptrcnt); break; case bitoftype_(s_void): restype = dbg_mk_typerep(TYPEVOID, ptrcnt); break; default: syserr(syserr_dbg_typerep, (VoidStar)x, (long)typespecmap_(x)); break; } break; } default: syserr(syserr_dbg_typerep, (VoidStar)x, (long)typespecmap_(x)); break; } if (typep != NULL) *typep = restype; return; } } static void dbg_addvar(Symstr *name, int32 t, int32 sourcepos, unsigned32 stgclass, Symstr *base, int32 addr, TypeExpr *type) { DbgList *p = DbgListAlloc(DEB_VAR); p->debsort = ITEMVAR; p->car.DEB_VAR.type = t; p->car.DEB_VAR.sourcepos = sourcepos; p->car.DEB_VAR.stgclass = stgclass; p->car.DEB_VAR.location = addr; p->car.DEB_VAR.sym = name; p->car.DEB_VAR.base = base; p->cdr = dbglist; dbglist = p; dbgloc += 20 + padstrlen(strlen(symname_(name))); if (type != NULL) dbg_typerep(type, &p->car.DEB_VAR.type); } void dbg_topvar(Symstr *name, int32 addr, TypeExpr *t, int stgclass, FileLine fl) /* For scoping reasons this only gets called on top-level variables (which */ /* are known to be held in global store). (Does this matter?) */ { if (usrdbg(DBG_PROC)) { /* nb bss => external here. The effect is only to cause the table item to be 0+symbol, rather than addr+data seg */ DbgList *p; Symstr *base = NULL; StgClass stg = (stgclass & DS_REG) ? C_REG : (stgclass & DS_EXT) ? C_EXTERN : C_STATIC; if (stgclass & (DS_EXT|DS_BSS)) base = name, addr = 0; #ifdef CONST_DATA_IN_CODE else if (stgclass & DS_CODE) base = bindsym_(constdatasegment); #endif else if (!(stgclass & DS_REG)) base = bindsym_(datasegment); if (debugging(DEBUG_Q)) cc_msg("top var $r @ %.6lx\n", name, (long)addr); if (stgclass != 0 && stg != C_REG) for ( p = dbglist ; p!=NULL ; p = p->cdr ) if ( p->debsort==ITEMVAR && (p->car.DEB_VAR.stgclass==C_EXTERN || p->car.DEB_VAR.stgclass==C_STATIC) && p->car.DEB_VAR.location==0 && p->car.DEB_VAR.sym == name) { p->car.DEB_VAR.sourcepos = fl.l; p->car.DEB_VAR.location = addr; p->car.DEB_VAR.base = base; return; } dbg_addvar(name, 0, fl.l, stg, base, addr, t); } } static int32 dbg_typeinternal(Symstr *name, int32 t, TypeExpr *type) /* This procedure is called on a type-declaration internal to a procedure * (from dbg_scope, after the syntax tree has evaporated), and on a global * one, with the syntax tree in place. The latter therefore goes through * dbg_type, which internalises the type. */ { if (isgensym(name)) { dbg_typerep(type, NULL); return 0; } else { DbgList *p = DbgListAlloc(DEB_TYPE); if (debugging(DEBUG_Q)) cc_msg("type $r\n", name); p->debsort = ITEMTYPE; p->car.DEB_TYPE.type = t; p->car.DEB_TYPE.typex = type; p->car.DEB_TYPE.loc = dbgloc; p->car.DEB_TYPE.name = symname_(name); p->cdr = dbglist; dbglist = p; dbgloc += 8 + padstrlen(strlen(symname_(name))); if (type != NULL) dbg_typerep(type, &p->car.DEB_TYPE.type); return p->car.DEB_TYPE.loc; } } void dbg_type(Symstr *name, TypeExpr *t, FileLine fl) /* This only gets called on top-level types (which are known to be held in * global store). */ { IGNORE(fl); (void)dbg_typeinternal(name, 0, t); } static Deb_filecoord *cur_proc_coord; void dbg_proc(Binder *b, TagBinder *parent, bool ext, FileLine fl) { IGNORE(ext); /* ASD has no use for static/external information */ IGNORE(parent); if (usrdbg(DBG_PROC)) { Symstr *name = bindsym_(b); DbgList *p = DbgListAlloc(DEB_PROC); TypeExpr *t = bindtype_(b); char *s = symname_(name); if (debugging(DEBUG_Q)) cc_msg("startproc $r\n", name); t = princtype(t); p->debsort = ITEMPROC; if (h0_(t) != t_fnap) syserr(syserr_dbg_proc); dbg_typerep(typearg_(t), &p->car.DEB_PROC.type); p->car.DEB_PROC.args = length((List *)typefnargs_(t)); p->car.DEB_PROC.sourcepos = fl.l; p->car.DEB_PROC.entryaddr = 0; /* fill in at dbg_enterproc */ p->car.DEB_PROC.bodyaddr = 0; /* fill in at dbg_bodyproc */ p->car.DEB_PROC.endproc = 0; /* fill in at dbg_xendproc */ p->car.DEB_PROC.fileentry = fl.f; p->car.DEB_PROC.name = s; p->car.DEB_PROC.codeseg = bindsym_(codesegment); p->cdr = dbglist; /* do this last (typerep above) */ dbglistproc = dbglist = p; /* so can be filled in */ dbgloc += 32 + padstrlen(strlen(s)); } if (usrdbg(DBG_LINE)) cur_proc_coord = (Deb_filecoord *)fl.p; dbg_returnlist = 0, dbg_loclist = 0; } void dbg_enterproc(void) { if (usrdbg(DBG_PROC)) { DbgList *p = dbglistproc; if (p == 0 || p->debsort != ITEMPROC || p->car.DEB_PROC.entryaddr != 0) syserr(syserr_dbg_proc1); if (debugging(DEBUG_Q)) cc_msg("enter '%s' @ %.6lx\n", p->car.DEB_PROC.name, (long)codebase); p->car.DEB_PROC.entryaddr = codebase; } if (usrdbg(DBG_LINE)) dbg_addcodep(cur_proc_coord, codebase); } /* The following routine records the post-entry codeaddr of a proc */ void dbg_bodyproc(void) { if (usrdbg(DBG_PROC)) { DbgList *p = dbglistproc; if (p == 0 || p->debsort != ITEMPROC || p->car.DEB_PROC.bodyaddr != 0) syserr(syserr_dbg_proc1); if (debugging(DEBUG_Q)) cc_msg("body '%s' @ %.6lx\n", p->car.DEB_PROC.name, (long)(codebase+codep)); p->car.DEB_PROC.bodyaddr = codebase+codep; } } void dbg_return(int32 addr) { if (usrdbg(DBG_PROC)) { if (debugging(DEBUG_Q)) cc_msg("return @ %.6lx\n", addr); dbg_returnlist = (Dbg_Return*) global_cons2(SU_Dbg, dbg_returnlist, addr); } } void dbg_xendproc(FileLine fl) { if (bindsym_(codesegment) == baseseg.sym) baseseg.len = codebase+codep; if (usrdbg(DBG_PROC)) { DbgList *q = dbglistproc; DbgList *p = DbgListAlloc(DEB_ENDPROC); if (q == 0 || q->debsort != ITEMPROC || q->car.DEB_PROC.endproc != 0) syserr(syserr_dbg_proc1); if (debugging(DEBUG_Q)) cc_msg("endproc '%s' @ %.6lx\n", q->car.DEB_PROC.name, (long)(codebase+codep)); q->car.DEB_PROC.endproc = dbgloc; p->debsort = ITEMENDPROC; p->car.DEB_ENDPROC.sourcepos = fl.l; p->car.DEB_ENDPROC.endaddr = codebase+codep; p->car.DEB_ENDPROC.fileentry = fl.f; p->car.DEB_ENDPROC.retaddrs = dbg_returnlist; p->car.DEB_ENDPROC.codeseg = bindsym_(codesegment); p->cdr = dbglist; dbglist = p; dbgloc += 20 + 4*length((List *)dbg_returnlist); dbg_loclist = 0, dbg_returnlist = 0; /* for safety */ } } /* dbg_locvar() registers the name and line of a declaration, and internalises * the type. Location info cannot be added until after register allocation. * See also dbg_scope which completes. * (Type internalisation cannot be done then, because by that time the tree * has evaporated). * Also remember that dead code elimination may remove some decls. */ void dbg_locvar(Binder *name, FileLine fl) { if (usrdbg(DBG_VAR) && !isgensym(bindsym_(name))) { /* local to a proc */ Dbg_LocList *p = (Dbg_LocList*) BindAlloc(sizeof(Dbg_LocList)); if (debugging(DEBUG_Q)) cc_msg("note loc var $b\n", name); p->cdr = dbg_loclist; p->name = name; p->pos = fl.l; p->typefrefs = NULL; p->size = sizeoftypelegal(bindtype_(name)) ? sizeoftype(bindtype_(name)) : sizeof_int; dbg_typerep(bindtype_(name), &p->typeref); dbg_loclist = p; } } static Dbg_LocList *dbg_findloclist(Binder *b) { Dbg_LocList *p; for (p = dbg_loclist; p != NULL; p = p->cdr) if (p->name == b) return p; return NULL; } void dbg_locvar1(Binder *b) { Symstr *name = bindsym_(b); Symstr *base = NULL; Dbg_LocList *p = dbg_findloclist(b); unsigned32 stgclass; int stgclassname; int32 addr = bindaddr_(b); if (p == NULL || p->pos == -1) { if (debugging(DEBUG_Q)) cc_msg(" omitted"); return; /* invented variable name (e.g. s_let) */ } switch (bindstg_(b) & PRINCSTGBITS) { default: defolt: syserr(syserr_dbg_table, name, (long)bindstg_(b), (long)addr); return; case bitofstg_(s_typedef): if (debugging(DEBUG_Q)) cc_msg(" <typedef>"); { int32 loc = dbg_typeinternal(name, p->typeref, NULL); Dbg_TypeFRef *ref = p->typefrefs; for (; ref != NULL; ref = cdr_(ref)) *fr_typeref_(ref) = dbg_mk_typerep(-loc, fr_ptrcnt_(ref)); } return; /* dbg_type deals with s_typedef vars */ case bitofstg_(s_extern): if (debugging(DEBUG_Q)) cc_msg(" <extern>"); return; /* local externs do not allocate store */ case bitofstg_(s_static): stgclass = C_STATIC, stgclassname = 'S'; if (bindstg_(b) & b_fnconst) { base = bindsym_(b); addr = 0; } else base = #ifdef TARGET_HAS_BSS (bindstg_(b) & u_bss) ? bindsym_(bsssegment) : #endif #ifdef CONST_DATA_IN_CODE (bindstg_(b) & u_constdata) ? bindsym_(constdatasegment) : #endif bindsym_(datasegment); break; case bitofstg_(s_auto): if (bindxx_(b) != GAP) { stgclass = C_REG, stgclassname = 'R', addr = register_number(bindxx_(b)); } else switch (addr & BINDADDR_MASK) { case BINDADDR_ARG: stgclass = C_AUTO, stgclassname = 'A', addr = local_fpaddress(b); if (p->size < 4 && !target_lsbytefirst) addr += 4 - p->size; break; case BINDADDR_LOC: stgclass = C_AUTO, stgclassname = 'P', addr = local_fpaddress(b); if (p->size < 4 && !target_lsbytefirst) addr += 4 - p->size; break; case 0: /* probably declared but not used case (where addr is still a bindlist) */ if ((bindstg_(b) & b_bindaddrlist) != 0) { if (debugging(DEBUG_Q)) cc_msg(" unused - omitted"); return; } /* otherwise, fall into internal error case */ default: goto defolt; } break; } if (debugging(DEBUG_Q)) cc_msg(" %c %lx", stgclassname, (long)addr); dbg_addvar(name, p->typeref, p->pos, stgclass, base, addr, NULL); if (p->typeref == 0) { /* (pointer to) an as yet undefined type. We must find and amend the * forward reference record */ Dbg_TypeFRef *s = dbg_structRefs; DbgList *var = dbglist; for (; s != NULL; s = fr_nextstruct_(s)) { Dbg_TypeFRef *refs = s; for (; refs != NULL; refs = cdr_(refs)) if (fr_typeref_(refs) == &p->typeref) { fr_typeref_(refs) = &var->car.DEB_VAR.type; return; } } } } static bool asd_scope_i(BindListList *newbll, BindListList *oldbll, int32 entering) { if (length((List *)newbll) > 1) { BindListList *bll = newbll; DbgList *last = NULL; for (bll = newbll; bll != oldbll; bll = bll->bllcdr) { if (oldbll == NULL && bll->bllcdr == NULL) break; if (bll == NULL) syserr(syserr_dbg_scope); if (bll->bllcar != 0) { DbgList *p = DbgListAlloc(DEB_SCOPE); dbglistscope = p; p->cdr = dbglist; p->debsort = entering >= 0 ? ITEMSCOPEBEGIN : ITEMSCOPEEND; p->car.DEB_SCOPE.s.next = last; /* filled in soon by INFOSCOPE */ p->car.DEB_SCOPE.codeseg = bindsym_(codesegment); dbgloc += 8; dbglist = p; last = p; } } } if (debugging(DEBUG_Q)) cc_msg("scope %ld\n", entering); for (; newbll != oldbll; newbll = newbll->bllcdr) { SynBindList *bl; if (newbll == NULL) syserr(syserr_dbg_scope); for (bl = newbll->bllcar; bl; bl = bl->bindlistcdr) { Binder *b = bl->bindlistcar; if (bindstg_(b) & b_dbgbit) continue; /* for this and next line */ bindstg_(b) |= b_dbgbit; /* see end of routine cmt */ if (debugging(DEBUG_Q)) cc_msg(" %s $b", entering>=0 ? "binding" : "unbinding", b); if (entering >= 0) dbg_locvar1(b); if (debugging(DEBUG_Q)) cc_msg("\n"); } } return YES; /* Ask for INFOSCOPE item to get called back more or less immediately */ /* from the local cg (INFOSCOPE item) to fill in the codeaddr */ } bool dbg_scope(BindListList *newbll, BindListList *oldbll) { int32 entering = length((List *)newbll) - length((List *)oldbll); if (entering == 0 && newbll == oldbll) return NO; if (entering < 0) { BindListList *t = newbll; newbll = oldbll, oldbll = t; } if (length((List *)newbll) > 1) { BindListList *bll_n = newbll; for (bll_n = newbll; bll_n != oldbll; bll_n = bll_n->bllcdr) { if (oldbll == NULL && bll_n->bllcdr == NULL) break; if (bll_n == NULL) { /* New is not a superset of old. Can happen if a block containing */ /* a scope end is deleted */ for (bll_n = newbll; bll_n != NULL; bll_n = bll_n->bllcdr) { BindListList *bll_o; for (bll_o = oldbll; bll_o != NULL; bll_o = bll_o->bllcdr) if (bll_o == bll_n) { /* Here, we regret having (maybe) swapped new and old */ int32 l_o = length((List *)bll_o); if (entering > 0) { asd_scope_i(oldbll, bll_o, l_o - length((List *)oldbll)); return asd_scope_i(newbll, bll_o, length((List *)newbll) - l_o); } else { asd_scope_i(newbll, bll_o, l_o - length((List *)newbll)); return asd_scope_i(oldbll, bll_o, length((List *)oldbll) - l_o); } } } syserr(syserr_dbg_scope); } } } return asd_scope_i(newbll, oldbll, entering); } /* Dummy procedure not yet properly implemented, included here to keep in */ /* step with dbx.c */ void dbg_commblock(Binder *b, SynBindList *members, FileLine fl) { b = b; members = members; fl = fl; } void dbg_define(char const *name, bool objectmacro, char const *body, dbg_ArgList const *args, FileLine fl) { DbgList *p = DbgListAlloc(DEB_DEFINE); size_t space = 24; p->debsort = ITEMDEFINE; p->car.DEB_DEFINE.name = name; p->car.DEB_DEFINE.fl = fl; p->car.DEB_DEFINE.arglist = args; p->car.DEB_DEFINE.body = body; if (objectmacro) p->car.DEB_DEFINE.argcount = -1; else { int32 n = 0; p->car.DEB_DEFINE.argcount = n; for (; args != NULL; args = args->next, n++) space += (size_t)padstrlen(strlen(args->name)); p->car.DEB_DEFINE.argcount = n; } space += (size_t)padstrlen(strlen(name))+(size_t)padstrlen(strlen(body)); p->car.DEB_DEFINE.space = space; dbgloc += space; p->cdr = dbglist; dbglist = p; if (debugging(DEBUG_Q)) { cc_msg("%s:%d #define %s", fl.f, fl.l, name); if (!objectmacro) { char const *s = ""; cc_msg("("); for (args = p->car.DEB_DEFINE.arglist; args != NULL; args = args->next) { cc_msg("%s%s", s, args->name); s = ", "; } cc_msg(")"); } cc_msg(" %s\n", body); } } void dbg_undef(char const *name, FileLine fl) { DbgList *p = DbgListAlloc(DEB_UNDEF); p->debsort = ITEMUNDEF; p->car.DEB_UNDEF.name = name; p->car.DEB_UNDEF.fl = fl; p->cdr = dbglist; dbglist = p; dbgloc += 12 + padstrlen(strlen(name)); if (debugging(DEBUG_Q)) { cc_msg("%s:%d #undef %s\n", fl.f, fl.l, name); } } void dbg_include(char const *filename, char const *path, FileLine fl) { /* No use for this in generating ASD tables */ IGNORE(filename); IGNORE(path); IGNORE(fl); } void dbg_notepath(char const *pathname) { /* No use for this in generating ASD tables */ IGNORE(pathname); } /* armobj.c calls writedebug to generate the debugging tables. */ /* It must format them and then call obj_writedebug() */ static void asdtables_write(void) { DbgList *p; int32 check = 0; int32 fileinfobase; int32 fileinfosize; int32 v[7]; char c[256]; DataXref *xrefs = NULL; /* produce structure descriptors for forward referenced structures for * which there hasn't been a real declaration */ obj_startdebugarea(DEBUGAREANAME); while (dbg_structRefs != 0) { if (fr_typeref_(dbg_structRefs) != 0) dbg_structentry(fr_sort_(dbg_structRefs), NULL, 0, dbg_structRefs, 0); dbg_structRefs = fr_nextstruct_(dbg_structRefs); } { /* add a sentinel to the ->nextincode list to flush last fileline */ dbg_coord_sentinel.codeaddr = codebase+codep; if (dbg_coord_p) { dbg_coord_q = dbg_coord_q->nextincode = &dbg_coord_sentinel; dbg_coord_sentinel.codeseg = bindsym_(codesegment); } else dbg_coord_p = dbg_coord_q = &dbg_coord_sentinel; } fileinfobase = dbgloc; fileinfosize = dbg_fileinfo(NO,0,0,&xrefs); dbgloc += fileinfosize; for (p = dbglist = (DbgList *)dreverse((List *)dbglist); p != NULL; p = p->cdr) { int sort = (int)p->debsort; switch (sort) { default: syserr(syserr_dbg_write, (long)sort); break; case ITEMSECTION: { char h[4]; size_t n = bcpl_string(c, p->car.DEB_SECTION.name); h[0] = LANG_C; h[1] = (usrdbg(DBG_LINE) ? 1 : 0) + (usrdbg(DBG_PROC|DBG_VAR) ? 2 : 0); h[2] = 0; h[3] = OldAsdTables ? ASD_FORMAT_VERSION-1 : ASD_FORMAT_VERSION; v[0] = 0, v[2] = baseseg.len; if (baseseg.len > 0) xrefs = dbg_relocate(xrefs, check+8, p->car.DEB_SECTION.codeseg); v[1] = 0, v[3] = data_size(); if (data_size() != 0) xrefs = dbg_relocate(xrefs, check+12, bindsym_(datasegment)); v[4] = fileinfobase; v[5] = dbgloc; dbg_hdr(sort, n+32); obj_writedebug(h, 4); obj_writedebug(v, 6+DBG_INTFLAG); obj_writedebug(c, n); check += (int32)n+32; break; } case ITEMPROC: { size_t n = bcpl_string(c, p->car.DEB_PROC.name); v[0] = p->car.DEB_PROC.type; v[1] = p->car.DEB_PROC.args; v[2] = p->car.DEB_PROC.sourcepos; v[3] = p->car.DEB_PROC.entryaddr; xrefs = dbg_relocate(xrefs, check+16, p->car.DEB_PROC.codeseg); v[4] = p->car.DEB_PROC.bodyaddr; xrefs = dbg_relocate(xrefs, check+20, p->car.DEB_PROC.codeseg); v[5] = p->car.DEB_PROC.endproc; v[6] = fileinfobase + dbg_filetooffset(p->car.DEB_PROC.fileentry); dbg_hdr(sort, n+32); obj_writedebug(v, 7+DBG_INTFLAG); obj_writedebug(c, n); check += (int32)n+32; break; } case ITEMENDPROC: { Dbg_Return *l = p->car.DEB_ENDPROC.retaddrs; int n = (int)length((List *)l); v[0] = p->car.DEB_ENDPROC.sourcepos; v[1] = p->car.DEB_ENDPROC.endaddr; xrefs = dbg_relocate(xrefs, check+8, p->car.DEB_ENDPROC.codeseg); v[2] = fileinfobase + dbg_filetooffset(p->car.DEB_ENDPROC.fileentry); v[3] = n; dbg_hdr(sort, 20+4*n); obj_writedebug(v, 4+DBG_INTFLAG); check += 20; for (; l ; l = l->cdr) { obj_writedebug(&(l->car), 1+DBG_INTFLAG); xrefs = dbg_relocate(xrefs, check, p->car.DEB_ENDPROC.codeseg); check += 4; } break; } case ITEMVAR: { size_t n = bcpl_string(c, symname_(p->car.DEB_VAR.sym)); v[0] = p->car.DEB_VAR.type; v[1] = p->car.DEB_VAR.sourcepos; v[2] = (int32) p->car.DEB_VAR.stgclass; v[3] = p->car.DEB_VAR.location; if (p->car.DEB_VAR.stgclass == C_EXTERN || p->car.DEB_VAR.stgclass == C_STATIC) { /* Make sure that occurrence in debug tables alone doesn't require a symbol to be resolved. symext_(sym) is non-null if the symbol has been otherwise referenced. */ Symstr *s = p->car.DEB_VAR.base; obj_symref(s, symext_(s) == NULL ? xr_data|xr_weak : xr_data, 0); xrefs = dbg_relocate(xrefs, check+16, p->car.DEB_VAR.base); } dbg_hdr(sort, n+20); obj_writedebug(v, 4+DBG_INTFLAG); obj_writedebug(c, n); check += (int32)n+20; break; } case ITEMTYPE: { size_t n = bcpl_string(c, p->car.DEB_TYPE.name); dbg_hdr(sort, n+8); obj_writedebug(&p->car.DEB_TYPE.type, 1+DBG_INTFLAG); obj_writedebug(c, n); check += (int32)n+8; break; } case ITEMCLASS: case ITEMUNION: case ITEMSTRUCT: { Dbg_Structelt *q = p->car.DEB_STRUCT.elts; size_t space = (size_t)p->car.DEB_STRUCT.space; v[0] = length((List *)q); v[1] = p->car.DEB_STRUCT.size; dbg_hdr(sort, space); obj_writedebug(v, 2+DBG_INTFLAG); check += 12, space -= 12; for (; q; q = cdr_(q)) { size_t n = bcpl_string(c, q->name); obj_writedebug(&q->offset, 2+DBG_INTFLAG); obj_writedebug(c, n); check += (int32)n+8, space -= n+8; } if (space != 0) syserr(syserr_dbg_struct); break; } case ITEMENUMC: { Dbg_Enumelt *q = p->car.DEB_ENUM.elts; size_t space = (size_t)p->car.DEB_ENUM.space; v[0] = p->car.DEB_ENUM.container; v[1] = length((List *)q); v[2] = q == NULL ? 0 : q->val; /* An enumeration with no enumerators is a bizarre thing, but */ /* legal in C++. */ dbg_hdr(sort, space); obj_writedebug(v, 3+DBG_INTFLAG); check += 16, space -= 16; for (; q != NULL; q = cdr_(q)) { size_t n = bcpl_string(c, q->name); obj_writedebug(c, n); check += n, space -= n; } if (space != 0) syserr(syserr_dbg_struct); break; } case ITEMENUMD: { Dbg_Enumelt *q = p->car.DEB_ENUM.elts; size_t space = (size_t)p->car.DEB_ENUM.space; v[0] = p->car.DEB_ENUM.container; v[1] = length((List *)q); dbg_hdr(sort, space); obj_writedebug(v, 2+DBG_INTFLAG); check += 12, space -= 12; for (; q != NULL; q = cdr_(q)) { size_t n = bcpl_string(c, q->name); obj_writedebug(&q->val, 1+DBG_INTFLAG); obj_writedebug(c, n); check += (int32)n+4, space -= n+4; } if (space != 0) syserr(syserr_dbg_struct); break; } case ITEMARRAY: dbg_hdr(sort, 24); obj_writedebug(&p->car.DEB_ARRAY.size, 5+DBG_INTFLAG); check += 24; break; case ITEMBITFIELD: dbg_hdr(sort, 16); obj_writedebug(&p->car.DEB_BF.type, 2+DBG_INTFLAG); obj_writedebug(&p->car.DEB_BF.size, 4); check += 16; break; case ITEMSCOPEBEGIN: case ITEMSCOPEEND: xrefs = dbg_relocate(xrefs, check+4, p->car.DEB_SCOPE.codeseg); dbg_hdr(sort, 8); obj_writedebug(&p->car.DEB_SCOPE.s.codeaddr, 1+DBG_INTFLAG); check += 8; break; case ITEMUNDEF: { size_t n = bcpl_string(c, p->car.DEB_UNDEF.name); dbg_hdr(sort, n+12); v[0] = fileinfobase + dbg_filetooffset(p->car.DEB_UNDEF.fl.f); v[1] = p->car.DEB_UNDEF.fl.l; obj_writedebug(v, 2+DBG_INTFLAG); obj_writedebug(c, n); check += (int32)n+12; break; } case ITEMDEFINE: { size_t n1 = bcpl_string(c, p->car.DEB_DEFINE.name); size_t n2 = strlen(p->car.DEB_DEFINE.body); size_t n2p = (size_t)padstrlen(n2); int32 space = 0; dbg_hdr(sort, (size_t)p->car.DEB_DEFINE.space); v[0] = fileinfobase + dbg_filetooffset(p->car.DEB_DEFINE.fl.f); v[1] = p->car.DEB_DEFINE.fl.l; v[2] = check + 24 + n1; v[3] = p->car.DEB_DEFINE.argcount; v[4] = p->car.DEB_DEFINE.argcount <= 0 ? 0 : check + 24 + n1 + n2p; obj_writedebug(v, 5+DBG_INTFLAG); obj_writedebug(c, n1); obj_writedebug(p->car.DEB_DEFINE.body, n2); v[0] = 0; obj_writedebug(v, (int32)n2p-n2); space = 24 + (int32)n1 + n2p; { dbg_ArgList const *ap = p->car.DEB_DEFINE.arglist; for (; ap != NULL; ap = ap->next) { n1 = bcpl_string(c, ap->name); obj_writedebug(c, n1); space += n1; } } check += space; break; } } } if (check != fileinfobase) syserr(syserr_dbg_fileinfobase, (long)fileinfobase, (long)check); check += dbg_fileinfo(YES, fileinfosize, fileinfobase, &xrefs); if (check != dbgloc) syserr(syserr_dbgloc, (long)dbgloc, (long)check); obj_enddebugarea(DEBUGAREANAME, xrefs); } #ifdef TARGET_HAS_FP_OFFSET_TABLES typedef struct FPFragmentList FPFragmentList; struct FPFragmentList { FPFragmentList *cdr; Symstr *codeseg; int32 n; ItemFPMapFragment frag; }; static struct { int32 size; FPFragmentList *frags, **frags_tail; } fpmap; #define NoSaveAddr ((asd_Address)-1) void obj_notefpdesc(ProcFPDesc const *fpd) { FPList *p = fpd->fplist, *lastp; int32 addr = fpd->startaddr; int32 offset = fpd->initoffset; int32 saveaddr = fpd->saveaddr; for (; (lastp = p) != NULL; p = cdr_(p)) { int32 bytes = 0; int32 startaddr = addr; for (; p != NULL; p = cdr_(p)) { unsigned32 addrdiff = p->addr - addr; addr = p->addr; if (addrdiff < 0x100 && -0x80 < p->change && p->change < 0x80) { if (bytes+4 >= 0x10000-6*4) break; bytes += 2; } else if (addrdiff < 0x10000 && -0x8000 < p->change && p->change < 0x8000) { if (bytes+8 >= 0x10000-6*4) break; bytes += 6; } else break; } { int32 n = (bytes + 3) & ~3L; int32 w = (int32)ITEMFPMAPFRAG; FPFragmentList *fl = (FPFragmentList *)DbgAlloc(sizeof(FPFragmentList)+n-1); char *fp = fl->frag.b; fl->frag.bytes = bytes; fl->codeseg = fpd->codeseg; fl->n = n; fl->frag.marker = w | ((n + 6*4) << 16); fl->frag.codestart = startaddr; /* ECN: function may not have a trailing stack adjust if the final * return is by a branch to an earlier return so use endaddr in * this case. */ if (p == NULL) fl->frag.codesize = fpd->endaddr - startaddr; else fl->frag.codesize = addr - startaddr; fl->frag.saveaddr = saveaddr; fl->frag.initoffset = offset; cdr_(fl) = NULL; *fpmap.frags_tail = fl; fpmap.frags_tail = &cdr_(fl); fpmap.size += (n + 6*4); for (; lastp != p; lastp = cdr_(lastp)) { unsigned32 addrdiff = lastp->addr - startaddr; startaddr = lastp->addr; if (addrdiff < 0x100 && -0x80 < lastp->change && lastp->change < 0x80) { fp[0] = (char)addrdiff; fp[1] = (char)lastp->change; fp += 2; } else { fp[0] = fp[1] = 0; if (target_lsbytefirst) { fp[2] = (char)addrdiff; fp[3] = (char)(addrdiff >> 8); fp[4] = (char)lastp->change; fp[5] = (char)(lastp->change >> 8); } else { fp[2] = (char)(addrdiff >> 8); fp[3] = (char)addrdiff; fp[4] = (char)(lastp->change >> 8); fp[5] = (char)lastp->change; } fp += 6; } offset += lastp->change; } for (; bytes < n; bytes++) fl->frag.b[bytes] = 0; } if (p == NULL) break; saveaddr = NoSaveAddr; addr = p->addr; offset += p->change; } } static void fpmap_write(void) { DataXref *xrefs = NULL; if (fpmap.size != 0) { char h[4]; int32 v[7]; int32 offset = 0; obj_startdebugarea(FPMAPAREANAME); h[0] = LANG_C; h[1] = 4; h[2] = 0; h[3] = ASD_FORMAT_VERSION; v[0] = 0, v[2] = baseseg.len; if (baseseg.len > 0) xrefs = dbg_relocate(xrefs, offset+8, baseseg.sym); v[1] = v[3] = 0; v[4] = 0; v[5] = fpmap.size; v[6] = 0; dbg_hdr(ITEMSECTION, 9*4); obj_writedebug(h, 4); obj_writedebug(v, 7+DBG_INTFLAG); offset += 9*4; { FPFragmentList *fp = fpmap.frags; for (; fp != NULL; fp = cdr_(fp)) { xrefs = dbg_relocate(xrefs, offset+8, fp->codeseg); if (fp->frag.saveaddr == NoSaveAddr) fp->frag.saveaddr = 0; else xrefs = dbg_relocate(xrefs, offset+12, fp->codeseg); obj_writedebug(&fp->frag, 6+DBG_INTFLAG); obj_writedebug(fp->frag.b, fp->n); offset += fp->n + offsetof(ItemFPMapFragment, b); } } obj_enddebugarea(FPMAPAREANAME, xrefs); } } static int32 fpmap_size(void) { return fpmap.size != 9*4 ? fpmap.size : 0; } #endif void dbg_finalise(void) { dbg_init_done = dbg_sub_init_done = NO; } void dbg_final_src_codeaddr(int32 a, int32 b) { IGNORE(a); IGNORE(b); } bool dbg_debugareaexists(char const *name) { if (StrEq(name, DEBUGAREANAME)) return asd_tablesize() != 0; #ifdef TARGET_HAS_FP_OFFSET_TABLES else if (StrEq(name, FPMAPAREANAME)) return fpmap_size() != 0; #endif return NO; } void dbg_writedebug(void) { if (asd_tablesize() != 0) asdtables_write(); #ifdef TARGET_HAS_FP_OFFSET_TABLES if (fpmap_size() != 0) fpmap_write(); #endif } static void dbg_sub_init(void) { dbglist = 0; baseseg.len = 0; dbglistproc = 0; dbglistscope = 0; dbg_filelist = 0, dbg_coord_p = 0; dbg_loclist = 0, dbg_returnlist = 0; /* for safety */ dbg_structRefs = 0; dbgloc = 0; dbg_sub_init_done = YES; #ifdef TARGET_HAS_FP_OFFSET_TABLES fpmap.size = 9*4; fpmap.frags = NULL; fpmap.frags_tail = &fpmap.frags; #endif } void dbg_setformat(char const *form) { oldformat = (form[0] != 0); } bool dbg_needsframepointer(void) { #ifdef TARGET_HAS_FP_OFFSET_TABLES return 0; #else return 1; #endif } void dbg_init(void) { obj_notedebugarea(DEBUGAREANAME); #ifdef TARGET_HAS_FP_OFFSET_TABLES obj_notedebugarea(FPMAPAREANAME); #endif if (!dbg_sub_init_done) dbg_sub_init(); baseseg.sym = bindsym_(codesegment); if (usrdbg(DBG_ANY)) { /* leave space for the DEB_SECTION item */ DbgList *p = DbgListAlloc(DEB_SECTION); p->debsort = ITEMSECTION; p->car.DEB_SECTION.name = objectfile == NULL ? "" : objectfile; p->car.DEB_SECTION.codeseg = bindsym_(codesegment); p->cdr = NULL; { DbgList *q, **pp = &dbglist; for (; (q = *pp) != NULL; pp = &q->cdr) continue; *pp = p; } dbgloc += 32 + padstrlen(strlen(p->car.DEB_SECTION.name)); if (usrdbg(DBG_LINE)) { Deb_filelist *x = dbg_filelist; for (; x != NULL; x = x->nextfile) { Deb_filecoord *l = x->linelist; for (; l != NULL; l = l->nextinfile) l->codeseg = bindsym_(codesegment); } } } dbg_init_done = YES; } #endif /* TARGET_HAS_ASD */ #endif /* TARGET_HAS_DEBUGGER */ /* End of arm/asd.c */
stardot/ncc
cppint/options.h
<reponame>stardot/ncc /* * options.h -- compiler configuration options set at compile time * Copyright (C) Acorn Computers Ltd. 1988 * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _options_LOADED #define _options_LOADED /* * The following conditional settings allow the produced compiler (TARGET) * to depend on the HOST (COMPILING_ON) environment. * Note that we choose to treat this independently of the target-machine / * host-machine issue. */ #define CPLUSPLUS 1 #define USE_PP #define NO_LISTING_OUTPUT 1 #define NO_CONFIG 1 #define NO_OBJECT_OUTPUT 1 #define NO_DEBUGGER 1 #define NO_ASSEMBLER_OUTPUT 1 #define TARGET_VTAB_ELTSIZE 4 /* for indirect VTABLEs optimised for single inheritance */ #include "toolver.h" #define NON_RELEASE_VSN TOOLVER_ARMCPP /* Expire this version at 00:00:01 on Saturday 01 Oct 94 */ /*#define UNIX_TIME_LIMIT 780969601 */ #define TARGET_ENDIANNESS_CONFIGURABLE 1 /* #define TARGET_DEFAULT_BIGENDIAN 0 */ /* 1 => bigendian default */ /* 0 => littleendian default */ /* unset => defaults to host */ #define DISABLE_ERRORS 1 /* -- to enable -Exyz... error suppression */ #define EXTENSION_SYSV 1 /* -- to allow #ident ... */ # define TARGET_SYSTEM "C Interpreter" # define HOST_WANTS_NO_BANNER 1 # ifndef DRIVER_OPTIONS /* -D__arm done by TARGET_PREDEFINES */ # define DRIVER_OPTIONS {NULL} # endif # define C_INC_VAR "ARMINC" # define C_LIB_VAR "ARMLIB" #ifndef RELEASE_VSN # define ENABLE_ALL 1 /* -- to enable all debugging options */ #endif /* mac-specific options - find a better home for these sometime! */ #ifdef macintosh /* The origin of time is 0th Jan 1904... */ # ifdef UNIX_TIME_LIMIT # define TIME_LIMIT (UNIX_TIME_LIMIT+(66*365+16)*24*3600) # endif # define NO_STATIC_BANNER 1 pascal void SpinCursor(short increment); /* copied from CursorCtl.h */ # define ExecuteOnSourceBufferFill() SpinCursor(1) #ifdef TARGET_IS_NEWTON # define HOST_OBJECT_INCLUDES_SOURCE_EXTN 1 /* .c -> .c.o */ # define EXTENSION_COUNTED_STRINGS 1 /* to enable Pascal-style strings */ # define EXTENSION_UNSIGNED_STRINGS 1 /* and they are unsigned */ # define ALLOW_KEYWORDS_IN_HASHIF 1 /* to allow keywords in #if expns */ # define ALLOW_WHITESPACE_IN_FILENAMES 1 /* to allow as it says... */ # define ONLY_WARN_ON_NONPRINTING_CHAR 1 /* to do as it says... */ # define HOST_DOES_NOT_FORCE_TRAILING_NL 1 # define HOST_WANTS_NO_BANNER 1 /* no routine banner output */ # define DISABLE_ERRORS 1 # define TARGET_WANTS_LINKER_TO_RESOLVE_FUNCTION_REFERENCES 1 # define HOST_CANNOT_INVOKE_ASSEMBLER 1 # define HOST_CANNOT_INVOKE_LINKER 1 # define PUT_FILE_NAME_IN_AREA_NAME 1 # define CHAR_NL '\n' # define CHAR_CR '\r' # define CFRONT_MODE_WARN_LACKS_STORAGE_TYPE 0 # define HOST_DOESNT_WANT_FP_OFFSET_TABLES 1 #endif #else /* NOT macintosh */ # ifdef UNIX_TIME_LIMIT # define TIME_LIMIT UNIX_TIME_LIMIT # endif #endif #ifdef TIME_LIMIT # define VENDOR_NAME "Advanced RISC Machines Limited" #endif #ifdef CPLUSPLUS # ifndef CFRONT_MODE_WARN_LACKS_STORAGE_TYPE # define CFRONT_MODE_WARN_LACKS_STORAGE_TYPE 1 # endif #endif #define MSG_TOOL_NAME "armcc" /* used to load correct NLS message file */ #endif /* end of cpparm/options.h */
stardot/ncc
mip/regsets.h
<gh_stars>0 /* * regsets.h, version 1a * Copyright (C) Acorn Computers Ltd., 1988. * Copyright (C) Codemist Ltd., 1988. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _regsets_h #define _regsets_h 1 #ifndef _defs_LOADED # include "defs.h" #endif #ifndef _cgdefs_LOADED # include "cgdefs.h" #endif /* The following line is a place holder: use discard2 not rldiscard. */ #define rldiscard(l) discard2(l) /* place holder only */ typedef void RProc2(int32, VoidStar); typedef void RProc1(int32); /* * vregsets - a space efficient representation for sets of integers which are * expected to be too sparse for a straghtforward bitmap, and too dense for * a Lisp-style list. * The name is historical, from the origins of this representation in regalloc, * but it is useful (and used) for sets of other things besides registers. * * The precise representation of a vregset is not revealed. However, it is * guaranteed that NULL is A valid value for an empty vregset. */ typedef enum { AT_Glob, AT_Bind, AT_Syn } AllocType; typedef struct { AllocType alloctype; unsigned32 *statsloc, *statsloc1, *statsbytes; } VRegSetAllocRec; /* A (pointer to a) record of this type gets passed to any vregset procedure * which may allocated new structure. * allocproc should be one of (Syn, Bind, Glob)Alloc * statsloc is incremented by one for each piece of structure added to the * set * statsloc1 is incremented by one for each freshly allocated piece of * structure (rather than reclaimed from a free chain) * statsbytes is incremented by the size of each freshly allocated piece of * structure. */ extern VRegSetP vregset_insert(int32 regno, VRegSetP set, bool *oldp, VRegSetAllocRec *allocrec); /* * Add an element to the set. *oldp is set TRUE if it was already in the set, * FALSE otherwise. */ extern bool vregset_member(int32 regno, VRegSetP set); extern VRegSetP vregset_delete(int32 regno, VRegSetP set, bool *oldp); /* * Remove an element from the set. *oldp is set FALSE if it was in the set, * TRUE otherwise */ /* * difference, union and intersection destructively modify the set which * is their first argument (and return the modified set as result) */ extern VRegSetP vregset_difference(VRegSetP s1, VRegSetP s2); extern VRegSetP vregset_union(VRegSetP s1, VRegSetP s2, VRegSetAllocRec *allocrec); extern VRegSetP vregset_intersection(VRegSetP s1, VRegSetP s2); extern VRegSetP vregset_copy(VRegSetP set, VRegSetAllocRec *allocrec); #define VR_SUBSET -1 #define VR_EQUAL 0 #define VR_SUPERSET 1 #define VR_UNORDERED 2 extern int vregset_compare(VRegSetP s1, VRegSetP s2); /* Returns the ordering of r1 wrt r2 */ #define vregset_equal(s1,s2) (vregset_compare(s1,s2)==VR_EQUAL) extern void vregset_map(VRegSetP set, RProc2 *dothis, VoidStar arg); /* * For each x in set , call dothis(x, arg). * Dothis may not access set in any way (not merely not modify it). */ extern void vregset_map1(VRegSetP set, RProc1 *dothis); /* As vregset_map, except that the call is dothis(x) */ extern void vregset_discard(VRegSetP set); extern void vregset_init(void); /* * Relations - symmetric relations between integers. The representation is * designed for the same conditions as that of vregsets. * Only a minimal set of operations are provided (those currently wanted by * clients). */ typedef struct SquareLists *Relation; /* * The precise representation of a Relation is not revealed. NULL is not a * valid Relation value - a new Relation must be given a value returned by * relation_init. */ typedef struct { AllocType alloctype; unsigned32 *statsloc, *statsbytes; } RelationAllocRec; extern bool relation_member(int32 a, int32 b, Relation matrix); extern bool relation_add(int32 a, int32 b, Relation matrix, RelationAllocRec *allocrec); extern bool relation_delete(int32 a, int32 b, Relation matrix); extern void relation_map(int32 a, Relation matrix, RProc2 *dothis, VoidStar arg); /* For all x such that x is related to a, call dothis(x, arg). * dothis may not access the Relation in any way. */ extern void relation_map1(int32 a, Relation matrix, RProc1 *dothis); /* As relation_map, except that the call is dothis(x) */ extern void relation_mapanddelete(int32 a, Relation matrix, RProc2 *dothis, VoidStar arg); extern Relation relation_init(RelationAllocRec *allocrec, int32 size, unsigned32 *statsloc); #endif /* end of regsets.h */
stardot/ncc
tests/2581.c
/* ARM C library test */ /* Copyright (C) Advanced RISC Machines, 1997. All Rights Reserved */ /* SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #define LONG_LONG #include <stdlib.h> #include <limits.h> #include "testutil.h" #include "mathtest.h" #include "mathtest.c" /* double precision tests */ static void t2581_dnan(void) { double_ints d; long l; unsigned long u; ivo(); /* clear IVO flag */ dset_to_qnan(&d); l = (long)d.f; EQI(l, 0); EQI(ivo(), TRUE); u = (unsigned long)d.f; EQU(u, 0); EQU(ivo(), TRUE); dneg(&d); l = (long)d.f; EQI(l, 0); EQU(ivo(), TRUE); u = (unsigned long)d.f; EQU(u, 0); EQU(ivo(), TRUE); } static void t2581_dnan_ll(void) { double_ints d; #ifdef LONG_LONG long long ll; unsigned long long ull; ivo(); /* clear IVO flag */ dset_to_qnan(&d); ll = (long long)d.f; EQLL(ll, 0); EQU(ivo(), TRUE); ull = (unsigned long long)d.f; EQUU(ull, 0); EQU(ivo(), TRUE); dneg(&d); ll = (long long)d.f; EQLL(ll, 0); EQU(ivo(), TRUE); ull = (unsigned long long)d.f; EQUU(ull, 0); EQU(ivo(), TRUE); #endif } #ifdef LONG_LONG #define LL_MAX 0x7fffffffffffffffLL #define ULL_MAX 0xffffffffffffffffULL #define LL_MIN (~LL_MAX) #define ULL_MIN 0 #endif static void t2581_dsigned(void) { double_ints d; long l; ivo(); /* clear IVO flag */ /* long */ /* double -> long [overflow] */ d.f = (double)(INT_MAX/2+1); l = (long)d.f; /* does not overflow */ EQI(l, INT_MAX/2 + 1); /* should return INT_MAX/2 + 1 */ EQU(ivo(), FALSE); d.f *= 2.0; /* should send overflowing */ l = (long)d.f; EQI(l, INT_MAX); /* overflowed - returns INT_MAX */ EQU(ivo(), TRUE); d.f = (double)INT_MAX; /* exact */ l = (long)d.f; EQI(l, INT_MAX); EQU(ivo(), FALSE); dsucc(&d); l = (long)d.f; /* overflows */ EQI(l, INT_MAX); /* should return INT_MAX */ EQU(ivo(), TRUE); l = INT_MIN; d.f = (double)l; /* exact */ l = (long)d.f; EQU(ivo(), FALSE); dpred(&d); /* into overflow */ l = (long)d.f; EQI(l, INT_MIN); EQU(ivo(), TRUE); } static void t2581_dsigned_ll(void) { #ifdef LONG_LONG double_ints d; long long ll; ivo(); /* clear IVO flag */ ll = LL_MAX; d.f = (double)ll; /* rounded up */ dpred(&d); ll = (long long)d.f; /* truncated */ EQLL(ll, (LL_MAX & ~((1ull << (11-1))-1ull))); EQU(ivo(), FALSE); dsucc(&d); ll = (long long)d.f; /* overflows */ EQLL(ll, LL_MAX); EQU(ivo(), TRUE); ll = LL_MIN; /* exact */ d.f = (double)ll; ll = (long long)d.f; EQLL(ll, LL_MIN); EQU(ivo(), FALSE); dpred(&d); /* overflows now */ ll = (long long)d.f; EQLL(ll, LL_MIN); EQU(ivo(), TRUE); #endif } static void t2581_dunsigned(void) { double_ints d; unsigned long u; ivo(); /* clear IVO flag */ /* unsigned */ /* double -> unsigned long [-ve] */ dset_to_mone(&d); u = (unsigned long)d.f; /* should fail - invalid */ EQU(u, 0); EQU(ivo(), TRUE); /* double -> unsigned long [overflow] */ d.f = UINT_MAX/2; dsucc(&d); /* big */ u = (unsigned long)d.f; /* should not overflow */ EQU(u, UINT_MAX/2+1); EQU(ivo(), FALSE); /* double -> unsigned long [overflow] */ d.f = (double)UINT_MAX; u = (unsigned long)d.f; /* should not overflow */ EQU(u, UINT_MAX); EQU(ivo(), FALSE); dsucc(&d); u = (unsigned long)d.f; /* overflows */ EQU(u, UINT_MAX); EQU(ivo(), TRUE); } static void t2581_dunsigned_ll(void) { #ifdef LONG_LONG double_ints d; unsigned long long ull; ivo(); /* clear IVO flag */ dset_to_mone(&d); ull = (unsigned long long)d.f; /* not representable */ EQUU(ull, 0); EQU(ivo(), TRUE); ull = ULL_MAX; d.f = (double)ull; /* doesn't quite fit - rounded up */ dpred(&d); ull = (unsigned long long)d.f; /* truncated */ EQUU(ull, ULL_MAX & ~((1ull << 11) - 1ull)); EQU(ivo(), FALSE); dsucc(&d); ull = (unsigned long long)d.f; /* overflows */ EQUU(ull, ULL_MAX); /* should return ull_max */ EQU(ivo(), TRUE); #endif } static void t2581_dinf(void) { double_ints d; long l; unsigned long u; ivo(); /* clear IVO flag */ dset_to_inf(&d); l = (long)d.f; EQI(l, INT_MAX); EQU(ivo(), TRUE); u = (unsigned long)d.f; EQU(u, UINT_MAX); EQU(ivo(), TRUE); dneg(&d); l = (long)d.f; EQI(l, INT_MIN); EQU(ivo(), TRUE); u = (unsigned long)d.f; EQU(u, 0); EQU(ivo(), TRUE); } static void t2581_dinf_ll(void) { #ifdef LONG_LONG double_ints d; long long ll; unsigned long long ull; ivo(); /* clear IVO flag */ dset_to_inf(&d); ll = (long long)d.f; EQLL(ll, LL_MAX); EQU(ivo(), TRUE); ull = (unsigned long long)d.f; EQUU(ull, ULL_MAX); EQU(ivo(), TRUE); dneg(&d); ll = (long long)d.f; EQLL(ll, LL_MIN); EQU(ivo(), TRUE); ull = (unsigned long long)d.f; EQUU(ull, 0); EQU(ivo(), TRUE); #endif } /* single precision tests */ static void t2581_fsigned(void) { float_int f; long l; ivo(); /* clear IVO flag */ fset_to_one(&f); l = (long)f.f; EQI(l, 1); EQU(ivo(), FALSE); l = INT_MAX; f.f = (float)l; /* does not fit - rounded up */ fpred(&f); l = (long)f.f; EQI(l, INT_MAX & ~((1ul << (8-1)) - 1)); EQU(ivo(), FALSE); fsucc(&f); l = (long)f.f; /* overflows */ EQI(l, INT_MAX); /* should return INT_MAX */ EQU(ivo(), TRUE); l = INT_MIN; f.f = (float)l; /* fits exactly */ l = (long)f.f; EQI(l, INT_MIN); /* with no error */ EQU(ivo(), FALSE); fpred(&f); /* take into underflow */ l = (long)f.f; EQI(l, INT_MIN); EQU(ivo(), TRUE); } static void t2581_fsigned_ll(void) { #ifdef LONG_LONG float_int f; long long ll; ivo(); /* clear IVO flag */ ll = LL_MAX; f.f = (float)ll; /* doesn't quite fit - rounded up */ fpred(&f); /* bring into range */ ll = (long long)f.f; /* truncated */ EQLL(ll, LL_MAX & ~((1ull << (32+8-1)) - 1ull)); EQU(ivo(), FALSE); fsucc(&f); ll = (long long)f.f; /* overflows */ EQLL(ll, LL_MAX); EQU(ivo(), TRUE); ll = LL_MIN; /* exact */ f.f = (float)ll; ll = (long long)f.f; EQLL(ll, LL_MIN); EQU(ivo(), FALSE); fpred(&f); /* take into overflow */ ll = (long long)f.f; EQLL(ll, LL_MIN); EQU(ivo(), TRUE); #endif } static void t2581_funsigned(void) { float_int f; unsigned long u; ivo(); /* clear IVO flag */ /* float -> unsigned long [-ve] */ fset_to_mone(&f); u = (unsigned long)f.f; /* should fail - invalid */ EQU(u, 0); EQU(ivo(), TRUE); /* float -> unsigned long [overflow] */ f.f =(float)(UINT_MAX/2); /* not >UINT_MAX, but large */ fsucc(&f); u = (unsigned long)f.f; /* should not overflow */ /* since float's don't have sufficient precision, this won't return * UINT_MAX/2+1, but UINT_MAX/2 + 1<<(length_of_float_exponent+1)+1 */ EQU(u, UINT_MAX/2 + (1<<8) + 1); EQU(ivo(), FALSE); f.f *= 2.0; /* causes overflow */ u = (unsigned long)f.f; /* overflows */ EQU(u, UINT_MAX); EQU(ivo(), TRUE); u = UINT_MAX; f.f= (float)UINT_MAX; /* rounds up */ fpred(&f); u = (unsigned long)f.f; /* just fits */ EQU(u, UINT_MAX & ~((1ul << 8)-1ul)); EQU(ivo(), FALSE); fsucc(&f); u = (unsigned long)f.f; /* overflows */ EQU(u, UINT_MAX); EQU(ivo(), TRUE); } static void t2581_funsigned_ll(void) { #ifdef LONG_LONG float_int f; unsigned long long ull; ivo(); /* clear IVO flag */ fset_to_mone(&f); ull = (unsigned long long)f.f; /* not representable */ EQUU(ull, 0); EQU(ivo(), TRUE); ull = ULL_MAX; f.f = (float)ull; /* doesn't quite fit - rounded up */ fpred(&f); ull = (unsigned long long)f.f; /* truncated */ EQUU(ull, (ULL_MAX & ~((1ull << (32+8))-1ull))); EQU(ivo(), FALSE); fsucc(&f); ull = (unsigned long long)f.f; /* overflows */ EQUU(ull, ULL_MAX); /* should return ull_max */ EQU(ivo(), TRUE); #endif } static void t2581_fnan(void) { float_int f; long l; unsigned long u; ivo(); /* clear IVO flag */ fset_to_qnan(&f); l = (long)f.f; EQI(l, 0); EQU(ivo(), TRUE); u = (unsigned long)f.f; EQU(u, 0); EQU(ivo(), TRUE); fneg(&f); l = (long)f.f; EQI(l, 0); EQU(ivo(), TRUE); u = (unsigned long)f.f; EQU(u, 0); EQU(ivo(), TRUE); } static void t2581_fnan_ll(void) { #ifdef LONG_LONG float_int f; long long ll; unsigned long long ull; fset_to_qnan(&f); ll = (long long)f.f; EQLL(ll, 0); EQU(ivo(), TRUE); ull = (unsigned long long)f.f; EQUU(ull, 0); EQU(ivo(), TRUE); fneg(&f); ll = (long long)f.f; EQLL(ll, 0); EQU(ivo(), TRUE); ull = (unsigned long long)f.f; EQUU(ull, 0); EQU(ivo(), TRUE); #endif } static void t2581_finf(void) { float_int f; long l; unsigned long u; ivo(); /* clear IVO flag */ fset_to_inf(&f); l = (long)f.f; EQI(l, INT_MAX); EQU(ivo(), TRUE); u = (unsigned long)f.f; EQU(u, UINT_MAX); EQU(ivo(), TRUE); fneg(&f); l = (long)f.f; EQI(l, INT_MIN); EQU(ivo(), TRUE); u = (unsigned long)f.f; EQU(u, 0); EQU(ivo(), TRUE); } static void t2581_finf_ll(void) { #ifdef LONG_LONG float_int f; long long ll; unsigned long long ull; ivo(); /* clear IVO flag */ fset_to_inf(&f); ll = (long long)f.f; EQLL(ll, LL_MAX); EQU(ivo(), TRUE); ull = (unsigned long long)f.f; EQUU(ull, ULL_MAX); EQU(ivo(), TRUE); fneg(&f); ll = (long long)f.f; EQLL(ll, LL_MIN); EQU(ivo(), TRUE); ull = (unsigned long long)f.f; EQUU(ull, 0); EQU(ivo(), TRUE); #endif } int main(void) { /* disable the IVO exception */ __fp_status(__fpsr_IOE+__fpsr_IOC, 0); BeginTest(); /* * double tests */ t2581_dnan(); t2581_dinf(); t2581_dsigned(); t2581_dunsigned(); t2581_dnan_ll(); t2581_dinf_ll(); t2581_dsigned_ll(); t2581_dunsigned_ll(); /* * float tests */ t2581_fnan(); t2581_finf(); t2581_fsigned(); t2581_funsigned(); t2581_fnan_ll(); t2581_finf_ll(); t2581_fsigned_ll(); t2581_funsigned_ll(); EndTest(); return 0; }
stardot/ncc
arm/mcdep.c
<gh_stars>0 /* * mcdep.c - miscellaneous target-dependent things. * Copyright (C) Acorn Computers Ltd., 1988. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <ctype.h> #include <string.h> #include <stdlib.h> #include "globals.h" #include "mcdep.h" #include "mcdpriv.h" #include "errors.h" #include "pp.h" #include "compiler.h" #include "arminst.h" #include "toolenv.h" #include "toolenv2.h" #include "tooledit.h" int arthur_module; int32 config; int32 pcs_flags; FPU_Type fpu_type; static int config_mulbits; /* number of bits per cycle */ static int config_multime; /* minimum cycles for MUL */ static int config_mlatime; /* minimum cycles for MLA */ typedef struct { char const *name; char const *val; } EnvItem; #define str(s) #s #define xstr(s) str(s) static EnvItem const builtin_defaults[] = { #if (PCS_DEFAULTS & PCS_CALLCHANGESPSR) { "-apcs.32bit", "#/32"}, #else { "-apcs.32bit", "#/26"}, #endif #if (PCS_DEFAULTS & PCS_NOSTACKCHECK) { "-apcs.swst", "#/noswst"}, #else { "-apcs.swst", "#/swst"}, #endif #if (PCS_DEFAULTS & PCS_REENTRANT) { "-apcs.reent", "#/reent"}, #else { "-apcs.reent", "#/noreent"}, #endif #if (PCS_DEFAULTS & PCS_SOFTFP) { "-apcs.softfp", "#/softfp"}, #else { "-apcs.softfp", "#/hardfp"}, #endif #if (PCS_DEFAULTS & PCS_FPE3) { "-apcs.fpis", "#/fpe3"}, #else { "-apcs.fpis", "#/fpe2"}, #endif #if (PCS_DEFAULTS & PCS_NOFP) { "-apcs.fp", "#/nofp"}, #else { "-apcs.fp", "#/fp"}, #endif #if (PCS_DEFAULTS & PCS_FPREGARGS) { "-apcs.fpr", "#/fpregargs"}, #else { "-apcs.fpr", "#/nofpregargs"}, #endif #if (PCS_DEFAULTS & PCS_INTERWORK) { "-apcs.inter", "#/interwork"}, { "-cpu", "#ARM7TM"}, /* Which automagically sets -arch */ #else { "-apcs.inter", "#/nointerwork"}, { "-cpu", "#ARM6"}, /* Which automagically sets -arch */ #endif #if (PCS_DEFAULTS & PCS_UNWIDENED_NARROW_ARGS) { "-apcs.wide", "#/narrow"}, #else { "-apcs.wide", "#/wide"}, #endif { "-zr", "=" xstr(LDM_REGCOUNT_MAX_DEFAULT) }, { "-zi", "=" xstr(INTEGER_LOAD_MAX_DEFAULT) }, { "-zap", "=" xstr(STRUCT_PTR_ALIGN_DEFAULT) }, { "-zas", "=4" }, #ifdef NO_UNALIGNED_LOADS { "-za", "=1"}, #else { "-za", "=0"}, #endif { ".areaperfn", "=-z+o" }, #ifdef CPLUSPLUS { ".debugtable", "=-dwarf" }, #else { ".debugtable", "=-asd" }, #endif { "-fpu", "#fpa"}, {NULL, NULL} }; int mcdep_toolenv_insertdefaults(ToolEnv *t) { EnvItem const *p = builtin_defaults; for (; p->name != NULL; p++) { ToolEdit_InsertStatus rc = tooledit_insert(t, p->name, p->val); if (rc == TE_Failed) return 1; } return 0; } #define MULSPD(bits, mul, mla) bits, mul, mla #define ARCH_2 PROCESSOR_HAS_26BIT_MODE #define ARCH_3 PROCESSOR_HAS_26BIT_MODE|PROCESSOR_HAS_32BIT_MODE #define ARCH_3G PROCESSOR_HAS_32BIT_MODE #define ARCH_3M ARCH_3|PROCESSOR_HAS_MULTIPLY #define ARCH_4 ARCH_3|(PROCESSOR_HAS_MULTIPLY|PROCESSOR_HAS_HALFWORDS) #define ARCH_4T ARCH_3|(PROCESSOR_HAS_MULTIPLY|PROCESSOR_HAS_HALFWORDS)|PROCESSOR_HAS_THUMB static Processor const p_arm6 = {"#ARM6", ARCH_3, "#3", MULSPD(2,2,2) }; static Processor const p_arm7 = {"#ARM7", ARCH_3, "#3", MULSPD(2,2,2) }; static Processor const p_arm7M = {"#ARM7M", ARCH_3M, "#3M",MULSPD(8,2,3) }; static Processor const p_arm7TM = {"#ARM7TM", ARCH_4T, "#4T",MULSPD(8,2,3) }; static Processor const p_arm8 = {"#ARM8", ARCH_4, "#4", MULSPD(8,3,3) }; static Processor const p_strongarm = {"#StrongARM1", ARCH_4, "#4", MULSPD(12,1,1)}; static Processor const p_sa1500 = {"#SA1500", ARCH_4, "#4", MULSPD(12,1,1)}; static Processor const p_arm2 = {"#ARM2", ARCH_2, "#2", MULSPD(2,2,2) }; static Processor const p_arm3 = {"#ARM3", ARCH_2, "#2", MULSPD(2,2,2) }; static Processor const *const processors[] = { &p_arm6, /* default: must come first */ &p_arm7, &p_arm7M, &p_arm7TM, &p_arm8, &p_strongarm, &p_sa1500, &p_arm2, &p_arm3, }; static const char *cistrchr(const char *s, int ch) { char c1 = (char)safe_tolower(ch); for (;;) { char c = safe_tolower(*s++); if (c == c1) return s - 1; if (c == 0) return 0; } } int EnumerateProcessors(ProcessorEnumProc *f, void *arg) { Uint i; for (i = 0; i < sizeof processors / sizeof processors[0]; i++) { int rc = f(arg, processors[i]); if (rc != 0) return rc; } return 0; } static Processor const *LookupProcessor_i(char const *key, size_t keylen) { Uint i; const char *keyopts = strpbrk(key, "0123456789"); const Processor *best = NULL; int bestval = 0; if (keyopts == NULL) keyopts = key + keylen; else keyopts = keyopts + strspn(keyopts, "0123456789"); for (i = 0; i < sizeof processors / sizeof processors[0]; i++) { /* match things like ARM700TDMI with ARM7TM */ const char *matchend = strpbrk(processors[i]->name, "0123456789"); size_t matchlen; if (matchend == NULL) matchlen = strlen(&processors[i]->name[1]); else matchlen = matchend - processors[i]->name; if (cistrneq(key, &processors[i]->name[1], matchlen)) { if (keyopts[0] == '\0' || keyopts[0] == '/') { best = processors[i]; break; } else { bool matches = YES; const char *p = keyopts; const char *opts = &processors[i]->name[1] + matchlen; int matchval = 0; for (; p < key + keylen; ++p) { int ch = safe_tolower(*p); if (ch == 'd' || ch == 'i') continue; if (cistrchr(opts, ch) != NULL) ++matchval; else { matches = NO; break; } } if (!matches) continue; if (bestval < matchval) { bestval = matchval; best = processors[i]; } } } } return best; } Processor const *LookupProcessor(char const *key) { return LookupProcessor_i(key, strlen(key)); } Processor const *LookupArchitecture(char const *key) { Uint i; for (i = 0; i < sizeof processors / sizeof processors[0]; i++) if (cistreq(processors[i]->arch+1, key)) return processors[i]; return NULL; } bool mcdep_config_option(char name, char const tail[], ToolEnv *t) { char b[64]; switch (safe_tolower(name)) { #ifndef TARGET_IS_UNIX case 'm': { int m = 1; if (isdigit(tail[0])) m += (tail[0]-'0'); sprintf(b, "=%d", m); tooledit_insert(t, "-zm", b); return YES; } #endif case 'a': if (tail[0] == '\0' || isdigit(tail[0])) { tooledit_insert(t, "-za", tail[0] == '0' ? "=0" : "=1"); return YES; } break; case 'd': tooledit_insert(t, "-zd", tail[0] == '0' ? "=0" : "=1"); return YES; case 'i': return tooledit_insertwithjoin(t, "-zi", '=', tail) != TE_Failed; case 'r': return tooledit_insertwithjoin(t, "-zr", '=', tail) != TE_Failed; } return NO; } typedef struct { char const *opt; char const *name; char const *val; } kw; static kw const pcs_keywords[] = { { "reentrant", "-apcs.reent", "#/reent" }, { "nonreentrant", "-apcs.reent", "#/noreent"}, { "noreentrant", "-apcs.reent", "#/noreent"}, { "reent", "-apcs.reent", "#/reent" }, { "nonreent", "-apcs.reent", "#/noreent"}, { "noreent", "-apcs.reent", "#/noreent"}, { "fpe3", "-apcs.fpis", "#/fpe3"}, { "fpe2", "-apcs.fpis", "#/fpe2"}, { "swstackcheck", "-apcs.swst", "#/swst"}, { "noswstackcheck", "-apcs.swst", "#/noswst"}, { "swst", "-apcs.swst", "#/swst"}, { "noswst", "-apcs.swst", "#/noswst"}, { "26bit", "-apcs.32bit", "#/26"}, { "32bit", "-apcs.32bit", "#/32"}, { "26", "-apcs.32bit", "#/26"}, { "32", "-apcs.32bit", "#/32"}, { "fpregargs", "-apcs.fpr", "#/fpregargs"}, { "nofpregargs", "-apcs.fpr", "#/nofpregargs"}, { "fpr", "-apcs.fpr", "#/fpregargs"}, { "nofpr", "-apcs.fpr", "#/nofpregargs"}, { "fp", "-apcs.fp", "#/fp"}, { "nofp", "-apcs.fp", "#/nofp"}, { "softfp", "-apcs.softfp", "#/softfp"}, { "softdoubles", "-apcs.softfp", "#/softdoubles"}, { "softd", "-apcs.softfp", "#/softdoubles"}, { "hardfp", "-apcs.softfp", "#/hardfp"}, { "interwork", "-apcs.inter", "#/interwork"}, { "nointerwork", "-apcs.inter", "#/nointerwork"}, { "inter", "-apcs.inter", "#/interwork"}, { "nointer", "-apcs.inter", "#/nointerwork"}, { "wide", "-apcs.wide", "#/wide"}, { "narrow", "-apcs.wide", "#/narrow"} }; static char const * const debug_table_keywords[] = { #ifdef TARGET_HAS_ASD "-asd", "-asd-old", #endif #ifdef TARGET_HAS_DWARF "-dwarf1", "-dwarf2", "-dwarf", #endif "" }; KW_Status mcdep_keyword(char const *key, char const *nextarg, ToolEnv *t) { char str[64]; int ch; unsigned i; bool sawproc = NO; if (cistreq(key, "-apcs")) { Uint count = 0; if (nextarg == NULL) return KW_MISSINGARG; if (nextarg[0] == '3') nextarg++; for (;; count++) { ch = *nextarg; i = 0; if (ch == 0) return (count == 0) ? KW_BADNEXT: KW_OKNEXT; if (ch != '/') return KW_BADARG; for (; (ch = *++nextarg) != '/' && ch != 0; ) str[i++] = safe_tolower(ch); str[i] = 0; for (i = 0; i < sizeof(pcs_keywords) / sizeof(pcs_keywords[0]); i++) if (StrEq(str, pcs_keywords[i].opt)) { tooledit_insert(t, pcs_keywords[i].name, pcs_keywords[i].val); break; } if (i == sizeof(pcs_keywords) / sizeof(pcs_keywords[0])) return KW_BADNEXT; } } for (i = 0; i < sizeof(debug_table_keywords) / sizeof(debug_table_keywords[0]); i++) if (cistreq(key, debug_table_keywords[i])) { tooledit_insertwithjoin(t, ".debugtable", '=', debug_table_keywords[i]); return KW_OK; } if (cistreq(key, "-fpu")) { if (nextarg == NULL) return KW_MISSINGARG; if (cistreq(nextarg, "fpa")) { tooledit_insert(t, "-fpu", "#fpa"); return KW_OKNEXT; } else if (cistreq(nextarg, "amp")) { tooledit_insert(t, "-fpu", "#amp"); return KW_OKNEXT; } return KW_BADNEXT; } /* The '-proc' form is preferred since '-armxxx' is passed to the linker without complaint. */ if (cistreq(key, "-arch")) { Uint i; if (nextarg == NULL) return KW_MISSINGARG; for (i = 0; i < sizeof processors / sizeof processors[0]; i++) if (cistreq(nextarg, &processors[i]->arch[1])) { tooledit_insert(t, "-cpu", "#generic"); tooledit_insert(t, "-arch", processors[i]->arch); return KW_OKNEXT; } return KW_BADNEXT; } else if (cistreq(key, "-proc") || cistreq(key, "-processor") || cistreq(key, "-cpu")) { if (nextarg == NULL) return KW_MISSINGARG; sawproc = YES; key = nextarg; } else if (key[0] == '-') key = key + 1; else return KW_NONE; { char const *sfx = strchr(key, '/'); size_t keylen = (sfx == NULL) ? strlen(key) : sfx - key; Processor const *cpu = LookupProcessor_i(key, keylen); if (cpu == NULL) return sawproc ? KW_BADNEXT : KW_NONE; if (cpu->flags & PROCESSOR_HAS_HALFWORDS && sfx != NULL) { if (cistreq(sfx + 1, "nohalfwordstores")) tooledit_insert(t, ".nohalfwordstores", "?"); else return sawproc ? KW_BADNEXT : KW_BADARG; } else if (sfx != NULL) return sawproc ? KW_BADNEXT : KW_BADARG; tooledit_insert(t, "-cpu", cpu->name); return sawproc ? KW_OKNEXT : KW_OK; } } static char lib_variant[16]; void target_lib_variant(char *b) { strcpy(b, lib_variant); } #ifndef COMPILING_ON_ARM char const *target_lib_name(ToolEnv *t, char const *name) { static char namebuf[64]; int len = strlen(name); IGNORE(t); if (name[len-2] == '.' && name[len-1] == 'o') { memcpy(namebuf, name, len-2); target_lib_variant(&namebuf[len-2]); return namebuf; } return name; } #endif char *target_asm_options(ToolEnv *t) { int i; static char v[32]; config_init(t); strcpy(v, (config & CONFIG_BIG_ENDIAN) ? "-bi" : "-li"); i = 3; if (pcs_flags & (PCS_REENTRANT+PCS_FPE3+PCS_CALLCHANGESPSR)) { if (i != 0) v[i++] = ' '; strcpy(&v[i], "-apcs 3"); if (pcs_flags & PCS_REENTRANT) strcat(&v[i], "/reent"); strcat(&v[i], (pcs_flags & PCS_CALLCHANGESPSR) ? "/32bit" : "/26bit"); } return v; } /*************************************************************/ /* */ /* Code to configure compiler for host system */ /* */ /*************************************************************/ #if 0 #ifdef TARGET_HAS_DATA_VTABLES bool mcdep_data_vtables(void) { return !!(pcs_flags & PCS_INTERWORK); } #endif #endif typedef struct { char const *name; char const *val; uint32 flag; } Opt; static Opt const config_opts[] = { {".bytesex", "=-bi", CONFIG_BIG_ENDIAN}, {"-apcs.reent", "#/reent", CONFIG_REENTRANT_CODE}, {"-apcs.softfp", "#/softfp", CONFIG_SOFTWARE_FP}, {"-apcs.softfp", "#/softdoubles", CONFIG_SOFTWARE_DOUBLES}, {"-apcs.fpr", "#/fpregargs", CONFIG_FPREGARGS}, {"-apcs.wide", "#/narrow", CONFIG_UNWIDENED_NARROW_ARGS}, {"-za", "=1", CONFIG_NO_UNALIGNED_LOADS}, {"-zap", "=1", CONFIG_STRUCT_PTR_ALIGN}, {NULL, NULL, 0} }; static Opt const pcs_opts[] = { {"-apcs.32bit", "#/32", PCS_CALLCHANGESPSR}, {"-apcs.swst", "#/noswst", PCS_NOSTACKCHECK}, {"-apcs.reent", "#/reent", PCS_REENTRANT}, {"-apcs.fpis", "#/fpe3", PCS_FPE3}, {"-apcs.fp", "#/nofp", PCS_NOFP}, {"-apcs.inter", "#/interwork", PCS_INTERWORK}, {"-zd", "=1", PCS_ACCESS_CONSTDATA_WITH_ADR}, {NULL, NULL, 0} }; void config_init(ToolEnv *t) { Uint i; config = 0; if (TE_HasValue(t, "-apcs.softfp", "#/hardfp") && TE_HasValue(t, "-fpu", "#amp")) config |= CONFIG_SOFTWARE_DOUBLES; for (i = 0; config_opts[i].name != NULL; i++) if (TE_HasValue(t, config_opts[i].name, config_opts[i].val)) config |= config_opts[i].flag; arthur_module = 0; integer_load_max = TE_Integer(t, "-zi", INTEGER_LOAD_MAX_DEFAULT); ldm_regs_max = TE_Integer(t, "-zr", LDM_REGCOUNT_MAX_DEFAULT); { char const *arch = toolenv_lookup(t, "-arch"); char const *cpu = toolenv_lookup(t, "-cpu"); Processor const *proc = NULL; if (TE_HasValue(t, ".nohalfwordstores", "?")) config |= CONFIG_NO_HALFWORD_STORES; /* architecture dependent configuration */ if (arch != NULL) proc = LookupArchitecture(arch + 1); /* skip the '#' */ if (proc != NULL) { if (proc->flags & PROCESSOR_HAS_HALFWORDS) config |= CONFIG_HALFWORD_SPT; if (proc->flags & PROCESSOR_HAS_MULTIPLY) config |= CONFIG_LONG_MULTIPLY; if (proc->flags & PROCESSOR_HAS_32BIT_MODE) config |= CONFIG_32BIT; if (proc->flags & PROCESSOR_HAS_26BIT_MODE) config |= CONFIG_26BIT; } /* processor dependent configuration */ if (cpu != NULL) proc = LookupProcessor(cpu + 1); config_mulbits = (proc != NULL) ? proc->mulbits : 0; config_multime = (proc != NULL) ? proc->multime : 0; config_mlatime = (proc != NULL) ? proc->mlatime : 0; } pcs_flags = 0; for (i = 0; pcs_opts[i].name != NULL; i++) if (TE_HasValue(t, pcs_opts[i].name, pcs_opts[i].val)) pcs_flags |= pcs_opts[i].flag; { char const *fpuname = toolenv_lookup(t, "-fpu"); fpu_type = (StrEq(fpuname, "#amp")) ? fpu_amp : fpu_fpa; } dbg_setformat(toolenv_lookup(t, ".debugtable")); { int bits; char v[8]; char *p = v; char *b = lib_variant; size_t vlen; if (!(config & CONFIG_SOFTWARE_FP)) { if (pcs_flags & PCS_FPE3) *p++ = (config & CONFIG_FPREGARGS) ? 'r' : 'h'; else *p++ = (config & CONFIG_FPREGARGS) ? 'z' : '2'; } if (pcs_flags & PCS_INTERWORK) { if (!(pcs_flags & PCS_NOSTACKCHECK)) *p++ = 's'; *p++ = 'i'; bits = 16; } else { if (pcs_flags & PCS_NOSTACKCHECK) *p++ = 'c'; if (pcs_flags & PCS_CALLCHANGESPSR) bits = 32; else bits = 26; if (pcs_flags & PCS_NOFP) *p++ = 'n'; } if (pcs_flags & PCS_REENTRANT) *p++ = 'e'; vlen = p - v; if (vlen != 0) { *b++ = '_'; memcpy(b, v, vlen); b += vlen; } sprintf(b, ".%d%c", bits, (config & CONFIG_BIG_ENDIAN) ? 'b' : 'l'); } } void mcdep_set_options(ToolEnv *t) { IGNORE(t); } /********************************************************************************************/ #include "jopcode.h" #include "mcdpriv.h" #include "armops.h" #include "aeops.h" #include "inlnasm.h" #include "flowgraf.h" static uint32 movc_workregs1(Icode const *ic); int32 a_loads_r1(PendingOp const* const p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; if (op <= J_LAST_JOPCODE) return loads_r1(op); return a_attributes(op) & _a_set_r1; } int32 a_reads_r1(PendingOp const* const p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; if (op <= J_LAST_JOPCODE) return reads_r1(op); return a_attributes(op) & _a_read_r1; } int32 a_uses_r1(PendingOp const* const p) { return a_reads_r1(p) || a_loads_r1(p); } int32 a_loads_r2(PendingOp const* const p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; if (p->peep & (P_PRE | P_POST)) return YES; if (op <= J_LAST_JOPCODE) return loads_r2(op); return (a_attributes(op) & _a_set_r2); } int32 a_reads_r2(PendingOp const* const p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; if (op <= J_LAST_JOPCODE) return reads_r2(op); return a_attributes(op) & _a_read_r2; } int32 a_uses_r2(PendingOp const* const p) { return a_reads_r2(p) || a_loads_r2(p); } int32 a_uses_r3(PendingOp const* const p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; if (op <= J_LAST_JOPCODE) return reads_r3(op); return a_attributes(op) & _a_read_r3; } int32 a_uses_r4(PendingOp const* const p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; if (p->peep & P_RSHIFT) return YES; if (op <= J_LAST_JOPCODE) return reads_r4(op); return (a_attributes(op) & _a_read_r4); } int32 a_uses_mem(PendingOp const* const p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; if (op <= J_LAST_JOPCODE) return reads_mem(op) || writes_mem(op); return a_attributes(op) & (_a_modify_mem+_a_read_mem); } int32 a_modifies_mem(PendingOp const* const p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; if (op <= J_LAST_JOPCODE) return writes_mem(op); return a_attributes(op) & _a_modify_mem; } int32 a_uses_stack(PendingOp const* const p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; if (op <= J_LAST_JOPCODE) return uses_stack(op); return a_attributes(op) & _a_uses_stack; } /* Spot the differences between the next 4 functions! */ bool corrupts_r1(Icode const* ic) { J_OPCODE op = ic->op & J_TABLE_BITS; switch (op) { case J_MOVC: case J_CLRC: return 4*bitcount(movc_workregs1(ic)) < ic->r3.i; default: return NO; } } bool corrupts_r2(Icode const* ic) { J_OPCODE op = ic->op & J_TABLE_BITS; switch (op) { case J_MOVC: return 4*bitcount(movc_workregs1(ic)) < ic->r3.i; default: return NO; } } bool a_corrupts_r1(PendingOp const* p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; switch (op) { case J_PUSHC: return NO; /* PUSHC always pre decrements r1 */ case J_MOVC: case J_CLRC: return 4*bitcount(movc_workregs1(&p->ic)) < p->ic.r3.i; default: return NO; } } bool a_corrupts_r2(PendingOp const* p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; switch (op) { case J_PUSHC: return YES; case J_MOVC: if (p->peep & P_POST) return NO; /* MOVC has optional post increment */ if (!(p->dataflow & J_DEAD_R2) && 4*bitcount(movc_workregs1(&p->ic)) >= p->ic.r3.i) return NO; return 4*bitcount(movc_workregs1(&p->ic)) + 4 < p->ic.r3.i; default: return NO; } } bool sets_psr(Icode const *ic) { J_OPCODE op = ic->op & J_TABLE_BITS; if (is_compare(op)) return YES; #ifdef ARM_INLINE_ASSEMBLER if ((op == J_MSR || op == J_MSK) || (ic->flags & SET_CC) || ((op == J_BL || op == J_SWI) && (ic->r3.i & regbit(R_PSR)))) return YES; #endif if (op == J_CALLK && ic->r2.i & K_RESULTINFLAGS) return YES; return NO; } bool reads_psr(Icode const* ic) { J_OPCODE op = ic->op & J_TABLE_BITS; PendingOp p; if (is_asminstr(op)) { p.ic = *ic; p.peep = 0; translate_asm_instr(&p); ic = &p.ic; op = ic->op & J_TABLE_BITS; } if (op == J_B && ic->op & Q_MASK != 0) return YES; if (op == J_ADCR || op == J_ADCK || op == J_SBCR || op == J_SBCK || op == J_RSCR || op == J_RSCK) return YES; #ifdef ARM_INLINE_ASSEMBLER if (op == J_MRS || ((op == J_BL || op == J_SWI) && (ic->r2.i & regbit(R_PSR)))) return YES; #endif if ((ic->op >> J_SHIFTPOS) & J_SHIFTMASK == SHIFT_ARITH + 0) /* ASR 0 = RRX, uses carry */ return YES; return NO; } bool uses_psr(Icode const *ic) { return sets_psr(ic) || reads_psr(ic); } bool corrupts_psr(Icode const *ic) { J_OPCODE op = ic->op & J_TABLE_BITS; if (op == J_CASEBRANCH) return YES; if ((op == J_MOVC || op == J_CLRC || op == J_PUSHC) && ic->r3.i > MOVC_LOOP_THRESHOLD) return YES; if (op == J_OPSYSK && (var_cc_private_flags & 512L)) return YES; if ((op == J_CALLR || op == J_CALLI) && (pcs_flags & PCS_CALLCHANGESPSR)) return YES; if (op == J_CALLK) { if (ic->r2.i & K_RESULTINFLAGS) return NO; return (pcs_flags & PCS_CALLCHANGESPSR); } return NO; } /* MOVC/CLRC/PUSHC are weird instructions: * * MOVC dst, src, #N * src may be SP, in which case the POST bit must be set (SP updated) * PUSHC SP, src, #N * implies writeback to SP (thus a_loads_r1) and corrupts src. * CLRC dst, #N * * src is not corrupted if * MOVC from SP (POST), or * N <= 4*bitcount(freeregs), or * dst dead and N-4 <= 4*bitcount(freeregs) * * dst is not corrupted if * PUSHC, or * N <= 4*bitcount(freeregs) - in gen.c */ static uint32 movc_workregs1(Icode const *ic) { /* p->op is known to be one of CLRC, MOVC or PUSHC */ uint32 set = regbit(R_A4) | regbit(R_IP); if (ic->r3.i > MOVC_LOOP_THRESHOLD) set |= regbit(R_A2) | regbit(R_A3); return set | ic->r4.i; } uint32 movc_workregs(PendingOp const *p) { /* p->op is known to be one of CLRC, MOVC or PUSHC */ uint32 set = movc_workregs1(&p->ic); /* Always preserve the store (&load for MOVC) addresses, * as gen.c can use writeback. */ set &= ~(regbit(p->ic.r1.rr)); if ((p->ic.op & ~J_ALIGNMENT) != J_CLRC) /* MOVC or PUSHC */ set &= ~regbit(p->ic.r2.rr); return set; } bool movc_preserving_r1r2(PendingOp const *p, bool dead_r2) { int32 op = p->ic.op & ~J_ALIGNMENT; if (op == J_PUSHC) return NO; { int32 workregs = movc_workregs(p); int32 workcount = 4*bitcount(workregs); if (op != J_CLRC && dead_r2) return p->ic.r3.i <= workcount + 4; else return p->ic.r3.i <= workcount; } } static uint32 GetUsedRegs(Binder *b) { Symstr *s = (h0_(b) == s_binder) ? bindsym_(b) : (Symstr *) b; uint32 volatile_regs = regbit(R_IP) | reglist(R_A1, NARGREGS) | reglist(R_F0, NFLTARGREGS); /* The code below is because of the fact that there are 2 different representations * of binders, depending of whether you are pre or post regalloc. * This code tries to find out in which stage we are... * Note that symext_(sym) might not be initialized. */ if (var_cc_private_flags & 1024L) /* usedregs optimization disabled */ return volatile_regs; return (symext_(s) != NULL) ? symext_(s)->usedregs.map[0] : volatile_regs; } static uint32 resultregs(Icode const * ic) /* pre: iscall_(ic) */ { /* return result registers including the default result reg */ if (k_resultregs_(ic->r2.i) == 0) return regbit(ic->r1.r); /* 0 means 1 result!!! */ /* > 0 means N results, starting from R_A1 */ return reglist(R_A1, R_A1 + k_resultregs_(ic->r2.i)); } static uint32 argumentregs(uint32 argdesc) { uint32 regs; regs = reglist(R_A1, k_intregs_(argdesc)); regs |= reglist(R_F0, k_fltregs_(argdesc)); if (argdesc & K_SPECIAL_ARG) regs |= regbit(TARGET_SPECIAL_ARG_REG); return regs; } bool UnalignedLoadMayUse(RealRegister r) { return r == R_IP || r == R_A1+3; } int32 MaxMemOffset(J_OPCODE op) { switch (j_memsize(op)) { case MEM_B: return (target_has_halfword_support && (op & J_SIGNED) != 0) ? 255 : 4095; case MEM_W: return (target_has_halfword_support && (op & J_ALIGNMENT) != J_ALIGN1) ? 254 : 4094; case MEM_I: return 4092; case MEM_F: case MEM_D: return 1020; case MEM_LL: return 0; } } int32 MinMemOffset(J_OPCODE op) { return -MaxMemOffset(op); } int32 MemQuantum(J_OPCODE op) { if ((op & J_ALIGNMENT) == J_ALIGN1) return 1; switch (j_memsize(op)) { case MEM_B: return 1; case MEM_W: return 2; case MEM_I: case MEM_F: case MEM_D: case MEM_LL: return 4; } } static bool OverlargeMemOffset(const Icode *ic) { int32 maxoffset, offset; if (reads_r3(ic->op)) /* filter out LDRxRs */ return NO; maxoffset = MaxMemOffset(ic->op); if (uses_stack(ic->op)) { if ((bindaddr_(ic->r3.b) & BINDADDR_MASK) == BINDADDR_ARG) { /* argument */ if (pcs_flags & PCS_NOFP) offset = max_argsize + greatest_stackdepth + TARGET_MAX_FRAMESIZE; else offset = max_argsize + 4; } else { /* local variable */ if (pcs_flags & PCS_NOFP) offset = greatest_stackdepth; else offset = greatest_stackdepth + TARGET_MAX_FRAMESIZE + NARGREGS * 4 + NFLTARGREGS * 12; /* WD: should use sizeof macro */ } return offset > maxoffset; } else return ic->r3.i < -maxoffset || ic->r3.i > maxoffset; } void RealRegisterUse(const Icode *ic, RealRegUse *u) { uint32 use = 0, def = 0, c_in = 0, c_out = 0; switch (ic->op & (J_TABLE_BITS | J_ALIGNMENT)) { case J_MOVC+J_ALIGN4: case J_CLRC+J_ALIGN4: case J_PUSHC+J_ALIGN4: c_in = c_out = movc_workregs1(ic); /* Clear out the input registers after register allocation * if they are corrupted. This is to prevent gen.c to syserr * if the input registers and corrupted inputs overlap... */ if (isany_realreg_(ic->r1.r)) c_in &= ~regbit(ic->r1.rr); if (isany_realreg_(ic->r2.r)) c_in &= ~regbit(ic->r2.rr); break; case J_LDRK+J_ALIGN1: case J_LDRVK+J_ALIGN1: c_out = regbit(R_IP) | regbit(R_A4); break; case J_STRK+J_ALIGN1: case J_STRVK+J_ALIGN1: c_in = regbit(R_IP); break; case J_LDRWK+J_ALIGN1: case J_LDRWVK+J_ALIGN1: c_out = regbit(R_IP); break; case J_STRWR+J_ALIGN2: case J_LDRWR+J_ALIGN2: if (target_has_halfword_support) { if ((ic->op & J_SHIFTMASK) != 0) c_in = regbit(R_IP); } else if (config & CONFIG_NO_UNALIGNED_LOADS) { c_in = regbit(R_IP); c_out = regbit(R_IP); } break; case J_LDRBR+J_ALIGN1: if (target_has_halfword_support && (ic->op & J_SIGNED) && (ic->op & J_SHIFTMASK)) c_in = regbit(R_IP); break; case J_COUNT: c_in = regbit(R_LR); c_out = regbit(R_IP); break; case J_PUSHM: def = regbit(R_SP); use = regbit(R_SP) | ic->r3.i; break; case J_POPMB: use = regbit(R_SP); def = regbit(R_SP) | ic->r3.i; break; /* WD: PUSHR & PUSHL seem unused??? */ case J_PUSHD: case J_PUSHF: use = def = regbit(R_SP); break; case J_MOVDIM: case J_MOVIDM: use = ic->r3.i; def = ic->r1.i; break; #ifdef ARM_INLINE_ASSEMBLER case J_LDM: case J_LDMW: def = ic->r3.i; break; case J_STM: case J_STMW: use = ic->r3.i; break; case J_SWI: case J_BL: use = ic->r2.i; def = ic->r3.i; c_out = ic->r4.i; break; case J_ABINRK: { uint32 op = OPCODE(ic->flags); if ((ic->flags & SET_CC) && (op == A_ADD || op == A_SUB || op == A_ADC || op == A_SBC || op == A_RSB || op == A_RSC)) c_in = regbit(R_IP); if (ic->flags & SET_PSR) /* TEQP & TSTP */ c_in = regbit(R_IP); break; } case J_ACMPK: if (ic->flags & (SET_CC | SET_PSR)) c_in = regbit(R_IP); break; #endif case J_OPSYSK: use = argumentregs(ic->r2.i); def = resultregs(ic); if (feature & FEATURE_INLINE_CALL_KILLS_LINKREG) c_in |= M_LR; c_out = reglist(R_A1, NARGREGS) | reglist(R_F0, NFLTARGREGS); c_out &= ~resultregs(ic); break; case J_CALLK: { uint32 usedregs = GetUsedRegs(ic->r3.b); uint32 volatile_regs = regbit(R_IP) | reglist(R_A1, NARGREGS) | reglist(R_F0, NFLTARGREGS); use = argumentregs(ic->r2.i); def = resultregs(ic); if (ic->r2.i & K_RESULTINFLAGS) def |= regbit(R_PSR); c_in = regbit(R_LR); c_out = (usedregs & volatile_regs) & ~resultregs(ic); break; } case J_CALLR: case J_CALLX: case J_CALLI: case J_CALLXR: case J_CALLIR: use = argumentregs(ic->r2.i); def = resultregs(ic); c_in = regbit(R_LR); c_out = regbit(R_IP) | reglist(R_A1, NARGREGS) | reglist(R_F0, NFLTARGREGS); c_out &= ~resultregs(ic); break; case J_TAILCALLK: case J_TAILCALLR: case J_TAILCALLX: case J_TAILCALLI: case J_TAILCALLXR: case J_TAILCALLIR: use = argumentregs(ic->r2.i); def = 0; break; /* J_ENTER & J_SAVE have quite complex register usage. As they are currently not * used in neither register allocation nor peepholing, this isn't implemented yet. * BEWARE for changes in this! */ case J_SAVE: break; case J_ENTER: def = argumentregs(ic->r3.i); break; #ifdef RANGECHECK_SUPPORTED case J_CHKNEFR: #endif case J_CMPFR: if (fpu_type == fpu_amp) c_out = regbit(R_IP); break; #ifdef RANGECHECK_SUPPORTED case J_CHKLK: case J_CHKUK: case J_CHKNEK: #endif case J_CASEBRANCH: case J_CMPK: if (Arm_EightBits(ic->r3.i) < 0 && Arm_EightBits(-(ic->r3.i)) < 0) c_in = regbit(R_IP); break; case J_MULK: if (MultiplyNeedsWorkreg(ic->r3.i)) c_in = regbit(R_IP); break; case J_FIXFR: if (fpu_type == fpu_amp) { c_in = regbit(R_IP); c_out = regbit(R_IP); } break; case J_ADCON: if (arthur_module != 0) c_in = regbit(R_IP); break; case J_B: if ((LabelNumber*) ic->r3.b == RETLAB) { if (currentfunction.nresultregs <= 1) use = regbit(currentfunction.baseresultreg); else use = regbit(currentfunction.nresultregs) - regbit(R_A1); } break; default: break; } if ((ic->op & J_TABLE_BITS) < J_LAST_JOPCODE && j_is_ldr_or_str(ic->op) && OverlargeMemOffset(ic)) c_in |= regbit(R_IP); u->use.map[0] = use; u->def.map[0] = def; u->c_in.map[0] = c_in; u->c_out.map[0] = c_out; } bool has_side_effects(Icode const *ic) { J_OPCODE op = ic->op & J_TABLE_BITS; if (writes_mem(op)) return YES; if (op == J_NULLOP || op == J_MCR || op == J_MRC || op == J_CDP || op == J_LDC || op == J_LDCW || op == J_STC || op == J_STCW || op == J_BL || op == J_SWI) return YES; return NO; } char *CheckJopcode(const Icode *ic, CheckJopcode_flags flags) { PendingOp p; p.ic = *ic; p.peep = 0; p.dataflow = p.ic.op & J_DEADBITS; p.cond = p.ic.op & Q_MASK; return CheckJopcodeP(&p, flags); } char *CheckJopcodeP(const PendingOp *p, CheckJopcode_flags flags) { char *errmsg = NULL; const Icode *ic = &p->ic; /* Check alignment of memory instructions */ if ((flags & JCHK_MEM) && (ic->op & J_TABLE_BITS) < J_LAST_JOPCODE && j_is_ldr_or_str(ic->op)) { if (!reads_r3(ic->op) && !uses_stack(ic->op)) /* LDRK/STRK */ { if (ic->r3.i & (MemQuantum(ic->op) - 1)) errmsg = "alignment error"; } if ((ic->op & J_ALIGNMENT) == J_ALIGN1 && OverlargeMemOffset(ic)) { if ((j_memsize(ic->op) == MEM_W && writes_mem(ic->op)) || j_memsize(ic->op) == MEM_I) errmsg = "unaligned LDR/STR offset out of range"; } } /* Check register numbers, usage, clashes and deadbits */ if (flags & JCHK_REGS) { bool fault = NO; RegisterUsage u; /* Consistency check on deadbits */ if (!a_uses_r1(p) && p->dataflow & J_DEAD_R1) fault = YES; if (!a_uses_r2(p) && p->dataflow & J_DEAD_R2) fault = YES; if (!a_uses_r3(p) && p->dataflow & J_DEAD_R3) fault = YES; if (!a_uses_r4(p) && p->dataflow & J_DEAD_R4) fault = YES; if (fault) errmsg = "corrupted deadbits"; /* Consistency check on physical register numbers */ fault = NO; if (a_uses_r1(p) && (uint32)p->ic.r1.rr >= 24) fault = YES; if (a_uses_r2(p) && (uint32)p->ic.r2.rr >= 24) fault = YES; if (a_uses_r3(p) && (uint32)p->ic.r3.rr >= 24) fault = YES; if (a_uses_r4(p) && (uint32)p->ic.r4.rr >= 24) fault = YES; if (fault) errmsg = "illegal register number"; if (GetRegisterUsage(p, &u)) errmsg = "corrupted register"; fault = NO; switch (ic->op) { case J_MULR: case J_MLAR: if (p->ic.r1.r == p->ic.r3.r) fault = YES; break; case J_MULL: case J_MLAL: if (p->ic.r1.r == p->ic.r2.r) fault = YES; if (p->ic.r1.r == p->ic.r3.r) fault = YES; if (p->ic.r2.r == p->ic.r3.r) fault = YES; break; #ifdef ARM_INLINE_ASSEMBLER case J_SWP: case J_SWPB: if (p->ic.r1.r == p->ic.r3.r) fault = YES; if (p->ic.r2.r == p->ic.r3.r) fault = YES; break; case J_LDMW: if (regbit(p->ic.r1.r) & p->ic.r3.i) fault = YES; break; #endif } if (fault) errmsg = "register clash"; } if ((flags & JCHK_SYSERR) && errmsg != NULL) { if (strcmp(errmsg, "alignment error") != 0) syserr(errmsg); else cc_warn("illegal unaligned load or store access - use __packed instead"); } return errmsg; } /* TODO remove writeback should be generalized into a backend function remove_jopcode() with the dead flags as inputs. This will return a NOOP, a modified instruction or the same instruction... */ void remove_writeback(Icode *ic) /* Remove writeback from LDM/STM/LDR/STR/LDC/STC if possible */ { J_OPCODE op = ic->op & J_TABLE_BITS; if (op == J_LDMW || op == J_STMW) { ic->flags &= ~M_WB; ic->op -= J_LDMW - J_LDM; } else if (op == J_ALDRKW || op == J_ASTRKW) { /* convert postindex to preindex of #0 if not LDRT/STRT */ ic->op -= J_ALDRKW - J_ALDRK; if (ic->flags & M_TRANS) ic->r3.i = 0; else { ic->flags &= ~M_WB; if (!(ic->flags & M_PREIDX)) { ic->flags |= M_PREIDX; ic->r3.i = 0; } } } else if (op == J_ALDRRW || op == J_ASTRRW) { /* convert postindex reg to preindex of #0 if not LDRT/STRT */ if (ic->flags & M_TRANS) { ic->flags = (ic->flags & ~RN_OPND_MASK) | RN_CONST; ic->op -= J_ALDRRW - J_ALDRK; ic->r3.i = 0; } else { ic->flags &= ~M_WB; ic->op -= J_ALDRRW - J_ALDRR; if (!(ic->flags & M_PREIDX)) { ic->flags = (ic->flags & ~RN_OPND_MASK) | RN_CONST; ic->op -= J_ALDRR - J_ALDRK; ic->flags |= M_PREIDX; ic->r3.i = 0; } } } else if (op == J_LDCW || op == J_STCW) { ic->op -= J_LDCW - J_LDC; ic->flags &= ~M_WB; /* do NOT convert postindex to preindex (Piccolo) */ } if (debugging(DEBUG_REGS) && op != ic->op & J_TABLE_BITS) print_xjopcode(ic, "-> Removed writeback"); } /* Returns the register usage of a pendingop. Returns true if the register usage * is incorrect (where inputs or outputs are being corrupted). */ bool GetRegisterUsage(const PendingOp *c, RegisterUsage *u) { RealRegUse usage; bool corrupted = NO; u->use = u->def = u->corrupt = u->dead = 0; if (a_loads_r1(c)) u->def |= regbit(c->ic.r1.rr); if (a_loads_r2(c)) u->def |= regbit(c->ic.r2.rr); if (sets_psr(&c->ic) || (c->peep & P_CMPZ)) u->def |= regbit(R_PSR); if (a_corrupts_r1(c)) u->corrupt |= regbit(c->ic.r1.rr); if (a_corrupts_r2(c)) u->corrupt |= regbit(c->ic.r2.rr); if (corrupts_psr(&c->ic)) u->corrupt |= regbit(R_PSR); if (a_reads_r1(c)) u->use |= regbit(c->ic.r1.rr); if (a_reads_r2(c)) u->use |= regbit(c->ic.r2.rr); if (a_uses_r3(c)) u->use |= regbit(c->ic.r3.rr); if (a_uses_r4(c)) u->use |= regbit(c->ic.r4.rr); if (reads_psr(&c->ic)) u->use |= regbit(R_PSR); RealRegisterUse(&c->ic, &usage); u->use |= usage.use.map[0]; u->def |= usage.def.map[0]; if (u->use & usage.c_in.map[0]) /* inputs & corrupted inputs CANNOT overlap */ corrupted = YES; if (u->def & usage.c_out.map[0]) /* output & corrupted output CANNOT overlap */ corrupted = YES; /* corrupted inputs may overlap with definitions, hence we clear out the definitions */ u->corrupt |= (usage.c_in.map[0] & ~u->def) | usage.c_out.map[0]; if (c->dataflow & J_DEAD_R1) u->dead |= regbit(c->ic.r1.rr); if (c->dataflow & J_DEAD_R2) u->dead |= regbit(c->ic.r2.rr); if (c->dataflow & J_DEAD_R3) u->dead |= regbit(c->ic.r3.rr); if (c->dataflow & J_DEAD_R4) u->dead |= regbit(c->ic.r4.rr); u->dead &= ~u->def; /* LDM R0, {R0} case - clear out all defined regs */ if (a_loads_r1(c) && (c->dataflow & J_DEAD_R1)) /* ADD R0, R0, #1 case */ u->dead |= regbit(c->ic.r1.rr); if (a_loads_r2(c) && (c->dataflow & J_DEAD_R2)) u->dead |= regbit(c->ic.r2.rr); return corrupted; } bool arm_shiftop_allowed(int32 n, int32 m, int32 signedness, int32 op) { IGNORE(m); IGNORE(n); switch (op) { case J_LDRBK+J_ALIGN1: return signedness == J_UNSIGNED || !target_has_halfword_support; case J_LDRWK+J_ALIGN2: return !target_has_halfword_support; case J_LDRK+J_ALIGN4: return YES; case J_LDRWK+J_ALIGN1: case J_LDRK+J_ALIGN1: return NO; case J_LDRFK+J_ALIGN4: case J_LDRDK+J_ALIGN4: case J_LDRDK+J_ALIGN8: return NO; default: return YES; } } int multiply_cycles(int val, bool accumulate) { if (config_mulbits == 0) return 4; /* guess an average multiply time */ if (val < 0 && config_mulbits >= 8) val = -val; return (accumulate ? config_mlatime : config_multime) + logbase2(val) / config_mulbits; } /* end of arm/mcdep.c */
stardot/ncc
arm/mcvsn.h
<reponame>stardot/ncc<filename>arm/mcvsn.h #define MC_VERSION "500"
stardot/ncc
mip/dbx.c
<gh_stars>0 /* * C compiler file dbx.c, version 5 * Copyright (C) Acorn Computers Ltd., 1988. * Copyright (C) Codemist Ltd., 1988. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef NO_VERSION_STRINGS extern char dbx_version[]; char dbx_version[] = "\ndbx.c $Revision$ 5\n"; #endif /* This file contains routines to buffer information required for */ /* the Unix symbolic debugger dbx. This has been hacked from c.armdbg, */ /* which generated debugging tables for the Arthur symbolic debugger ASD. */ /* * Notes: * 1. RCC. Parameters are tricky. Currently a parameter in a register * generates 2 dbx things, one a param, with its offset from fp, * and the other a register variable. This enables dbx to pick * up the original value of the parameter when running down the * the stack, and the current value (if anyone assigns to it) while * inside the procedure. But it is a bit of a tacky thing to do. */ #ifdef unix # include <a.out.h> # ifdef arm /* a.out.h defines size_t via sys/types.h */ # define __size_t /* so inhibit later definition by stddef.h */ # endif #else # include "aout.h" #endif #ifdef __STDC__ # include <string.h> #else # include <strings.h> #endif #include <stddef.h> #include "globals.h" #include "mcdep.h" #include "mcdpriv.h" #include "store.h" #include "codebuf.h" #include "aeops.h" #include "xrefs.h" #include "util.h" #include "regalloc.h" /* for register_number */ #include "bind.h" /* evaluate */ #include "sem.h" /* alignoftype, sizeoftype, structfield */ #include "errors.h" #ifdef FORTRAN #include "feext.h" /* syn_equivcheck */ #endif #if !defined(__STDC__) || (defined(__sparc) && defined(P_tmpdir) && \ !defined(__svr4__)) && !defined(__cplusplus) # define sprintf ansi_sprintf static int sprintf(char *buf,const char *format,...) { va_list ap; va_start(ap, format); vsprintf(buf, format, ap); va_end(ap); return strlen(buf); } #endif #ifdef TARGET_HAS_DEBUGGER #define ACORN_DBX_VSN 315L char dbg_name[4] = "dbx"; int usrdbgmask; /* * Definitions of type values for dbx information in symbol table. * Really should get these from h.stab, but what the hell. */ #define N_GSYM 0x20 /* global symbol: name,,0,type,0 */ #define N_FNAME 0x22 /* procedure name (f77 kludge): name,,0 */ #define N_FUN 0x24 /* procedure: name,,0,linenumber,address */ #define N_STSYM 0x26 /* static symbol: name,,0,type,address */ #define N_LCSYM 0x28 /* .lcomm symbol: name,,0,type,address */ #define N_RSYM 0x40 /* register sym: name,,0,type,register */ #define N_SLINE 0x44 /* src line: 0,,0,linenumber,address */ #define N_SSYM 0x60 /* structure elt: name,,0,type,struct_offset */ #define N_SO 0x64 /* source file name: name,,0,0,address */ #define N_LSYM 0x80 /* local sym: name,,0,type,offset */ #define N_SOL 0x84 /* #included file name: name,,0,0,address */ #define N_PSYM 0xa0 /* parameter: name,,0,type,offset */ #define N_ENTRY 0xa4 /* alternate entry: name,linenumber,address */ #define N_LBRAC 0xc0 /* left bracket: 0,,0,nesting level,address */ #define N_RBRAC 0xe0 /* right bracket: 0,,0,nesting level,address */ #define N_BCOMM 0xe2 /* begin common: name,, */ #define N_ECOMM 0xe4 /* end common: name,, */ #define N_ECOML 0xe8 /* end common (local name): ,,address */ #define N_LENG 0xfe /* second stab entry with length information */ #define N_PC 0x30 /* global pascal symbol: name,,0,subtype,line */ /* * The following values are copied from debugging information generated * by VAX-Unix PCC. These types must all be declared explicitly (though * self-referentially). */ #ifndef FORTRAN /* ie is C */ #define T_INT 1 #define T_CHAR 2 #define T_LONG 3 #define T_SHORT 4 #define T_UCHAR 5 #define T_USHORT 6 #define T_ULONG 7 #define T_UINT 8 #define T_FLOAT 9 #define T_DOUBLE 10 #define T_VOID 11 #define T_BYTE 0 #define T_UBYTE 0 #define T_COMPLEX 0 #define T_DCOMPLEX 0 #define T_EXTEND 0 #define T_LBYTE 0 #define T_LSHORT 0 #define T_LOGICAL 0 #define T_LLONG 0 #else /* ie is F77 */ #define T_INT 3 #define T_CHAR 9 #define T_LONG 3 #define T_SHORT 2 #define T_UCHAR 9 #define T_USHORT 2 #define T_ULONG 3 #define T_UINT 3 #define T_FLOAT 4 #define T_DOUBLE 5 #define T_VOID 10 #define T_BYTE 1 #define T_UBYTE 1 #define T_COMPLEX 6 #define T_DCOMPLEX 7 #define T_EXTEND 13 #define T_LBYTE 11 #define T_LSHORT 12 #define T_LOGICAL 8 #define T_LLONG 8 #endif static int32 tableindex[DT_MAX+1] = { 0, T_BYTE, T_SHORT, T_INT, T_LONG, T_UBYTE, T_USHORT, T_UINT, T_ULONG, T_FLOAT, T_DOUBLE, T_EXTEND, T_COMPLEX, T_DCOMPLEX, T_LBYTE, T_LSHORT, T_LOGICAL, T_LLONG, T_CHAR, T_UCHAR }; #define DbgAlloc(n) GlobAlloc(SU_Dbg, n) static char *copy(char *s) { int l = strlen(s) + 1; /* Makes a heap copy of something in a local array to pass to * aoutobj (no longer in global store). */ char *p = (char *)SynAlloc((int32)l); memcpy(p, s, l); return(p); } static char *globalcopy(char *s) { int l = strlen(s) + 1; /* Makes a global heap copy of something in a local array (for typereps) */ char *p = (char *)DbgAlloc((int32)l); memcpy(p, s, l); return(p); } #define TYPESEGSIZE 256 /* type table segment size */ #define TYPESEGBITS 8 /* log2(MAXTYPES) */ #define TYPESEGMAX 256 /* maximum number of type table segments */ #define MAXSTRING 4096 /* size of temporary string buffers */ typedef struct TypeInfo { TypeExpr *type; char *name; char *defn; } TypeInfo; typedef TypeInfo *TypeSeg[TYPESEGSIZE]; static TypeSeg *(*dbg_typetab)[TYPESEGMAX]; #define typeinfo_(n) (*(*dbg_typetab)[((n)-1)>>TYPESEGBITS]) \ [((n)-1)&(TYPESEGSIZE-1)] static int32 dbg_freetype; /* * The following definitions of the standard types are stolen from * decoded output of VAX pcc. Don't ask me why there is a thing * called "???" as type 12. */ #ifndef FORTRAN /* ie is C */ static TypeInfo dbg_stdtypes[] = { { NULL, "int", "r1;-2147483648;2147483647;" }, { NULL, "char", "r2;-128;127;" }, { NULL, "long", "r1;-2147483648;2147483647;" }, { NULL, "short", "r1;-32768;32767;" }, { NULL, "unsigned char", "r1;0;255;" }, { NULL, "unsigned short", "r1;0;65535;" }, { NULL, "unsigned long", "r1;0;-1;" }, { NULL, "unsigned int", "r1;0;-1;" }, { NULL, "float", "r1;4;0;" }, { NULL, "double", "r1;8;0;" }, { NULL, "void", "11" }, { NULL, "???", "1" }, { NULL, NULL, NULL }, }; #else /* ie is fortran */ static TypeInfo dbg_stdtypes[] = { { NULL, "byte", "r1;-128;127;" }, { NULL, "integer*2", "r2;-32768;32767;" }, { NULL, "integer", "r3;-2147483648;2147483647;" }, { NULL, "real", "r4;4;0;" }, { NULL, "double precision", "r5;8;0;" }, { NULL, "complex", "r6;8;0;" }, { NULL, "double complex", "r7;16;0;" }, { NULL, "logical", "r8;4;0;" }, { NULL, "char", "r9;-128;127;" }, { NULL, "void", "r10;0;0;" }, { NULL, "logical*1", "r11;1;0;" }, { NULL, "logical*2", "r12;2;0;" }, { NULL, "real*16", "r13;16;0;" }, { NULL, NULL, NULL }, }; #endif static void dbg_stab(char *name, int32 type, int32 desc, unsigned long value) { struct nlist nlist; nlist.n_un.n_name = name; nlist.n_type = (char)type; nlist.n_other = (char)0; nlist.n_desc = (short)desc; nlist.n_value = value; obj_stabentry(&nlist); } static void dbg_stdheader(void) { TypeInfo *p; char buf[64]; int idx, pos; for (p = dbg_stdtypes, idx = 1; p->name != NULL; ++p) { pos = sprintf(buf, "%s:t%d=%s", p->name, idx++, p->defn); buf[pos] = 0; dbg_stab(copy(buf), N_LSYM, 0, 0); } } #define newtypeseg_() (TypeSeg *)DbgAlloc(TYPESEGSIZE * sizeof(TypeInfo *)) static void dbg_inittypes(void) { TypeInfo *p; TypeSeg *q; int32 i; if (!usrdbg(DBG_ANY)) { dbg_typetab = (TypeSeg *(*)[])DUFF_ADDR; return; } dbg_typetab = (TypeSeg *(*)[])DbgAlloc(sizeof(*dbg_typetab)); for (i = 0; i < TYPESEGMAX; i++) (*dbg_typetab)[i] = NULL; q = (*dbg_typetab)[0] = newtypeseg_(); for (p = &dbg_stdtypes[0], i = 0; p->name != NULL; ++p) { (*q)[i++] = p; } (*q)[i] = NULL; dbg_freetype = i; } static int32 dbg_typeintab(char *name, TypeExpr *t) { if (h0_(t) == s_typespec) { /* may be a built-in one */ SET_BITMAP m = typespecmap_(t); int32 ubit = m & bitoftype_(s_unsigned); int32 langinfo = typedbginfo_(t); if (langinfo != 0) return langinfo; switch (m & -m) { case bitoftype_(s_char): return(ubit ? T_UCHAR : T_CHAR); case bitoftype_(s_int): if (m & bitoftype_(s_short)) { return(ubit ? T_USHORT : T_SHORT); } return(ubit ? T_UINT : T_INT); case bitoftype_(s_double): return((m & bitoftype_(s_short)) ? T_FLOAT : T_DOUBLE); case bitoftype_(s_void): return(T_VOID); default: break; } } /* * Not built-in: search table for it. */ { int32 i; for (i = 0; i < TYPESEGMAX; i++) { TypeSeg *q = (*dbg_typetab)[i]; int32 j; if (q == NULL) return 0; for (j = 0; j < TYPESEGSIZE; j++) { TypeInfo *p = (*q)[j]; if (p == NULL) return 0; if (p->type == t && (name[0] == '\0' || strcmp(p->name,name) == 0)) return(i * TYPESEGMAX + j + 1); } } } return(0); } static int32 dbg_newtype(TypeExpr *type, char *name, char *defn) { TypeInfo *p; if (++dbg_freetype > TYPESEGSIZE * TYPESEGMAX) syserr(syserr_too_many_types); p = (TypeInfo *)DbgAlloc(sizeof(TypeInfo)); typeinfo_(dbg_freetype) = p; p->type = type; p->name = name; p->defn = defn; if ((dbg_freetype & (TYPESEGSIZE-1)) == 0) (*dbg_typetab)[dbg_freetype >> TYPESEGBITS] = newtypeseg_(); typeinfo_(dbg_freetype+1) = NULL; return(dbg_freetype); } typedef int VarClass; #define CLASS_AUTO 0 #define CLASS_EXT 1 #define CLASS_STATIC 2 #define CLASS_REG 3 #define CLASS_OWN 4 #define CLASS_PARAM 5 #define CLASS_VARPARAM 6 #define CLASS_COMMMEM 7 #define CLASS_BSS 8 #define CLASS_EXTBSS 9 static char charofclass[] = "@GSrVpvVSG"; static char ntypeof[] = { N_LSYM, N_GSYM, N_STSYM, N_RSYM, N_STSYM, N_PSYM, N_PSYM, N_GSYM, N_LCSYM,N_LCSYM, 0 }; /* flag values for 'debsort' */ #define D_SRCPOS 1 #define D_PROC 2 #define D_VAR 3 #define D_TYPE 4 #define D_STRUCT 5 #define D_FILEINFO 6 #define D_SCOPE 7 #define D_COMMON 8 #define dbg_hdr_(debsort,len) ((int32)(len)<<16 | (debsort)) /* The next macro seems to indicate a lack to do this portably in ANSI-C */ /* Are discriminated unions second class objects? */ #define DbgListVarSize(variant) \ ((size_t)(sizeof(p->car.variant)+offsetof(DbgList,car))) /* The following is the *internal* data structure in which debug info. */ /* is buffered. */ typedef struct DbgList { struct DbgList *cdr; int32 debsort; union Deb_Things { struct { char *fname; int32 sourcepos; int32 codeaddr; } DEB_SRCPOS; struct { char *type; int32 isextern; int32 sourcepos; int32 codeaddr; char *name; } DEB_PROC; struct { char *type; int32 sourcepos; VarClass dbxclass; int32 location; Symstr *sym; } DEB_VAR; struct { int32 typeidx; } DEB_TYPE; struct { int32 typeidx; } DEB_STRUCT; struct { int32 levelchange; int32 level; int32 codeaddr; } DEB_SCOPE; struct { int32 isstart; char *name; } DEB_COMMON; } car; } DbgList; static DbgList *dbglist, *dbglistproc; static DbgList *dbgscope; /* used only briefly */ int32 dbg_tablesize() { return 0; /* harmless, but should raise an error ?? */ } int32 dbg_tableindex(int32 dt_number) { if (dt_number > DT_MAX) return 0; return tableindex[dt_number]; } VoidStar dbg_notefileline(FileLine fl) { DbgList *p; if (!usrdbg(DBG_LINE)) return(DUFF_ADDR); if (debugging(DEBUG_Q)) cc_msg("-- noteline(%ld)\n", (long)(fl.l & 0x3fffff)); p = (DbgList *)DbgAlloc(DbgListVarSize(DEB_SRCPOS)); p->cdr = dbglist; dbglist = p; p->debsort = D_SRCPOS; p->car.DEB_SRCPOS.fname = fl.f; p->car.DEB_SRCPOS.sourcepos = fl.l; p->car.DEB_SRCPOS.codeaddr = -1; /* to be patched later */ return((VoidStar)p); } /* * Bits 0..21 of a sourcepos are the lineno, bits 22..31 are character * position on line: this is the wrong way round for comparing them, * but that's the way TopExpress defined it, so have to rotate before * comparing. */ #define ROTPOS(srcpos) (((srcpos)<<10) | ((srcpos)>>22)) /* * dbg_insertitem is needed to put things into the dbglist at a * place determined by source order or code order, rather than always * tacking them on the beginning of the list (which is reversed later). */ static void dbg_insertitem(DbgList *p, int32 srcpos, int32 codeaddr) { int32 rpos = ROTPOS(srcpos); DbgList *prev, *x; if (debugging(DEBUG_Q)) cc_msg("-- insert(line=%ld)\n", srcpos & 0x3fffff); for (prev = NULL, x = dbglist; x != NULL; x = x->cdr) { if (x->debsort != D_SRCPOS) continue; if (srcpos == 0) { int32 xaddr = x->car.DEB_SRCPOS.codeaddr; if ((xaddr >= 0) && (xaddr <= codeaddr)) break; } else { if (ROTPOS(x->car.DEB_SRCPOS.sourcepos) <= rpos) break; } prev = x; } if (srcpos == 0) { /* no point adding a D_SRCPOS record */ x = p; } else { x = (DbgList *)DbgAlloc(DbgListVarSize(DEB_SRCPOS)); x->debsort = D_SRCPOS; x->car.DEB_SRCPOS.fname = NULL; /* dubious? */ x->car.DEB_SRCPOS.sourcepos = srcpos; x->car.DEB_SRCPOS.codeaddr = -1; p->cdr = x; } if (prev != NULL) { x->cdr = prev->cdr; prev->cdr = p; } else { x->cdr = dbglist; dbglist = p; } } void dbg_addcodep(VoidStar debaddr, int32 codeaddr) { DbgList *p = (DbgList *)debaddr; if (!usrdbg(DBG_ANY)) return; if (p == NULL) { /* J_INFOSCOPE */ /* * c.flowgraf outputs a J_INFOSCOPE immediately after calling * dbg_scope, to mark the relevant code address. */ if (debugging(DEBUG_Q)) cc_msg("-- scope at 0x%lx\n", codeaddr); if ((p = dbgscope) != NULL) { dbgscope = NULL; /* mustn't leave it lying around... */ p->car.DEB_SCOPE.codeaddr = codeaddr; dbg_insertitem(p, 0, codeaddr); } } else { /* J_INFOLINE */ if (p->debsort != D_SRCPOS) syserr(syserr_addcodep); if (p->car.DEB_SRCPOS.codeaddr == -1) { p->car.DEB_SRCPOS.codeaddr = codeaddr; } } } /* End of file/line co-ordinate code */ static int32 sprinttype(char *name,char *, TypeExpr *); static int32 sprintstruct(char *pp, TypeExpr *type) { char *start = pp; TagBinder *b = typespectagbind_(type); Symstr *sym; AEop sort; /* do two passes to cope with cycles */ sym = bindsym_(b); if (b->tagbinddbg > 0) { pp += sprintf(pp, "%ld", b->tagbinddbg); *pp = 0; return(pp - start); /* seen before */ } if (!(attributes_(b) & TB_DEFD)) { /* no definition yet */ b->tagbinddbg = -dbg_newtype(type, symname_(sym), NULL); pp += sprintf(pp, "%ld", -b->tagbinddbg); *pp = 0; return(pp - start); } if (b->tagbinddbg < 0) { /* it has become defined */ b->tagbinddbg = -b->tagbinddbg; } else { b->tagbinddbg = dbg_newtype(type, symname_(sym), NULL); } /* * Beware circular types and anonymous types. */ if (!isgensym(sym)) { /* not anonymous */ DbgList *p = (DbgList*)DbgAlloc(DbgListVarSize(DEB_STRUCT)); pp += sprintf(pp, "T%ld=", b->tagbinddbg); p->debsort = D_STRUCT; p->car.DEB_STRUCT.typeidx = b->tagbinddbg; p->cdr = dbglist; dbglist = p; } else { pp += sprintf(pp, "%ld=", b->tagbinddbg); } { char dbxclass = 0; switch (sort = (attributes_(b) & ENUMORCLASSBITS)) { case bitoftype_(s_struct): dbxclass = 's'; break; case bitoftype_(s_class): dbxclass = 's'; break; case bitoftype_(s_union): dbxclass = 'u'; break; case bitoftype_(s_enum): dbxclass = 'e'; break; default: syserr(syserr_tagbindsort, sort); } *pp++ = dbxclass; if (dbxclass != 'e') pp += sprintf(pp, "%ld", sizeoftype(type)); } { StructPos p; ClassMember *l; structpos_init(&p, b); for (l = tagbindmems_(b); l != 0; l = memcdr_(l)) { if (sort != s_enum) structfield(l, sort, &p); if (memsv_(l)) { /* note that memsv is 0 for padding bit fields */ pp += sprintf(pp, "%s:", symname_(memsv_(l))); if (sort == bitoftype_(s_enum)) { /* symdata_ here is ok, since dbg_typerep gets called for local things when a declaration is first seen (by dbg_locvar) at which time bindings are still in place. */ pp += sprintf(pp, "%ld", bindenumval_(l)); *pp++ = ','; } else { pp += sprinttype("", pp, memtype_(l)); *pp++ = ','; pp += sprintf(pp, "%ld,%ld;", p.woffset*8 + p.boffset, p.bsize != 0 ? p.bsize : p.typesize * 8); } } } } *pp++ = ';'; *pp = 0; if (!isgensym(sym)) { /* not anonymous */ typeinfo_(b->tagbinddbg)->defn = globalcopy(start); pp = start; pp += sprintf(pp, "%ld", b->tagbinddbg); *pp = 0; } return(pp - start); } static int32 sprinttype(char *name, char *buf, TypeExpr *x) { char *p = buf; int32 typeidx = dbg_typeintab(name,x); int32 n; if (typeidx != 0) { TypeInfo *t = typeinfo_(typeidx); if (t->name[0] == '<' && t->defn != NULL) { /* anonymous structure */ p += sprintf(p, "%s", t->defn); } else { p += sprintf(p, "%ld", typeidx); } *p = 0; return(p - buf); } switch (h0_(x)) { case t_content: case t_ref: /* @@@ ok? Or f77 'v'? */ #ifndef FORTRAN /* dbx doesn't understand f77 pointers, & has special type 'v'*/ *p++ = '*'; #endif p += sprinttype("", p, typearg_(x)); break; case t_subscript: *p++ = 'a'; n = typesubsize_(x) ? evaluate(typesubsize_(x)) : 1; p += sprintf(p, "r%d;0;%ld", T_INT, n-1); *p++ = ';'; p += sprinttype("", p, typearg_(x)); break; case t_fnap: *p++ = 'f'; p += sprinttype("", p, typearg_(x)); break; case s_typespec: { SET_BITMAP m = typespecmap_(x); switch (m & -m) { case bitoftype_(s_enum): case bitoftype_(s_struct): case bitoftype_(s_class): case bitoftype_(s_union): p += sprintstruct(p, x); break; case bitoftype_(s_typedefname): p += sprinttype("", p, bindtype_(typespecbind_(x))); break; default: syserr(syserr_sprinttype, (VoidStar )x, (long)typespecmap_(x)); break; } } break; default: syserr(syserr_sprinttype, (VoidStar)x, (long)typespecmap_(x)); break; } *p = 0; return(p - buf); } static char *dbg_typerep(TypeExpr *x) { char buf[MAXSTRING]; sprinttype("", buf, x); return globalcopy(buf); } static void dbg_addvar_t(Symstr *name, char *typerep, int32 sourcepos, VarClass dbxclass, int32 addr) { DbgList *p = (DbgList*)DbgAlloc(DbgListVarSize(DEB_VAR)); p->debsort = D_VAR; p->car.DEB_VAR.type = typerep; p->car.DEB_VAR.sourcepos = sourcepos; p->car.DEB_VAR.dbxclass = dbxclass; p->car.DEB_VAR.location = addr; p->car.DEB_VAR.sym = name; dbg_insertitem(p, sourcepos, -1); } static void dbg_addvar(Symstr *name, TypeExpr *t, int32 sourcepos, VarClass dbxclass, int32 addr) { dbg_addvar_t(name, dbg_typerep(t), sourcepos, dbxclass, addr); } static void dbg_addcomm(int32 isstart, char *name, int32 sourcepos) { DbgList *p = (DbgList*)DbgAlloc(DbgListVarSize(DEB_COMMON)); p->debsort = D_COMMON; p->car.DEB_COMMON.isstart = isstart; p->car.DEB_COMMON.name = name; dbg_insertitem(p, sourcepos, -1); } static char stgclasses[] = {CLASS_STATIC, CLASS_EXT, CLASS_BSS, CLASS_EXTBSS}; void dbg_topvar(Symstr *name, int32 addr, TypeExpr *t, int stgclass, FileLine fl) /* For scoping reasons this only gets called on top-level variables (which */ /* are known to be held in global store). (Does this matter?) */ { if (usrdbg(DBG_PROC)) { DbgList *p, **prev = &dbglist; if (debugging(DEBUG_Q)) cc_msg("top var $r @ %d:%.6lx\n", name, stgclass, (long)addr); for (; (p = *prev) != NULL ; prev = &cdr_(p)) { int oldclass = p->car.DEB_VAR.dbxclass; if (p->debsort==D_VAR && ( oldclass == CLASS_EXT || oldclass == CLASS_STATIC || oldclass == CLASS_BSS || oldclass == CLASS_EXTBSS) && p->car.DEB_VAR.location==0 && p->car.DEB_VAR.sym == name) { /* Remove the superceded declaration */ *prev = cdr_(p); break; } } dbg_addvar(name, t, fl.l, stgclasses[stgclass], addr); } } void dbg_type(Symstr *name, TypeExpr *t, FileLine fl) /* * This does NOT only get called on top-level types (which * are known to be held in global store). (So: globalize_typeexpr()). * Now called also from dbg_locvar1() and rd_decl(). */ { if (usrdbg(DBG_ANY)) { char buf[MAXSTRING]; char *pp = buf; char *s = symname_(name); if (debugging(DEBUG_Q)) cc_msg("type $r\n", name); pp += sprinttype(s, pp, t); *pp = 0; if (!isgensym(name)) { /* which means that anonymous enums will get no type entry, though the members may be used. But this is just what PCC does */ DbgList *p = (DbgList*)DbgAlloc(DbgListVarSize(DEB_TYPE)); p->debsort = D_TYPE; p->car.DEB_TYPE.typeidx = dbg_newtype(t, s, globalcopy(buf)); p->cdr = dbglist; /* do this last (typerep above) */ dbglist = p; } } } typedef struct Dbg_LocList { struct Dbg_LocList *cdr; Binder *name; char *typerep; int32 pos; bool processed; } Dbg_LocList; static Dbg_LocList *dbg_loclist; /* * dbg_locvar() only registers the name and line of a declaration -- * the location info cannot be added until after register allocation. * See also dbg_scope which completes. * Also remember that dead code elimination may remove some decls. */ void dbg_locvar(Binder *name, FileLine fl) { if (usrdbg(DBG_VAR) && !isgensym(bindsym_(name))) { TypeExpr *t = bindtype_(name); if (debugging(DEBUG_Q)) cc_msg("-- locvar(%s)\n", symname_(bindsym_(name))); if (bindstg_(name) & bitofstg_(s_typedef)) dbg_type(bindsym_(name), t, fl); else { /* local to a proc */ Dbg_LocList *p = (Dbg_LocList*)DbgAlloc(sizeof(Dbg_LocList)); char *typerep = dbg_typerep(t); if (debugging(DEBUG_Q)) cc_msg("note loc var $b [%s]\n", name, typerep); p->cdr = dbg_loclist; p->name = name; p->pos = fl.l; p->typerep = typerep; p->processed = NO; dbg_loclist = p; } } } static Dbg_LocList *dbg_lookupline(Binder *b) { Dbg_LocList *p; for (p = dbg_loclist; p; p = p->cdr) if (p->name == b) return p; return NULL; } /* dbg_locvar1 is called when the location for a declaration is known. By this time, things allocated in local storage have evaporated (in particular, bindtype_(b). And the Symstrs for most gensyms. */ #ifndef local_fpaddress /* This is here because things have changed so the old code did not work */ /* # define local_fpaddress(x) 0 */ #endif void dbg_locvar1(Binder *b) { Symstr *name = b->bindsym; Dbg_LocList *loc = dbg_lookupline(b); VarClass dbxclass; int32 addr = bindaddr_(b); if (debugging(DEBUG_Q)) cc_msg("-- locvar1(%s)", symname_(name)); if (loc == NULL) { if (debugging(DEBUG_Q)) cc_msg(" omitted\n"); return; /* invented variable name (e.g. s_let) */ } loc->processed = YES; switch (bindstg_(b) & PRINCSTGBITS) { default: defolt: syserr(syserr_dbx_locvar, name, (long)bindstg_(b), (long)addr); return; case bitofstg_(s_typedef): return; /* typedef already done in locvar */ case bitofstg_(s_extern): if (debugging(DEBUG_Q)) cc_msg(" <extern>\n"); return; /* local externs do not allocate store */ case bitofstg_(s_static): dbxclass = CLASS_OWN; break; case bitofstg_(s_auto): #ifndef FORTRAN if (bindxx_(b) != GAP) { if ((addr & BINDADDR_MASK) == BINDADDR_ARG) { /* * An arg which is mostly in a register: persuade dbx * that there are 2 things with same name, first an arg * and second a register variable. This depends on the * later definition taking precedence in dbx. */ dbg_addvar_t(name, loc->typerep, loc->pos, CLASS_PARAM, local_fpaddress(b)); loc->pos += (1L << 22); /* one char later... */ } dbxclass = CLASS_REG; addr = register_number(bindxx_(b)); } else /* continues below... */ #endif switch (addr & BINDADDR_MASK) { case BINDADDR_ARG: #ifdef FORTRAN /* dbx doesn't understand f77 pointers, so has special type */ dbxclass = CLASS_VARPARAM; #else dbxclass = CLASS_PARAM; #endif addr = local_fpaddress(b); break; case BINDADDR_LOC: dbxclass = CLASS_AUTO; addr = local_fpaddress(b); break; default: goto defolt; } break; } if (debugging(DEBUG_Q)) cc_msg(" %c %lx", charofclass[dbxclass], (long)addr); dbg_addvar_t(name, loc->typerep, loc->pos, dbxclass, addr); } /* * The code here is written is this manner, so that for *significant* * effort, we could save variable (code) extent information for * a debugger. Consider f() { { int x; ... } { int y; ... } }. */ bool dbg_scope(BindListList *newbll, BindListList *oldbll) { int32 oldlevel = length((List *)oldbll); int32 newlevel = length((List *)newbll); int32 entering = newlevel - oldlevel; int nvars; if (!usrdbg(DBG_VAR)) return NO; if (newbll == oldbll) return NO; if (debugging(DEBUG_Q)) cc_msg("-- dbg_scope(entering=%ld)\n", entering); if (entering < 0) { BindListList *t = newbll; newbll = oldbll, oldbll = t; } /* * Patch all the local variable declarations back into the dbglist * at the appropriate position with respect to the D_SRCPOS items. */ for (nvars = 0; newbll != oldbll; newbll = newbll->bllcdr) { SynBindList *bl; if (newbll == 0) syserr(syserr_dbx_scope); for (bl = newbll->bllcar; bl; bl = bl->bindlistcdr) { Binder *b = bl->bindlistcar; if (bindstg_(b) & b_dbgbit) continue; if (debugging(DEBUG_Q)) cc_msg(" %s $b", entering>=0 ? "binding" : "unbinding", b); ++nvars; if (entering < 0) { dbg_locvar1(b); bindstg_(b) |= b_dbgbit; } } } { DbgList *p = (DbgList *)DbgAlloc(DbgListVarSize(DEB_SCOPE)); dbgscope = p; /* it is added to dbglist soon by addcodep(NULL, ...) */ p->cdr = NULL; /* for safety ... */ p->debsort = D_SCOPE; p->car.DEB_SCOPE.levelchange = entering; p->car.DEB_SCOPE.level = oldlevel; p->car.DEB_SCOPE.codeaddr = -1; } /* * Return YES here to ask the local code-generator * to notify us the code location of where these declarations start/end, * resulting in a call to dbg_addcodep(NULL, codeaddr). */ return YES; } void dbg_proc(Binder *b, TagBinder *parent, bool ext, FileLine fl) { Symstr *name = bindsym_(b); TypeExpr *t = princtype(bindtype_(b)); if (debugging(DEBUG_Q)) cc_msg("-- proc(%s)\n", symname_(name)); if (usrdbg(DBG_ANY)) { DbgList *p = (DbgList*)DbgAlloc(DbgListVarSize(DEB_PROC)); if (debugging(DEBUG_Q)) cc_msg("startproc $r\n", name); p->debsort = D_PROC; if (h0_(t) != t_fnap) syserr(syserr_dbx_proc); p->car.DEB_PROC.type = dbg_typerep(typearg_(t)); p->car.DEB_PROC.isextern = ext; /* * Don't use DEB_PROC.args currently, so I am expunging it to * save space. * p->car.DEB_PROC.args = length((List *)typefnargs_(t)); */ p->car.DEB_PROC.sourcepos = fl.l; p->car.DEB_PROC.codeaddr = 0; /* fill in at dbg_enterproc */ p->car.DEB_PROC.name = symname_(name); #ifdef FORTRAN dbglistproc = p; dbg_insertitem(p, fl.l, -1); #else /* (not f77) - above may not do any harm, but to be careful: */ p->cdr = dbglist; /* do this last (typerep above) */ dbglistproc = dbglist = p; /* so can be filled in */ #endif } dbg_loclist = 0; } void dbg_enterproc(void) { if (debugging(DEBUG_Q)) cc_msg("-- enterproc(%d)\n", 0); if (usrdbg(DBG_ANY)) { DbgList *p = dbglistproc; if (p == 0 || p->debsort != D_PROC || p->car.DEB_PROC.codeaddr != 0) syserr(syserr_dbx_proc1); if (debugging(DEBUG_Q)) cc_msg("enter '%s' @ %.6lx\n", p->car.DEB_PROC.name, (long)codebase); p->car.DEB_PROC.codeaddr = codebase; } } void dbg_bodyproc(void) { /* ignored by dbx */ } void dbg_return(int32 addr) { /* ignored by dbx */ addr = addr; } void dbg_xendproc(FileLine fl) { #ifdef FORTRAN Dbg_LocList *p = dbg_loclist; for (; p != NULL; p = p->cdr) if (!(p->processed)) syn_equivcheck(p->name); #endif if (debugging(DEBUG_Q)) cc_msg("-- endproc()\n"); dbg_notefileline(fl); dbglistproc = 0; } void dbg_commblock(Binder *b, SynBindList *members, FileLine fl) { char buf[64], *name = symname_(bindsym_(b)); if (members == NULL) return; sprintf(buf, "%s_", ++name); /* lose starting '/', add trailing '_' */ name = copy(buf); dbg_addcomm(1, name, fl.l); for (; members != NULL; members = members->bindlistcdr) { Binder *m = members->bindlistcar; dbg_addvar(bindsym_(m), bindtype_(m), fl.l, CLASS_COMMMEM,bindaddr_(m)); } dbg_addcomm(0, name, fl.l); } #ifdef COMPILING_ON_RISC_OS /* * Dbx looks for the .c .f .h extension on filenames to decide what * language was used, so we have to fiddle with filenames a little. * The code below will not work very well, but cross-compiling on * Arthur to produce an a.out/dbx object is useful only in the * short term for testing. RCC. */ static char xbuf[256]; static char *frigfname(char *name) { if (name[1] == '.') { char t = name[0]; if ((t == 'c') || (t == 'h') || (t == 's')) { sprintf(xbuf, "%s.%c%c", name+2, t, 0); return(xbuf); } } return(name); } #else #define frigfname(name) (name) #endif /* * The object formatter calls writedebug to generate the debugging tables. * It must call obj_stab to put the appropriate things in sym table. */ void dbg_writedebug() { DbgList *p; char *curfile = sourcefile; int32 curline = 0; int32 curcode = -1; char buf[MAXSTRING]; /* to build names in */ if (!usrdbg(DBG_ANY)) return; #define sameline(a, b) ((a)<<10 == (b)<<10) #define ADDRMASK 0x3fffffc #define setpos(x,c) \ if ((c)>=0 && !sameline((x),curline)) \ curline=(x), curcode=(c), dbg_stab(0, N_SLINE, curline, curcode&ADDRMASK) if (debugging(DEBUG_Q)) cc_msg("-- dbg_flush()\n"); dbg_stab(frigfname(curfile), N_SO, ACORN_DBX_VSN, 0); dbg_stdheader(); for (p = (DbgList *)dreverse((List *)dbglist); p != NULL; p = p->cdr) { int32 sort = p->debsort; switch (sort) { default: syserr(syserr_dbx_write, (long)sort); break; case D_SRCPOS: { int32 codeaddr = p->car.DEB_SRCPOS.codeaddr; char *fname = p->car.DEB_SRCPOS.fname; if (fname == NULL) fname = curfile; if (fname != curfile) { curfile = p->car.DEB_SRCPOS.fname; curline = -1; if (codeaddr < 0) codeaddr = curcode; dbg_stab(frigfname(curfile), N_SOL, 0, codeaddr); } setpos(p->car.DEB_SRCPOS.sourcepos, codeaddr); } break; case D_PROC: #ifndef FORTRAN /* ie is C */ { sprintf(buf, "%s:%c%s", p->car.DEB_PROC.name, p->car.DEB_PROC.isextern ? 'F' : 'f', p->car.DEB_PROC.type); dbg_stab(copy(buf), N_FUN, p->car.DEB_PROC.sourcepos, p->car.DEB_PROC.codeaddr & ADDRMASK); } #else /* ie is F77 */ { char *tail; strcpy(buf, p->car.DEB_PROC.name); tail = buf + strlen(buf) - 1; if (*tail != '_') tail++; sprintf(tail, ":%c%s", p->car.DEB_PROC.isextern ? 'F' : 'f', p->car.DEB_PROC.type); dbg_stab(copy(buf), N_FUN, p->car.DEB_PROC.sourcepos, p->car.DEB_PROC.codeaddr & ADDRMASK); } #endif break; case D_SCOPE: { int32 d = p->car.DEB_SCOPE.levelchange; int32 level = p->car.DEB_SCOPE.level; int32 addr = p->car.DEB_SCOPE.codeaddr; int32 final; final = level + d; if (d < 0) { --level; --final; d = -1; } else { d = 1; } for (; level != final; level += d) { if (level > 1) { dbg_stab(NULL, d > 0 ? N_LBRAC:N_RBRAC, level, addr); } } } break; case D_VAR: { char *pp = buf; int ntype; Symstr *sym = p->car.DEB_VAR.sym; setpos(p->car.DEB_VAR.sourcepos, curcode); pp += sprintf(pp, "%s:", symname_(sym)); if (p->car.DEB_VAR.dbxclass != CLASS_AUTO) { *pp++ = charofclass[p->car.DEB_VAR.dbxclass]; } pp += sprintf(pp, "%s", p->car.DEB_VAR.type); ntype = (int)ntypeof[p->car.DEB_VAR.dbxclass]; *pp = 0; { ExtRef *x = symext_(sym); int32 loc = p->car.DEB_VAR.location; if (x != NULL && (x->extflags & xr_bss) && (x->extflags & (xr_defloc | xr_defext)) && x->extoffset != 0) loc = x->extoffset; dbg_stab(copy(buf), ntype, 0, loc); } } break; case D_COMMON: dbg_stab(p->car.DEB_COMMON.name, (p->car.DEB_COMMON.isstart == 0) ? N_ECOMM : N_BCOMM, 0, 0); break; case D_TYPE: { TypeInfo *t = typeinfo_(p->car.DEB_TYPE.typeidx); if (debugging(DEBUG_Q)) cc_msg("-- D_TYPE %ld\n", p->car.DEB_TYPE.typeidx); sprintf(buf, "%s:t%ld=%s", t->name, p->car.DEB_TYPE.typeidx, t->defn); dbg_stab(copy(buf), N_LSYM, 0, 0); } break; case D_STRUCT: { TypeInfo *t = typeinfo_(p->car.DEB_STRUCT.typeidx); if (debugging(DEBUG_Q)) cc_msg("-- D_STRUCT %s\n", t->name); sprintf(buf, "%s:%s", t->name, t->defn); dbg_stab(copy(buf), N_LSYM, 0, 0); } break; } } dbglist = NULL; } void dbg_init() { dbglist = 0; dbgscope = 0; dbglistproc = 0; dbg_loclist = 0; /* for safety */ dbg_inittypes(); } #endif /* TARGET_HAS_DEBUGGER */ /* End of section dbx.c */ bool dbg_needsframepointer(void) { return TRUE; } void dbg_finalise(void) {} void dbg_setformat(int format) {} void dbg_final_src_codeaddr(int32 a, int32 b) { IGNORE(a); IGNORE(b); }
stardot/ncc
ccarm/options.h
/* * options.h -- compiler configuration options set at compile time * Copyright (C) 1991, 1992 Advanced RISC Machines Ltd. All rights reserved. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _options_LOADED #define _options_LOADED /* * The following conditional settings allow the produced compiler (TARGET) * to depend on the HOST (COMPILING_ON) environment. * Note that we choose to treat this independently of the target-machine / * host-machine issue. */ #include "toolver.h" #define NON_RELEASE_VSN TOOLVER_ARMCC #define TARGET_ENDIANNESS_CONFIGURABLE 1 #define TARGET_DEFAULT_BIGENDIAN 0 /* 1 => bigendian default */ /* 0 => littleendian default */ /* unset => defaults to host */ #define PCS_DEFAULTS (PCS_CALLCHANGESPSR /* 32 bit */ \ | PCS_FPE3 \ | PCS_SOFTFP \ /* | PCS_NOSTACKCHECK */ \ /* | PCS_REENTRANT */ \ /* | PCS_FPREGARGS */ \ ) #define TARGET_SYSTEM "" #define TARGET_IS_RISC_OS 1 #define TARGET_HAS_DIVREM_FUNCTION 1 /* divide fn also returns remainder.*/ #define TARGET_HAS_DIV_10_FUNCTION 1 /* fast divide by 10 */ /* the last two would be in target.h*/ /* but are OS-dependent too. */ #define TARGET_HAS_INLINE_ASSEMBLER #define ARM_INLINE_ASSEMBLER #define PROFILE_COUNTS_INLINE 1 /* #define DO_NOT_EXPLOIT_REGISTERS_PRESERVED_BY_CALLEE 1 */ /* #define MOVC_KILLS_REGISTER_PRESERVED_BY_CALLEE_EXPLOITATION 1 */ /* #define TARGET_STACK_MOVES_ONCE 1 / * Experimental option */ #ifndef DRIVER_OPTIONS /* -D__arm done by TARGET_PREDEFINES */ # define DRIVER_OPTIONS {NULL} #endif /* to avoid conflict with host compilers */ #define C_INC_VAR "ARMINC" #define C_LIB_VAR "ARMLIB" #ifndef RELEASE_VSN # define ENABLE_ALL 1 /* -- to enable all debugging options */ #endif #define HOST_WANTS_NO_BANNER 1 /* mac-specific options - find a better home for these sometime! */ #ifdef macintosh # define NO_STATIC_BANNER 1 pascal void SpinCursor(short increment); /* copied from CursorCtl.h */ # define ExecuteOnSourceBufferFill() SpinCursor(1) #endif #define TARGET_STACK_MOVES_ONCE #define target_stack_moves_once (var_cc_private_flags & 32768L) #define DISABLE_ERRORS #define MSG_TOOL_NAME "armcc" /* used to load correct NLS message file */ #define TARGET_HAS_ASD #define TARGET_HAS_DWARF #endif /* end of ccarm/options.h */
stardot/ncc
mip/dwarf1.c
/* * C compiler file mip/dwarf1.c * Copyright: (C) 1995, Advanced RISC Machines Limited. All rights reserved. * Writer for DWARF version 1 debug tables. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <string.h> #include "globals.h" #if defined(TARGET_HAS_DEBUGGER) && defined(TARGET_HAS_DWARF) #include "errors.h" #include "aeops.h" #include "cgdefs.h" #include "version.h" #include "xrefs.h" #include "codebuf.h" #include "builtin.h" /* te_xxx, xxxsegment */ #include "simplify.h" /* mcrep */ #include "mcdep.h" #include "dwarf.h" #include "bind.h" /* for isgensym() */ #include "dw_int.h" typedef union { uint32 u; char const *s; struct { uint32 n; Symstr *sym; } ref; uint32 const *d; } AttribArg; static int32 dw_1_lineinfo_size(void) { int32 n; Dw_FileCoord *p = dw_coord_p, *prev = NULL; if (p == NULL) return 0; for (n = 18; p != NULL; prev = p, p = cdr_(p)) if (prev == NULL || !(p->line == prev->line && p->col == prev->col && p->codeaddr == prev->codeaddr)) n += 10; return n; } void Dw_1_WriteLineinfo(void) { Dw_FileCoord *p = dw_coord_p, *prev = NULL; DataXref *xrefs = NULL; int32 size = dw_1_lineinfo_size(); int32 roundup = (size & 2) ? 2 : 0; int32 sectionbase = p->codeaddr; dw_coord_sentinel.codeseg = bindsym_(codesegment); *dw_coord_q = &dw_coord_sentinel; dw_coord_sentinel.codeaddr = dw_mapped_codebase+dw_mapped_codep; obj_startdebugarea(Dwarf1LineInfoAreaName); Dw_WriteW(size + roundup, 0); Dw_WriteW(sectionbase, 4); xrefs = Dw_Relocate(xrefs, 4, p->codeseg); for (; p != NULL; prev = p, p = cdr_(p)) /* Include the sentinel (to mark the end of info, and to hold the address of end of code-segment) Note that, despite the DWARF spec talking about deltas for the code addresses, it appears to mean from the section start, not from the previous statement. */ if (prev == NULL || !(p->line == prev->line && p->col == prev->col && p->codeaddr == prev->codeaddr)) { Dw_WriteW(p->line, 0); Dw_WriteH(p->col, 0); Dw_WriteW(p->codeaddr-sectionbase, 0); } /* round up to 4-byte multiple */ if (roundup) Dw_WriteH(0, 0); obj_enddebugarea(Dwarf1LineInfoAreaName, xrefs); } /* armobj.c calls writedebug to generate the debugging tables. */ /* It must format them and then call obj_writedebug() */ static unsigned32 dw_1_writeattribute(int attr, unsigned32 offset, AttribArg arg) { offset = Dw_WriteH(attr, offset); switch (attr & 15) { case FORM_ADDR: case FORM_REF: return Dw_WriteW_Relocated(arg.ref.n, arg.ref.sym, offset); case FORM_BLOCK2: case FORM_DATA2: return Dw_WriteH(arg.ref.n, offset); case FORM_DATA4: if (arg.ref.sym != NULL) dw_xrefs = Dw_Relocate(dw_xrefs, offset, arg.ref.sym); return Dw_WriteW(arg.ref.n, offset); case FORM_BLOCK4: return Dw_WriteW(arg.ref.n, offset); case FORM_DATA8: return Dw_WriteL(arg.d, offset); case FORM_STRING: return Dw_WriteInlineString(arg.s, offset); default: syserr("dw_1_writeattribute(%x)", attr); return offset; } } static unsigned32 dw_1_writeattrib_u(int attr, unsigned32 offset, unsigned32 u) { AttribArg arg; arg.ref.n = u; arg.ref.sym = ((attr & 15) == FORM_REF) ? dw_debug_sym : NULL; return dw_1_writeattribute(attr, offset, arg); } static unsigned32 dw_1_writeattrib_l(int attr, unsigned32 offset, uint32 const *d) { AttribArg arg; arg.d = d; return dw_1_writeattribute(attr, offset, arg); } static unsigned32 dw_1_writeattrib_str(int attr, unsigned32 offset, char const *s) { AttribArg arg; arg.s = s; return dw_1_writeattribute(attr, offset, arg); } static unsigned32 dw_1_writeattrib_ref(int attr, unsigned32 offset, unsigned32 n, Symstr *sym) { AttribArg arg; arg.ref.n = n; arg.ref.sym = sym; return dw_1_writeattribute(attr, offset, arg); } static unsigned32 dw_1_attrib_size(int attr) { switch (attr & 15) { case FORM_ADDR: case FORM_REF: case FORM_DATA4: case FORM_BLOCK4: return 6; case FORM_BLOCK2: case FORM_DATA2: return 4; case FORM_DATA8: return 10; default: syserr("dw_1_attrib_size(%x)", attr); return 0; } } static unsigned32 dw_1_attrib_str_size(char const *s) { return (uint32)strlen(s) + 2 + 1; } static unsigned32 dw_1_hdr_size(void) { return 6 + dw_1_attrib_size(AT_sibling); } static unsigned32 dw_1_attrib_friend_size(Friend *amigos) { int32 n = 0; for (; amigos != NULL; amigos = amigos->friendcdr) if (h0_(amigos->u.friendfn) == s_binder) n += (bindstg_(amigos->u.friendfn) & b_undef) ? 0 : 1; else n++; return 4 * n + dw_1_attrib_size(AT_friends); } static unsigned32 dw_1_typeref_size(Dw_ItemList *typep) { /* For DWARF version 1, qualified types do not have information items, nor do base types (the qualifiers and distinction between base and user types are encoded in the reference). It's uncertain whether pointer and reference types should be separate types or not: there are items for them, but also there are modifier values. For now, we make them items. */ switch (debsort_(typep)) { case DW_TAG_base_type: return dw_1_attrib_size(AT_fund_type); case DW_TAG_fref: case DW_TAG_structure_type: case DW_TAG_union_type: case DW_TAG_class_type: case DW_TAG_enumeration_type: case DW_TAG_subroutine_type: case DW_TAG_array_type: case DW_TAG_typedef: return dw_1_attrib_size(AT_user_def_type); case DW_TAG_reference_type: case DW_TAG_pointer_type: case DW_TAG_const_type: case DW_TAG_volatile_type: { unsigned32 n = qualtype_n_(typep); Dw_ItemList *basetype = qualtype_basetype_(typep); if (debsort_(basetype) == DW_TAG_base_type) { if (basetype_typecode_(basetype) == FT_void && n == 1 && qualtype_map_(typep)[0] == MOD_pointer_to) /* special representation for void * */ return dw_1_attrib_size(AT_fund_type); else return dw_1_attrib_size(AT_mod_fund_type) + n + 2; /* fundamental type code */ } else return dw_1_attrib_size(AT_mod_u_d_type) + n + 4; /* type ref */ } default: syserr("dw_1_typeref_size %d", debsort_(typep)); return 0; } } #define MAXEXPRSTRINGSIZE 256 static uint32 Dw_Expr2CPntr(Expr *e, char *buf) { StringSegList *p = ((String *)e)->strseg; uint32 n = 0; for (; p != NULL && (n+p->strseglen) < MAXEXPRSTRINGSIZE; n += p->strseglen, p = p->strsegcdr) memcpy(&buf[n], p->strsegbase, (size_t)p->strseglen); buf[n] = 0; return n; } #define at_default_value_code 0x01e #define AT_default_value_addr AT_ADDR(at_default_value_code) #define AT_default_value_short AT_DATA2(at_default_value_code) #define AT_default_value_int AT_DATA4(at_default_value_code) #define AT_default_value_dble AT_DATA8(at_default_value_code) #define AT_default_value_string AT_STRING(at_default_value_code) static unsigned32 Dw_1_InfoItemSize(Dw_ItemList *p) { /* must be kept in step with WriteInfo below */ unsigned32 n; switch (debsort_(p)) { case DW_TAG_compile_unit: n = dw_1_hdr_size() + dw_1_attrib_size(AT_language) + dw_1_attrib_str_size(sect_name_(p)); if (dw_baseseg.len > 0) { n += dw_1_attrib_size(AT_low_pc) + dw_1_attrib_size(AT_high_pc); } if (dw_1_lineinfo_size() != 0) { n += dw_1_attrib_size(AT_stmt_list); } return n + dw_1_attrib_str_size(version_banner()); case DW_TAG_subprogram: n = dw_1_hdr_size() + dw_1_attrib_str_size(Dw_Unmangle(proc_name_(p))); { Dw_ItemList *restype = proc_type_(p); if (!is_void_type_(restype)) n += dw_1_typeref_size(restype); } if (proc_parent_(p) != NULL) n += dw_1_attrib_size(AT_member); return n + ((proc_endproc_(p) != NULL) ? dw_1_attrib_size(AT_low_pc) + dw_1_attrib_size(AT_high_pc) + dw_1_attrib_size(AT_proc_body) : 0); case DW_TAG_procdecl: n = dw_1_hdr_size() + dw_1_attrib_str_size(Dw_Unmangle(procdecl_name_(p))); { Dw_ItemList *restype = procdecl_type_(p); if (!is_void_type_(restype)) n += dw_1_typeref_size(restype); } if (procdecl_parent_(p) != NULL) n += dw_1_attrib_size(AT_member); if (procdecl_stg_(p) & bitofstg_(s_virtual)) { n += dw_1_attrib_size(AT_vtable_offset); n += dw_1_attrib_str_size(""); } return n; case DW_TAG_endproc: return 0; case DW_TAG_proctype_formal: n = dw_1_hdr_size() + dw_1_typeref_size(formal_type_(p)); if (formal_name_(p)!= NULL) n += dw_1_attrib_str_size(symname_(formal_name_(p))); if (formal_defltexpr_(p) != NULL) { Expr *e = formal_defltexpr_(p); int32 mcsize = mcrepofexpr(e) & MCR_SIZE_MASK; switch (h0_(e)) { case s_integer: n += dw_1_attrib_size((mcsize < 4) ? AT_default_value_short : AT_default_value_int); break; case s_floatcon: n += dw_1_attrib_size((mcsize < 8) ? AT_default_value_int : AT_default_value_dble); break; case s_string: { char buf[MAXEXPRSTRINGSIZE]; n += Dw_Expr2CPntr(e, buf) + 2 + 1; break; } default: n += dw_1_attrib_size(AT_default_value_addr); } } return n; case DW_TAG_subroutine_type: n = dw_1_hdr_size(); { Dw_ItemList *restype = proctype_type_(p); if (!is_void_type_(restype)) n += dw_1_typeref_size(restype); } return n; case DW_TAG_variable: case DW_TAG_formal_parameter: n = dw_1_hdr_size() + dw_1_typeref_size(var_type_(p)) + dw_1_attrib_size(AT_location); if (!isgensym(var_sym_(p))) n += dw_1_attrib_str_size(Dw_Unmangle(symname_(var_sym_(p)))); switch (var_stgclass_(p)) { case Stg_Extern: case Stg_Static: return n + 5; case Stg_Reg: case Stg_ArgReg: return n + 5; case Stg_Auto: case Stg_ArgAuto: if (var_base_(p).r == R_NOFPREG) return 0; return n + 11; default: syserr("Dw_1_InfoItemSize: stg %p = %d", p, var_stgclass_(p)); } case DW_TAG_unspecified_parameters: return dw_1_hdr_size(); case DW_TAG_typedef: return dw_1_hdr_size() + dw_1_attrib_str_size(type_name_(p)) + dw_1_typeref_size(type_type_(p)); case DW_TAG_fref: case DW_TAG_class_type: case DW_TAG_union_type: case DW_TAG_structure_type: n = dw_1_hdr_size(); if (struct_name_(p) != NULL) n += dw_1_attrib_str_size(struct_name_(p)); if (struct_size_(p) != 0) n += dw_1_attrib_size(AT_byte_size); if (struct_friends_(p) != NULL) n += dw_1_attrib_friend_size(struct_friends_(p)); return n; case DW_TAG_volatile_type: case DW_TAG_const_type: case DW_TAG_pointer_type: case DW_TAG_reference_type: return 0; case DW_TAG_ptr_to_member_type: n = dw_1_hdr_size() + dw_1_typeref_size(ptrtomem_container_(p)) + dw_1_typeref_size(ptrtomem_type_(p)); return n; case DW_TAG_member: n = dw_1_hdr_size() + dw_1_attrib_str_size(member_name_(p)) + dw_1_typeref_size(member_type_(p)); if (member_offset_(p) != -1) n += dw_1_attrib_size(AT_location) + 6 /* op_const(n) op_add */; if (member_bsize_(p) != 0) { n += dw_1_attrib_size(AT_bit_size) + dw_1_attrib_size(AT_bit_offset); } return n; case DW_TAG_inheritance: n = dw_1_hdr_size() + dw_1_typeref_size(inherit_type_(p)) + dw_1_attrib_size(AT_location) + 6; if (inherit_virt_(p)) n += dw_1_attrib_str_size(""); return n; case DW_TAG_enumeration_type: n = dw_1_hdr_size(); if (enum_name_(p) != NULL) n += dw_1_attrib_str_size(enum_name_(p)); n += dw_1_attrib_size(AT_byte_size); { Dw_ItemList *elts = enum_children_(p); n += dw_1_attrib_size(AT_element_list); for (; elts != NULL; elts = sibling_(elts)) if (debsort_(elts) == DW_TAG_enumerator) { n += 4 + (uint32)strlen(enumerator_name_(elts)) + 1; } } return n; case DW_TAG_enumerator: return 0; /* DWARF version 2 only */ case TAG_padding: /* null entry to terminate sibling chains */ { Dw_ItemList *l = *null_parent_(p); for (; l != p; l = sibling_(l)) if (dbgloc_(l) != 0) return 4; debsort_(p) = DW_TAG_ignore; return 0; } case DW_TAG_array_type: n = dw_1_hdr_size() + dw_1_attrib_size(AT_subscr_data); n += array_open_(p) ? 10 : 12; return n + dw_1_typeref_size(array_basetype_(p)); case DW_TAG_lexical_block: return dw_1_hdr_size() + dw_1_attrib_size(AT_low_pc) + dw_1_attrib_size(AT_high_pc); case DW_TAG_ignore: case DW_TAG_end_lexical_block: case DW_TAG_base_type: case DW_TAG_array_bound: return 0; default: syserr("Dw_1_InfoItemSize %d", debsort_(p)); return 0; } } static unsigned32 dw_this_itemsize; static unsigned32 dw_1_hdr(Dw_ItemList *p, int itemsort, unsigned32 offset) { dw_this_itemsize = Dw_1_InfoItemSize(p); offset = Dw_WriteW(dw_this_itemsize, offset); offset = Dw_WriteH(itemsort, offset); { Dw_ItemList *sib = sibling_(p); for (; sibling_(sib) != 0; sib = sibling_(sib)) if (dbgloc_(sib) != 0) break; return dw_1_writeattrib_u(AT_sibling, offset, dbgloc_(sib)); } } static unsigned32 dw_1_writetyperef(Dw_ItemList *typep, unsigned32 offset) { /* For DWARF version 1, qualified types do not have information items, nor do base types (the qualifiers and distinction between base and user types are encoded in the reference). It's uncertain whether pointer and reference types should be separate types or not: there are items for them, but also there are modifier values. For now, we use modifiers. */ switch (debsort_(typep)) { case DW_TAG_base_type: return dw_1_writeattrib_u(AT_fund_type, offset, basetype_typecode_(typep)); case DW_TAG_structure_type: case DW_TAG_union_type: case DW_TAG_class_type: case DW_TAG_enumeration_type: case DW_TAG_subroutine_type: case DW_TAG_array_type: case DW_TAG_typedef: return dw_1_writeattrib_u(AT_user_def_type, offset, dbgloc_(typep)); case DW_TAG_reference_type: case DW_TAG_pointer_type: case DW_TAG_const_type: case DW_TAG_volatile_type: { int n = qualtype_n_(typep); Dw_TypeRep *basetype = qualtype_basetype_(typep); if (debsort_(basetype) == DW_TAG_base_type) { if (basetype_typecode_(basetype) == FT_void && n == 1 && qualtype_map_(typep)[0] == MOD_pointer_to) /* special representation for void * */ return dw_1_writeattrib_u(AT_fund_type, offset, FT_pointer); else { offset = dw_1_writeattrib_u(AT_mod_fund_type, offset, n+2L); offset = Dw_WriteBN(qualtype_map_(typep), n, offset); return Dw_WriteH(basetype_typecode_(basetype), offset); } } else { offset = dw_1_writeattrib_u(AT_mod_u_d_type, offset, n+4L); offset = Dw_WriteBN(qualtype_map_(typep), n, offset); return Dw_WriteW_Relocated(dbgloc_(basetype), dw_debug_sym, offset); } } default: syserr("dw_1_writetype %d", debsort_(typep)); return 0; } } static unsigned32 dw_1_write_friends(unsigned32 offset, Friend *amigos) { Dw_ItemList *p; offset = Dw_WriteH(AT_friends, offset); offset = Dw_WriteH(dw_1_attrib_friend_size(amigos)-dw_1_attrib_size(AT_friends), offset); for (; amigos != NULL ; amigos = amigos->friendcdr) { if (h0_(amigos->u.friendclass) == s_tagbind) { dw_xrefs = Dw_Relocate(dw_xrefs, offset, dw_debug_sym); offset = Dw_WriteW(dbgloc_((Dw_TypeRep *)((TagBinder *)amigos->u.friendclass)->tagbinddbg), offset); } else if (!(bindstg_(amigos->u.friendfn) & b_undef)) for (p = dw_list; p != NULL; p = cdr_(p)) if (debsort_(p) == DW_TAG_subprogram && strncmp(proc_name_(p), symname_(bindsym_(amigos->u.friendfn)), strlen(proc_name_(p))) == 0) { dw_xrefs = Dw_Relocate(dw_xrefs, offset, dw_debug_sym); offset = Dw_WriteW(dbgloc_(p), offset); break; } } return offset; } void Dw_1_WriteInfo(void) { Dw_ItemList *p; unsigned32 infosize, offset, roundup; dw_xrefs = NULL; obj_startdebugarea(Dwarf1DebugAreaName); for (infosize = 0, p = dw_list; p != NULL; p = cdr_(p)) { uint32 n; if (debsort_(p) == DW_TAG_fref) debsort_(p) = struct_undefsort_(p); n = Dw_1_InfoItemSize(p); dbgloc_(p) = n == 0 ? 0 : infosize; infosize += n; } if (infosize & 3) roundup = 8 - (infosize & 3); else roundup = 0; for (offset = 0, p = dw_list; p != NULL; p = cdr_(p)) { int sort = debsort_(p); unsigned32 start = offset; switch (sort) { default: syserr(syserr_dbg_write, (long)sort); break; case DW_TAG_compile_unit: { Dw_ItemList dummy; dummy.dbgloc = infosize + roundup; sibling_(p) = &dummy; offset = dw_1_hdr(p, TAG_compile_unit, offset); } offset = dw_1_writeattrib_u(AT_language, offset, (LanguageIsCPlusPlus) ? LANG_C_PLUS_PLUS : LANG_C89); offset = dw_1_writeattrib_str(AT_name, offset, sect_name_(p)); if (dw_baseseg.len > 0) { offset = dw_1_writeattrib_ref(AT_low_pc, offset, 0, sect_codeseg_(p)); offset = dw_1_writeattrib_ref(AT_high_pc, offset, dw_baseseg.len, sect_codeseg_(p)); } if (dw_1_lineinfo_size() != 0) { offset = dw_1_writeattrib_ref(AT_stmt_list, offset, 0, dw_lineinfo_sym); } offset = dw_1_writeattrib_str(AT_producer, offset, version_banner()); break; case DW_TAG_subprogram: offset = dw_1_hdr(p, proc_global_(p) ? TAG_global_subroutine : TAG_subroutine, offset); offset = dw_1_writeattrib_str(AT_name, offset, Dw_Unmangle(proc_name_(p))); { Dw_ItemList *restype = proc_type_(p); if (!is_void_type_(restype)) offset = dw_1_writetyperef(restype, offset); } if (proc_parent_(p) != NULL) offset = dw_1_writeattrib_ref(AT_member, offset, dbgloc_(proc_parent_(p)), dw_debug_sym); if (proc_endproc_(p) != NULL) { offset = dw_1_writeattrib_ref(AT_low_pc, offset, proc_entry_(p), proc_codeseg_(p)); offset = dw_1_writeattrib_ref(AT_proc_body, offset, proc_body_(p), proc_codeseg_(p)); offset = dw_1_writeattrib_ref(AT_high_pc, offset, high_pc_(p), proc_codeseg_(p)); } break; case DW_TAG_procdecl: offset = dw_1_hdr(p, procdecl_global_(p) ? TAG_global_subroutine : TAG_subroutine, offset); offset = dw_1_writeattrib_str(AT_name, offset, Dw_Unmangle(procdecl_name_(p))); { Dw_ItemList *restype = procdecl_type_(p); if (!is_void_type_(restype)) offset = dw_1_writetyperef(restype, offset); } if (procdecl_parent_(p) != NULL) offset = dw_1_writeattrib_ref(AT_member, offset, dbgloc_(procdecl_parent_(p)), dw_debug_sym); if (procdecl_stg_(p) & bitofstg_(s_virtual)) { offset = dw_1_writeattrib_u(AT_vtable_offset, offset, procdecl_voffset_(p)); offset = dw_1_writeattrib_str(AT_virtual, offset, ""); } break; case DW_TAG_endproc: break; case DW_TAG_unspecified_parameters: offset = dw_1_hdr(p, TAG_unspecified_parameters, offset); break; case DW_TAG_proctype_formal: offset = dw_1_hdr(p, TAG_formal_parameter, offset); if (formal_name_(p) != NULL) offset = dw_1_writeattrib_str(AT_name, offset, symname_(formal_name_(p))); offset = dw_1_writetyperef(formal_type_(p), offset); { Expr *e = formal_defltexpr_(p); if (e != NULL) switch (h0_(e)) { case s_integer: offset = dw_1_writeattrib_u(((mcrepofexpr(e) & MCR_SIZE_MASK) < 4) ? AT_default_value_short : AT_default_value_int, offset, intval_(e)); break; case s_string: { char buf[MAXEXPRSTRINGSIZE]; (void)Dw_Expr2CPntr(e, buf); offset = dw_1_writeattrib_str(AT_default_value_string, offset, buf); break; } case s_floatcon: if (mcrepofexpr(e) & MCR_SIZE_MASK < 8) offset = dw_1_writeattrib_u(AT_default_value_int, offset, ((FloatCon *)e)->floatbin.fb.val); else offset = dw_1_writeattrib_l(AT_default_value_dble, offset, (uint32 *)((FloatCon *)e)->floatbin.irep); break; default: offset = dw_1_writeattrib_ref(AT_default_value_addr, offset, dbgloc_(formal_defltfn_(p)), dw_debug_sym); } } break; case DW_TAG_subroutine_type: offset = dw_1_hdr(p, TAG_subroutine_type, offset); { Dw_ItemList *restype = proctype_type_(p); if (!is_void_type_(restype)) offset = dw_1_writetyperef(restype, offset); } break; case DW_TAG_ptr_to_member_type: offset = dw_1_hdr(p, TAG_ptr_to_member_type, offset); offset = dw_1_writetyperef(ptrtomem_container_(p), offset); offset = dw_1_writetyperef(ptrtomem_type_(p), offset); break; case DW_TAG_variable: sort = var_stgclass_(p) == Stg_Extern ? TAG_global_variable : TAG_local_variable; case DW_TAG_formal_parameter: if ((var_stgclass_(p) == Stg_Auto || var_stgclass_(p) == Stg_ArgAuto) && var_base_(p).r == R_NOFPREG) break; offset = dw_1_hdr(p, sort, offset); if (!isgensym(var_sym_(p))) offset = dw_1_writeattrib_str(AT_name, offset, Dw_Unmangle(symname_(var_sym_(p)))); offset = dw_1_writetyperef(var_type_(p), offset); offset = Dw_WriteH(AT_location, offset); switch (var_stgclass_(p)) { case Stg_Extern: case Stg_Static: offset = Dw_WriteH(5, offset); offset = Dw_WriteB(OP_ADDR, offset); { Symstr *s = var_base_(p).sym; obj_symref(s, symext_(s) == NULL ? xr_data|xr_weak : xr_data, 0); offset = Dw_WriteW_Relocated(var_loc_(p), s, offset); } break; case Stg_Reg: case Stg_ArgReg: offset = Dw_WriteH(5, offset); offset = Dw_WriteB(OP_REG, offset); offset = Dw_WriteW(var_loc_(p), offset); break; case Stg_Auto: case Stg_ArgAuto: offset = Dw_WriteH(11, offset); offset = Dw_WriteB(OP_BASEREG, offset); offset = Dw_WriteW(var_base_(p).r, offset); offset = Dw_WriteB(OP_CONST, offset); offset = Dw_WriteW(var_loc_(p), offset); offset = Dw_WriteB(OP_ADD, offset); break; } break; case DW_TAG_typedef: offset = dw_1_hdr(p, TAG_typedef, offset); offset = dw_1_writeattrib_str(AT_name, offset, type_name_(p)); offset = dw_1_writetyperef(type_type_(p), offset); break; case DW_TAG_class_type: case DW_TAG_union_type: case DW_TAG_structure_type: offset = dw_1_hdr(p, debsort_(p), offset); if (struct_name_(p) != NULL) offset = dw_1_writeattrib_str(AT_name, offset, struct_name_(p)); if (struct_size_(p) != 0) offset = dw_1_writeattrib_u(AT_byte_size, offset, struct_size_(p)); if (struct_friends_(p) != NULL) offset = dw_1_write_friends(offset, struct_friends_(p)); break; case DW_TAG_volatile_type: case DW_TAG_const_type: case DW_TAG_pointer_type: case DW_TAG_reference_type: break; case DW_TAG_member: offset = dw_1_hdr(p, TAG_member, offset); offset = dw_1_writeattrib_str(AT_name, offset, member_name_(p)); offset = dw_1_writetyperef(member_type_(p), offset); if (member_bsize_(p) != 0) { offset = dw_1_writeattrib_u(AT_bit_size, offset, member_bsize_(p)); offset = dw_1_writeattrib_u(AT_bit_offset, offset, member_boffset_(p)); } if (member_offset_(p) != -1) { offset = dw_1_writeattrib_u(AT_location, offset, 6); offset = Dw_WriteB(OP_CONST, offset); offset = Dw_WriteW(member_offset_(p), offset); offset = Dw_WriteB(OP_ADD, offset); } break; case DW_TAG_inheritance: offset = dw_1_hdr(p, TAG_inheritance, offset); offset = dw_1_writetyperef(inherit_type_(p), offset); offset = dw_1_writeattrib_u(AT_location, offset, 6); offset = Dw_WriteB(OP_CONST, offset); offset = Dw_WriteW(inherit_offset_(p), offset); offset = Dw_WriteB(OP_ADD, offset); if (inherit_virt_(p)) offset = dw_1_writeattrib_str(AT_virtual, offset, ""); break; case DW_TAG_enumeration_type: offset = dw_1_hdr(p, TAG_enumeration_type, offset); if (enum_name_(p) != NULL) offset = dw_1_writeattrib_str(AT_name, offset, enum_name_(p)); offset = dw_1_writeattrib_u(AT_byte_size, offset, enum_size_(p)); { Dw_ItemList *elts = enum_children_(p); Dw_ItemList *prev = NULL, *next; /* DWARF version 1 requires the enumeration members in reverse order. Pre-reverse them. (And reverse back on writing) */ for (; elts != NULL; prev = elts, elts = next) { next = sibling_(elts); sibling_(elts) = prev; } elts = prev; offset = dw_1_writeattrib_u(AT_element_list, offset, dw_this_itemsize - (offset + 6 - start)); prev = NULL; for (; elts != NULL; prev = elts, elts = next) { if (debsort_(elts) == DW_TAG_enumerator) { /* This just ignores the sibling list terminator */ offset = Dw_WriteW(enumerator_val_(elts), offset); offset = Dw_WriteInlineString(enumerator_name_(elts), offset); } next = sibling_(elts); sibling_(elts) = prev; } } break; case DW_TAG_enumerator: break; /* DWARF version 2 only */ case TAG_padding: /* null entry to terminate sibling chains */ offset = Dw_WriteW(4, offset); break; case DW_TAG_array_type: offset = dw_1_hdr(p, TAG_array_type, offset); offset = dw_1_writeattrib_u(AT_subscr_data, offset, dw_1_typeref_size(array_basetype_(p)) + (array_open_(p) ? 10 : 12)); offset = Dw_WriteB(array_open_(p) ? FMT_FT_C_X : FMT_FT_C_C, offset); offset = Dw_WriteH(FT_signed_integer, offset); offset = Dw_WriteW(array_lowerbound_(p), offset); if (array_open_(p)) offset = Dw_WriteH(0, offset); else offset = Dw_WriteW(array_upperbound_(p), offset); offset = Dw_WriteB(FMT_ET, offset); offset = dw_1_writetyperef(array_basetype_(p), offset); break; case DW_TAG_lexical_block: offset = dw_1_hdr(p, TAG_lexical_block, offset); offset = dw_1_writeattrib_ref(AT_low_pc, offset, startscope_codeaddr_(p), startscope_codeseg_(p)); offset = dw_1_writeattrib_ref(AT_high_pc, offset, endscope_codeaddr_(startscope_end_(p))+4, startscope_codeseg_(p)); /* +4 is bodge for XRAY */ break; case DW_TAG_ignore: case DW_TAG_end_lexical_block: case DW_TAG_base_type: case DW_TAG_array_bound: break; } } if (roundup != 0) { unsigned32 w = 0; Dw_WriteW(roundup, offset); obj_writedebug(&w, roundup - 4); } obj_enddebugarea(Dwarf1DebugAreaName, dw_xrefs); } #else typedef int dummy; /* prevent translation unit from being empty */ #endif /* defined(TARGET_HAS_DWARF) && defined(TARGET_HAS_DEBUGGER) */ /* end of mip/dwarf1.c */
stardot/ncc
tests/2597.c
/* Test for what sqrt() should return */ /* Copyright (C) 1997, Advanced RISC Machines, All Rights Reserved. */ /* SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <stdlib.h> #include <math.h> #include <errno.h> #include "testutil.h" #include "mathtest.h" #include "mathtest.c" #define EQDI(x, y) (EQI((x).i.se_hi, (y).i.se_hi), EQI((x).i.lo, (y).i.lo)) void t2597_zero(void) { double_ints d, r; get_errno(); /* reset errno */ d.f = 0.0; r.f = sqrt(d.f); EQDI(r, d); EQI(get_errno(), 0); dneg(&d); r.f = sqrt(d.f); EQDI(r, d); EQI(get_errno(), 0); } void t2597_one(void) { double_ints d, r; get_errno(); /* reset errno */ dset_to_one(&d); r.f = sqrt(d.f); EQDI(r, d); EQI(get_errno(), 0); dneg(&d); r.f = sqrt(d.f); d.f = -HUGE_VAL; EQDI(r, d); EQI(get_errno(), EDOM); } void t2597_inf(void) { double_ints d, r; get_errno(); /* reset errno */ dset_to_inf(&d); r.f = sqrt(d.f); EQDI(r, d); EQI(get_errno(), 0); dneg(&d); r.f = sqrt(d.f); d.f = -HUGE_VAL; EQDI(r, d); EQI(get_errno(), EDOM); } void t2597_min(void) { double_ints d, r; get_errno(); /* reset errno */ d.f = 1.4916681482400413E-154*1.4916681482400413E-154; r.f = sqrt(d.f); d.f = 1.4916681482400413E-154; EQDI(r, d); EQI(get_errno(), 0); dneg(&d); r.f = sqrt(d.f); d.f = -HUGE_VAL; EQDI(r, d); EQI(get_errno(), EDOM); } void t2597_max(void) { double_ints d, r; get_errno(); /* reset errno */ d.f = 1.3407807929942596E154 * 1.3407807929942596E154; r.f = sqrt(d.f); d.f = 1.3407807929942596E154; EQDI(r, d); EQI(get_errno(), 0); dneg(&d); r.f = sqrt(d.f); d.f = -HUGE_VAL; EQDI(r, d); EQI(get_errno(), EDOM); } void t2597_nan(void) { double_ints d; get_errno(); dset_to_qnan(&d); d.f = sqrt(d.f); EQU(disnan(&d), TRUE); EQI(get_errno(), 0); } void t2597_104(void) { double_ints d, r; get_errno(); /* reset errno */ d.f = 10.4; r.f = sqrt(d.f); d.f = 3.2249030993194200967; EQDI(r, d); EQI(get_errno(), 0); dneg(&d); r.f = sqrt(d.f); d.f = -HUGE_VAL; EQDI(r, d); EQI(get_errno(), EDOM); } void t2597_106(void) { double_ints d, r; get_errno(); /* reset errno */ d.f = 10.6; r.f = sqrt(d.f); d.f = 3.2557641192199411329; EQDI(r, d); EQI(get_errno(), 0); dneg(&d); r.f = sqrt(d.f); d.f = -HUGE_VAL; EQDI(r, d); EQI(get_errno(), EDOM); } void t2597_105(void) { double_ints d, r; get_errno(); /* reset errno */ d.f = 10.5; r.f = sqrt(d.f); d.f = 3.24037034920393; EQDI(r, d); EQI(get_errno(), 0); dneg(&d); r.f = sqrt(d.f); d.f = -HUGE_VAL; EQDI(r, d); EQI(get_errno(), EDOM); } void t2597_110(void) { double_ints d, r; get_errno(); /* reset errno */ d.f = 11.0; r.f = sqrt(d.f); d.f = 3.3166247903554; EQDI(r, d); EQI(get_errno(), 0); dneg(&d); r.f = sqrt(d.f); d.f = -HUGE_VAL; EQDI(r, d); EQI(get_errno(), EDOM); } void t2597_1000(void) { double_ints d, r; get_errno(); /* reset errno */ d.f = 100.0; r.f = sqrt(d.f); d.f = 10.0; EQDI(r, d); EQI(get_errno(), 0); dneg(&d); r.f = sqrt(d.f); d.f = -HUGE_VAL; EQDI(r, d); EQI(get_errno(), EDOM); } int main(void) { /* disable the IVO exception */ __fp_status(__fpsr_IOE+__fpsr_IOC, 0); get_errno(); /* reset errno */ BeginTest(); t2597_zero(); t2597_one(); t2597_min(); t2597_max(); t2597_inf(); t2597_nan(); t2597_104(); t2597_106(); t2597_105(); t2597_110(); t2597_1000(); EndTest(); return 0; }
stardot/ncc
tests/2789.c
<filename>tests/2789.c<gh_stars>0 /* * ARM C compiler regression test $RCSfile$ * Copyright (C) 1997 Advanced Risc Machines Ltd. All rights reserved. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <stdlib.h> #include "testutil.h" typedef unsigned int UINT32; typedef unsigned char UINT8; typedef struct { UINT32 parg0_save; UINT32 parg1_save; UINT32 parg2_save; UINT32 parg3_save; UINT32 parg4_save; UINT32 farg0_save; UINT32 farg1_save; UINT32 farg2_save; UINT32 farg3_save; UINT32 farg4_save; UINT32 bk_save; UINT32 s0_save; UINT32 s1_save; UINT32 s2_save; UINT32 s3_save; UINT32 s4_save; UINT32 pd_save; UINT32 sp_save; UINT32 fp_save; UINT32 lk_save; UINT32 st_save; UINT32 pc_save; UINT32 tc_save; UINT32 tb_save; UINT32 sb_save; } ABrisc; typedef struct tcb { UINT32 status; struct tcb *next; struct tcb *prev; UINT32 irqmask_save; UINT32 tid; UINT32 pri; UINT32 or_mask; UINT32 and_mask; UINT8 *mailbox; struct tcb *next_delay; struct tcb *prev_delay; UINT32 exp_time; UINT32 *errp; UINT32 retValue; struct llh *plist; UINT32 newPri; UINT32 a1_save; UINT32 a2_save; UINT32 a3_save; UINT32 a4_save; UINT32 v1_save; UINT32 v2_save; UINT32 v3_save; UINT32 v4_save; UINT32 v5_save; UINT32 *sb_save; UINT32 *sl_save; UINT32 *fp_save; UINT32 *ip_save; UINT32 *sp_save_usr; void (*lr_save_usr) (); UINT32 spsr_save; void (*lr_save) (); UINT32 *stack_end; UINT32 timeslice; UINT32 *userTask; void (*onReady) (struct tcb *ptcb); void (*onFault) (struct tcb * ptcb, UINT32 faultCode); void (*onDelete) (struct tcb *ptcb); UINT32 resumeTime; UINT32 runTime; ABrisc ABrisc_save; /* Defined above */ UINT32 *trendPtr; } TCB; typedef struct llh { union { UINT32 status; UINT32 evFlag; UINT32 pendOpt; } u; TCB *next; TCB *prev; TCB *tail; } LLH; TCB *os_tcbList[256]; TCB *os_curTCB; #define HW_GLOBAL_IRQ_EN (1 << 0x00) #define HW_GLOBAL_FIQ_EN (1 << 0x01) void OS_tCreate( void (*task) (), UINT32 tid, UINT32 pri, UINT32 *tStack, UINT32 stkLength, TCB *ptcb, UINT32 *errp ) { *errp = 0; if (pri >= 32) { *errp = 0x0013; } else if ((tid != 0) && (tid < 256) && (os_tcbList[tid] == 0)) { os_tcbList[tid] = ptcb; ptcb->tid = tid; ptcb->pri = pri; ptcb->newPri = 0; ptcb->status = 0; ptcb->next = 0; ptcb->prev = 0; ptcb->or_mask = 0; ptcb->and_mask = 0; ptcb->mailbox = 0; ptcb->next_delay = 0; ptcb->prev_delay = 0; ptcb->exp_time = 0; ptcb->errp = 0; ptcb->retValue = 0; ptcb->plist = 0; ptcb->plist = 0; ptcb->userTask = 0; ptcb->onReady = 0; ptcb->onFault = 0; ptcb->irqmask_save = HW_GLOBAL_IRQ_EN | HW_GLOBAL_FIQ_EN; ptcb->sp_save_usr = tStack; ptcb->sl_save = (UINT32 *) ((UINT32) tStack - stkLength * 4 + 256); ptcb->stack_end = (UINT32 *) ((UINT32) tStack - stkLength * 4); *ptcb->stack_end = 0xAB; ptcb->timeslice = 0; ptcb->lr_save = task; ptcb->spsr_save = 0x10; ptcb->lr_save_usr = 0; ptcb->fp_save = 0; ptcb->ABrisc_save.st_save = 0x0f000001; ptcb->ABrisc_save.tc_save = 0; } else { *errp = 1; } return; } #define EQP(a, b) EQI((int)a, (int)b) void t1() { /* Initializing the struct */ int i=0; UINT32 tStack=0xa000; UINT32 errp; TCB tcb; char *buffer = (char *)&tcb; for (i=0; i<sizeof(TCB); ++i) buffer[i]=(unsigned char)(i%256); os_tcbList[0x10]=0; OS_tCreate(0, 0x00000010, /* tid */ 0x00000001, /* pri */ &tStack, /* tStack */ 0x000000ff, /* stkLength */ &tcb, &errp); EQP(errp, 0); EQI(tcb.tid, 0x10); EQI(tcb.pri, 0x1); EQP(tcb.newPri, 0); EQI(tcb.status, 0); EQP(tcb.next, 0); EQP(tcb.prev, 0); EQI(tcb.or_mask, 0); EQI(tcb.and_mask, 0); EQP(tcb.mailbox, 0); EQP(tcb.next_delay, 0); EQP(tcb.prev_delay, 0); EQI(tcb.exp_time, 0); EQP(tcb.errp, 0); EQI(tcb.retValue, 0); EQP(tcb.plist, 0); EQP(tcb.userTask, 0); EQP(tcb.onReady, 0); EQP(tcb.onFault, 0); EQI(tcb.irqmask_save, 3); EQP(tcb.sp_save_usr, &tStack); EQP(*tcb.stack_end, 0xab); EQI(tcb.timeslice, 0); EQP(tcb.lr_save, 0); EQI(tcb.spsr_save, 0x10); EQP(tcb.lr_save_usr, 0); EQP(tcb.fp_save, 0); EQI(tcb.ABrisc_save.st_save, 0x0f000001); EQI(tcb.ABrisc_save.tc_save, 0); } int new_calls = 0; size_t requested_size = 0; void *allocated_block = 0; void *ptr_arg = 0; size_t extra_size_arg = 0; void *New(size_t n, void *heap, size_t heap_size) { ++new_calls; requested_size = n; ptr_arg = heap; extra_size_arg = heap_size; return allocated_block = (n <= heap_size ? heap : 0); } void t2() { int x; void *res = New(100, &x, 200); EQI(new_calls, 1); EQI(requested_size, 100); EQP(ptr_arg, &x); EQI(extra_size_arg, 200); EQP(allocated_block, &x); EQP(res, &x); } int main() { t1(); t2(); return 0; }
stardot/ncc
cfe/syn.c
<filename>cfe/syn.c /* * cfe/syn.c: syntax analysis phase of C/C++ compiler. * Copyright (C) Codemist Ltd., 1988-1993 * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Advanced RISC Machines Limited, 1992. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 188 * Checkin $Date$ * Revising $Author$ */ /* ************* NASTY HACK, PLEASE FIX ME *************************** */ #define errname_templateformal errname_formalarg /* AM memo: Jan 93: need to fix lookahead w.r.t. '#if' (re-entrancy). */ /* Discussion by AM: function call extension syntax (prefix/postfix). */ /* Currently there are various C extensions to function call syntax. */ /* e.g. extern int __pure __swi(3) (*f(int g()))(int h()); */ /* There are also #pragma's which can also specify some of these. */ /* __pure and __swi above have never affected g() and h(), but the */ /* #pragma versions do. Moreover, until 6 Apr 93, there was a bug in */ /* that __pure and __swi were placed on the result of f(), not on f */ /* itself. Such qualifiers are now placed on BOTH (but still not */ /* on g or h). mip/cg.c ignores __swi when not on a fn constant. */ /* Since C++ has syntax (e.g.) "int f() const;" to qualify the fn call */ /* then we can extend this notation to allow: */ /* int (*f(int) __pure)(void) __swi(6); */ /* to denote that f is implemented by swi 6 but always returns a pure */ /* function. In the meantime, PREFIX (as before) __pure and __swi */ /* apply to both a function AND any function result(s), but NOT to */ /* its arguments. */ /* Note that C++ 'extern "C" int (*f)();' has similar properties and */ /* treatment of the various features should really all be unified! */ /* AM Memo: TypeFnAux (e.g. oldstyle) may enable us to kill the */ /* dreadful uses of 999 and 1999 in the following. */ /* AM Memo: reconsider the uses of FileLine fl, in particular the */ /* possibility of having a FileLine field in DeclRhsList. */ /* AM Jan 90: rework 'declflag' contexts; fix register syntax, */ /* fn-type parsing in formals/casts and 'void' formals. */ /* AM Sep 89: Rework 'incomplete type' code. Kill some Parkes hacks. */ /* AM Sep 89: re-work s_typestartsym so that it may only occur in */ /* contexts in which macros may reasonably use it. */ /* AM, Mar 89: rework rd_declarator now that ANSI have ruled on [] and */ /* () combinations in declarators. Fix bugs whereby */ /* bad combinations of () and [] via typedef were missed. */ #ifndef _SYN_H #include <string.h> /* for memset */ #include "globals.h" #include "syn.h" #include "pp.h" /* for pp_inhashif */ #include "lex.h" #include "simplify.h" #include "bind.h" #include "sem.h" #include "aetree.h" #include "builtin.h" #include "vargen.h" #include "mcdep.h" /* for dbg_xxx */ #include "store.h" #include "errors.h" #include "aeops.h" #include "codebuf.h" #include "compiler.h" /* UpdateProgress */ /* It seems better to forbid "int a{2};" etc in C++. */ #define archaic_init(s) ((s) == s_lbrace) /* and for C-only compilers... */ #define rd_cpp_name(x) (void)0 #define rd_handler() 0 #define rd_compound_statement(op) 0 #define rd_template_formals() 0 #define rd_template_postfix(a, b) ((void)0) #define rd_template_actuals(a) ((ExprList *)0) #define push_template_args(a,b) 0 #define rd_meminit(a, b, c, d, e) 0 #define rd_qualifying_name(xscope, FB_GLOBAL) 0 #define rd_pseudo(xscope) 0 #define rd_cplusplus_for(fl) 0 #define rd_cppcast() 0 #define rd_classdecl(b) (void)0 #define rd_dtor(sv) (void)0 #define cmd_rescope(s,ss,c) (c) #define syn_setlab(l, s) (void)0 #define syn_reflab(l, s, c) (c) #define reverse_SynBindList(x) (SynBindList *)dreverse((List *)x) #define cpp_mkunaryorop(op, a) 0 #define cpp_mkbinaryorop(op, a, b) 0 #define cpp_mkfnaporop(e, l) 0 #define instate_classname_typedef(b, fl) 0 #define syn_embed_if(x) 0 #define fixup_special_member(declarator, type, convtype, scope, stg) 0 #define use_classname_typedef(basictype) (void)0 #define memfn_typefix(temp, scope) (void)0 #define cpp_special_member(d) 0 #define reinvent_fn_DeclRhsList(a,b,c,d) 0 #define push_multi_scope(b) 0 #define cpp_end_strdecl(b) (void)0 #define syn_pop_linkage() (void)0 #define syn_memdtor(a, b, c, d) (void *)0 #define ispurefnconst(e) 0 #define gen_reftemps() (void)0 #define instate_anonu_members(d, b) (void)0 #define ovld_match_def(b, t, l, p, d) 0 #define rd_cpp_prefixextra(op) 0 #define set_access_context(a, b) 0 #define rd_access_adjuster(a,b) (void)0 #define cg_topdecl(a,b) ((void)0) #define cg_reinit() ((void)0) #define syn_dtorinit(b) 0 #define syn_dtorfinal(b) 0 #define generate_core_part(b, c) 0 #define is_declaration(n) 0 #define is_type_id() 0 #define rd_declrhs_exec_cpp(d, initflag) 0 #define conditionalised_delete(t, d, p) 0 #define xsyn_init() ((void)0) #define add_memfn_template(a,b,c,d,e,f,g,h,i) ((void)0) #define inst_template_begin(a,b) ((void)0) #define inst_template_end() ((void)0) #define syn_implicit_instantiate(a,b) ((void)0) #define save_pendingfns(a) ((void)0) #define restore_pendingfns(a) ((void)0) #define save_curfn_misc(a) ((void)0) #define restore_curfn_misc(a) ((void)0) #define rd_exception_spec() ((void)0) #endif /* _SYN_H */ #ifdef TARGET_HAS_INLINE_ASSEMBLER # include "inlnasm.h" #endif struct SynScope { struct SynScope *cdr; SynBindList *car; int32 scopeid; }; #define mkSynScope(a,b,c) (SynScope *)syn_list3(a,b,c) #define discardSynScope(p) discard3(p) struct SynGoto { struct SynGoto *cdr; Cmd *gotocmd; SynScope *gotoscope; }; #define mkSynGoto(a,b,c) (SynGoto *)syn_list3(a,b,c) enum blk_flavour { blk_BODY, /* for rd_block(function body) */ blk_INNER, /* for rd_block(inner block) */ blk_IMPLICIT, /* for rd_block(C++ decl) */ blk_STMTSEQ, /* for Cfront compatibilty */ blk_SSTMT }; /* for Cfront compatibility */ /* The next line is in flux, but flags code which is invented, and */ /* does not correspond to a user written action. E.g. narrowing in */ /* f(x) float x; {...}. Note that x = 1 in { int x = 1; is not so. */ static FileLine syn_invented_fl = { 0, 0, 0 }; /* Code may test for invented FileLines by testing (fl.f == 0)!!! */ static SynBindList *syn_reftemps; /* syn_reftemps is sort-of an extra item in synscope. */ static bool chk_for_auto = NO; #define syn_current_linkage() \ (syn_linkage == 0 ? LINK_CPP : syn_linkage->linkcar) typedef struct PendingFnList { struct PendingFnList *pfcdr; Symstr *pfname, *pfrealname; /* maybe a binder soon, see declarator_name */ TypeExpr *pftype; SET_BITMAP pfstg; /* MEMFNBITS */ TagBinder *pfscope; ScopeSaver pf_formaltags; int pf_toklist_handle; ScopeSaver pf_templateformals; bool pf_tfn; } PendingFnList; static PendingFnList *syn_pendingfns; typedef struct GenFnList { struct GenFnList *cdr; TopDecl *d; Mark* mark; } GenFnList; static GenFnList *syn_generatedfns; enum LinkSort { LINK_C, LINK_CPP }; typedef struct Linkage { struct Linkage *linkcdr; enum LinkSort linkcar; } Linkage; static Linkage *syn_linkage, *syn_linkage_free; typedef struct FuncMisc { Cmd *switchcmd; SynScope *loopscope, *switchscope; AEop kaerb; TypeExpr *resttype, *switchtype; bool is_ctor, is_dtor; Binder *structresult; CurrentFnDetails curfndetails; LabBind *labels; LabBind *labsyms[MAX_SAVED_LABELS]; int recurse; } FuncMisc; #ifdef CPLUSPLUS static enum LinkSort linkage_of_string(String *s); static void save_pendingfns(PendingFnList **old_pendingfns); static void restore_pendingfns(PendingFnList *old_pendingfns); static void save_curfn_misc(FuncMisc *tmp); static void restore_curfn_misc(FuncMisc *tmp); #else static enum LinkSort linkage_of_string(String *s) { IGNORE(s); return LINK_C; } #endif /* forward references within this file - reorganise to reduce */ static void ensure_formals_typed(DeclRhsList *d,bool proto); static TypeExpr *rd_typename(int declflag); static Expr *rd_prefixexp(int n); #ifdef EXTENSION_VALOF static Cmd *rd_block(enum blk_flavour f, bool real_block); #endif static Cmd *rd_command(bool declposs); static DeclRhsList *rd_decllist(int declflag); static void rd_enumdecl(TagBinder *tb); static void rd_classdecl_(TagBinder *tb); static DeclRhsList *rd_decl2(int, SET_BITMAP); /* newer comments... * 2. (7-apr-86 further change): * Extra field (a BindList) of formal params added to s_fndef * (think of as like lambda). It has s_binder entries. * 3. Diads (incl fnap) and monads have a type field type_() at offset 1. * Use arg1_ and arg2_ to get args. * 1. declarators are now turned into type expressions a la Algol68. * 3. sizeof is turned into an integer constant by the parser. * s_integer has therefore a intorig_() node showing the original * expression for error messages (e.g. "sizeof(int) = 9;") */ /* some general comments... 0. AE tree nodes have an h0_() field specifying which AEop (small int) they contain and then several pointers representing subtrees. 1. list types in general (like actual parameters, block declarations block commands) are stored without tag fields, in the usual lisp form. Use cdr_() = h0_() for CDR. 0 denotes the end. They are read using tail pointers to avoid excess recursion. 2. Missing, or empty expressions or commands are stored as 0. E.g. "for (;;)" or "if e then c;". Note that the empty statement ";" is also stored as 0 and hence "if e then c else;" is indistiguishable from the above. 3. Note the curious format of string constants - for ANSI implicit string constant concatenation - we have a string node has a pointer to a LIST of string elements. 4. Note that labelled statements require 1 symbol of lookahead to distinguish them from expression statements. See POSSLABEL uses below. 5. The allocators list1, ..., list6 create the parse tree. Moreover no permanent structure is allocated in them so that the allocator free pointer can be reset after reading and code-generating each top-level phrase. */ bool implicit_return_ok; #define tagparent_(p) ((p)->tagparent) /* The values for 'declflag' below (with the exception of DUPL_OK which */ /* may be or'ed in) are private to parsing. They represent CONTEXTS */ /* (e.g. FORMAL) for declarators, abstract declarators, typenames, etc. */ /* The values are 'sparse' to allow quick testing for membership of */ /* sets like CONC_DECLARATOR. */ /* #define DUPL_OK 0x001 */ /* defined in bind.h */ /* #define TOPLEVEL 0x002 */ /* defined in bind.h */ /* #define GLOBALSTG 0x004 */ /* defined in bind.h */ #define MEMBER 0x008 /* i.e. in struct/union */ #define BLOCKHEAD 0x010 #define ARG_TYPES 0x020 /* declaring formals, after e.g. 'f(x)' */ #define FORMAL 0x040 /* inside ()'s: both (int a) and (a) OK. */ #define TYPENAME 0x080 /* i.e. typename for case/sizeof. */ #define SIMPLETYPE 0x100 /* C++ casts like "int(3)" etc. */ #define CONVERSIONTYPE 0x200 /* C++ "operator int * ();" */ #define NEW_TYPENAME 0x400 /* C++ new-type-name [ES]. */ #define FLEX_TYPENAME 0x800 /* C++ 'new' TYPENAME, [var] ok [ES]. */ /* #define TEMPLATE 0x1000 */ /* defined in bind.h */ #define CATCHER 0x2000 /* C++ 'catch' context. */ #define ANONU 0x4000 /* OR-able with MEMBER/BLOCKHEAD etc. */ #define TFORMAL 0x8000 /* template formal. */ /* contexts in which 'storage classes' are allowed (vestigial): */ /* [ES] seems to disallow "catch(register int x) { ... }". We don't. */ #define STGCLASS_OK (TOPLEVEL|BLOCKHEAD|FORMAL|ARG_TYPES|CATCHER) /* contexts in which a type is REQUIRED (typename and struct member): */ #define TYPE_NEEDED (LanguageIsCPlusPlus ?\ (TYPENAME|FLEX_TYPENAME|NEW_TYPENAME|CATCHER) :\ (TYPENAME|FLEX_TYPENAME|NEW_TYPENAME|MEMBER|CATCHER)) /* contexts in which declarators must be ABSTRACT or CONCRETE. */ #define CONC_DECLARATOR (TOPLEVEL|BLOCKHEAD|ARG_TYPES|MEMBER) #define ABS_DECLARATOR (TYPENAME|FLEX_TYPENAME|NEW_TYPENAME) /* parsing table initialisation... */ static int32 illtypecombination[NUM_OF_TYPES]; static int bind_scope; /* TOPLEVEL, GLOBALSTG, or LOCALSCOPE */ static AEop access; /* Operator priority for rd_expr(): we use even priorities for */ /* left-associative operators and odd priorities for right-association. */ /* This means that we can get right-priority simply by or-ing one into */ /* the left-priority. */ /* Other things could added to lpriovec, such as 'needs lvalue' etc. */ static char lpriovec[s_NUMSYMS]; #define lprio_(op) lpriovec[op] #define rprio_(op) (lpriovec[op] | 1) /* <NAME> - Make it compile */ #ifdef CALLABLE_COMPILER Expr *rd_asm_decl(void) { return (Expr*) 0; /* Temporary - currently asm is implemented as a command rather then a declaration... */ } #endif static void initpriovec(void) { AEop s,t; AEop i; for (s = s_bool; istypestarter_(s); s++) illtypecombination[shiftoftype_(s)] = ~0; illtypecombination[shiftoftype_(s_signed)] = illtypecombination[shiftoftype_(s_unsigned)] = ~(bitoftype_(s_int) | bitoftype_(s_char) | bitoftype_(s_longlong) | bitoftype_(s_long) | bitoftype_(s_short) | CVBITS); illtypecombination[shiftoftype_(s_long)] = ~(bitoftype_(s_int) | bitoftype_(s_signed) | bitoftype_(s_unsigned) | bitoftype_(s_double) | bitoftype_(s_float) | CVBITS); if (!(feature & FEATURE_FUSSY)) { illtypecombination[shiftoftype_(s_long)] &= ~bitoftype_(s_long); illtypecombination[shiftoftype_(s_longlong)] = ~(bitoftype_(s_int) | bitoftype_(s_signed) | bitoftype_(s_unsigned) | CVBITS); } illtypecombination[shiftoftype_(s_short)] = ~(bitoftype_(s_int) | bitoftype_(s_signed) | bitoftype_(s_unsigned) | CVBITS); illtypecombination[shiftoftype_(s_const)] = bitoftype_(s_const); illtypecombination[shiftoftype_(s_volatile)] = bitoftype_(s_volatile); illtypecombination[shiftoftype_(s_unaligned)] = bitoftype_(s_unaligned) | bitoftype_(s_double) | bitoftype_(s_float); /* now symmetrise: */ for (s = s_bool; istypestarter_(s); s++) for (t = s_bool; istypestarter_(t); t++) if (!(illtypecombination[shiftoftype_(s)] & bitoftype_(t))) illtypecombination[shiftoftype_(t)] &= ~bitoftype_(s); for (i=0; i<s_NUMSYMS; i++) lpriovec[i] = (isassignop_(i) ? 13 : 0); lpriovec[s_comma] = 10; lpriovec[s_assign] = 13; lpriovec[s_cond] = 15; lpriovec[s_oror] = 16; lpriovec[s_andand] = 18; lpriovec[s_or] = 20; lpriovec[s_xor] = 22; lpriovec[s_and] = 24; lpriovec[s_equalequal] = lpriovec[s_notequal] = 26; lpriovec[s_less] = lpriovec[s_greater] = lpriovec[s_lessequal] = lpriovec[s_greaterequal] = 28; lpriovec[s_leftshift] = lpriovec[s_rightshift] = 30; lpriovec[s_plus] = lpriovec[s_minus] = 32; lpriovec[s_times] = lpriovec[s_div] = lpriovec[s_rem] = 34; lpriovec[s_dotstar] = lpriovec[s_arrowstar] = 36; } /* check_bitsize and check_bittype get prunetype'd types. */ static Expr *check_bitsize(Expr *e, TypeExpr *t, Symstr *sv) { uint32 n = evaluate(e); uint32 size = MAXBITSIZE; /* * In C++/PCC mode bit fields may be 'char', 'short', 'long' or 'enum'. * In ANSI mode bit fields must (else undefined) be 'int'. */ if (h0_(t) == s_typespec) { if (typespecmap_(t) & bitoftype_(s_char)) size = 8; else if (int_islonglong_(typespecmap_(t))) size = 8*sizeof_longlong; else if (typespecmap_(t) & bitoftype_(s_short)) size = 8*sizeof_short; else if (typespecmap_(t) & bitoftype_(s_long)) size = 8*sizeof_long; /* else treat enum as 'int'. */ /* @@@ Sept 91: we should check enum range against bit size, */ /* and even add signedness info to ensure happyness! */ } if (n > size /* unsigned! */) cc_err(syn_err_bitsize, (long)n); else if (n==0 && sv!=NULL) n = (uint32)-1, cc_err(syn_err_zerobitsize); if (n > size || h0_(e) != s_integer) e = globalize_int(1); return e; } /* check_bitsize and check_bittype get prunetype'd types. */ static TypeExpr *check_bittype(TypeExpr *t) { /* In ANSI C, only int bitfields are allowed, C++ also allows * bool/char/short/long/enum (like PCC mode). * In PCC mode, it's important NOT to translate char and short * types to int, because they are packed differently. * Also C++ typechecking requires 'enum' not to be translated to int. * C++: wchar_t is also allowed (when we support it) */ #define OKbittypes (bitoftype_(s_int)|bitoftype_(s_bool)| \ bitoftype_(s_char)|bitoftype_(s_short)| \ bitoftype_(s_enum)|bitoftype_(s_long)| \ bitoftype_(s_unsigned)|bitoftype_(s_signed)| \ bitoftype_(s_const)|bitoftype_(s_volatile)) if (h0_(t) != s_typespec || typespecmap_(t) & ~OKbittypes) { cc_err(syn_rerr_bitfield, t); t = te_int; } if (!(feature & FEATURE_CPP) && (typespecmap_(t) & (bitoftype_(s_char)|bitoftype_(s_short)| bitoftype_(s_enum)|bitoftype_(s_long)))) { if (feature & FEATURE_FUSSY) { cc_rerr(syn_rerr_ANSIbitfield, t); t = te_int; } else if (!(feature & FEATURE_PCC)) /* @@@ warn for any non-ANSI C bitfield type, but leave alone! */ cc_warn(syn_rerr_ANSIbitfield, t); } /* sem.c is responsible for the interpretation of 'plain' int bitfields */ /* as signed/unsigned (q.v. under FEATURE_SIGNED_CHAR). */ /* It is vital that 'BITFIELD' on the next line does not qualify a typedef. */ return primtype2_(typespecmap_(t) | BITFIELD, typespecbind_(t)); } static Expr *check_arraysize(Expr *e) { unsigned32 n; if (is_template_arg_binder(e)) return e; n = evaluate(e); if (n == 0 && !(suppress & D_ZEROARRAY)) cc_pccwarn(syn_rerr_array_0); /* The limit imposed here on array sizes is rather ARBITRARY, but char */ /* arrays that consume over 16Mbytes seem silly at least in 1988/89! */ if (n > 0xffffff) cc_err(syn_err_arraysize, (long)n); if (n > 0xffffff || h0_(e) != s_integer) e = globalize_int(1); return e; } static const char *ctxtofdeclflag(int f) { if (f & TOPLEVEL) return msg_lookup(errname_toplevel); if (f & MEMBER && !(f & TEMPLATE)) return msg_lookup(errname_structelement); if (f & TEMPLATE) { if (f & MEMBER) return msg_lookup(errname_membertemplate); else return msg_lookup(errname_classtemplate); } if (f & FORMAL) return msg_lookup(errname_formalarg); if (f & ARG_TYPES) return msg_lookup(errname_formaltype); if (f & BLOCKHEAD) return msg_lookup(errname_blockhead); if (f & TYPENAME) return msg_lookup(errname_typename); if (f & SIMPLETYPE) return msg_lookup(errname_simpletype) /* <simple type> */; if (f & CONVERSIONTYPE) return msg_lookup(errname_conversiontype) /* <conversion type> */; if (f & (FLEX_TYPENAME|NEW_TYPENAME)) return msg_lookup(errname_new_type_name) /* <new-type-name> */; if (f & CATCHER) return msg_lookup(errname_catch_name) /* <catch name> */; if (f & TFORMAL) return msg_lookup(errname_templateformal); return msg_lookup(errname_unknown); } AEop peepsym(void) { AEop s; nextsym(); s = curlex.sym; ungetsym(); return s; } void checkfor_ket(AEop s) { /* The next lines are a long-stop against loops in error recovery */ if (errs_on_this_sym >= 4) { cc_err(syn_err_expecteda, s); nextsym(); } else if (curlex.sym == s) nextsym(); else { cc_err(syn_err_expected, s); ++errs_on_this_sym; } } void checkfor_delimiter_ket(AEop s, msg_t expected1, msg_t expected1a) /* as checkfor_ket but less read-ahead */ { /* The next lines are a long-stop against loops in error recovery */ if (errs_on_this_sym >= 4) { cc_err(expected1a, s); nextsym(); } else if (curlex.sym == s) curlex.sym = s_nothing; else { cc_err(expected1, s); ++errs_on_this_sym; } } void checkfor_2ket(AEop s, AEop t) { /* The next lines are a long-stop against loops in error recovery */ if (errs_on_this_sym >= 4) { cc_err(syn_err_expected2a, s, t); nextsym(); } else if (curlex.sym == s) nextsym(); else { cc_rerr(syn_err_expected2, s, t, s); ++errs_on_this_sym; } } void checkfor_delimiter_2ket(AEop s, AEop t) { if (curlex.sym == s) curlex.sym = s_nothing; else checkfor_2ket(s, t); } /* now to get on with it. */ Expr *rd_ANSIstring(void) { AEop op = curlex.sym; /* s_string or s_wstring */ StringSegList *p,*q; /* Note that the list of string segments must last longer than most */ /* other parts of the parse tree, hence use binder_list3() here. */ q = p = (StringSegList *) binder_list3((StringSegList *)0, curlex.a1.s, curlex.a2.len); while (nextsym(), isstring_(curlex.sym)) if (curlex.sym == op) q = q->strsegcdr = (StringSegList *) binder_list3((StringSegList *)0, curlex.a1.s, curlex.a2.len); else cc_err(syn_err_mix_strings); return (Expr *)syn_list2(op, p); } static ExprList *rd_exprlist_opt(void) { ExprList *p = 0, *q = 0, *temp; if (curlex.sym != s_rpar) for (;;) { temp = mkExprList(0, rd_expr(UPTOCOMMA)); if (p == 0) p = q = temp; else cdr_(q) = temp, q = temp; if (curlex.sym != s_comma) break; nextsym(); } checkfor_2ket(s_rpar, s_comma); return p; } /* Notionally, rd_primary and rd_prefixexp should take no argument. However, it is most convenient to give it an argument 'labelhack' which we set to POSSLABEL to indicate statement contexts. In such contexts the possible expressions are 'label:' or <expression>. This is necessary to enable lookahead past s_identifier's in statement context to see if there is a colon, with represents a label, or an operator like '='. Consider "a:b=c;" or "a:b++;". Note that this must be done by rd_primary since labels and variables have different environments. Doing this re-entrantly is important since "#if..." happens rather asynchronously. */ #define NOLABEL PASTCOMMA /* for clarity */ #define POSSLABEL (PASTCOMMA-2) /* lower (= same) priority as PASTCOMMA */ /* SynScope duplicates some of the functionality in bind.c, but */ /* currently it is simpler to use an alternative structure. */ static SynScope *synscope; static int32 synscopeid; static bool elselast; /* private to rd_command(), cleared by valof. */ static Cmd *cur_switchcmd; static SynScope *cur_loopscope, *cur_switchscope; static AEop cur_break; /* what 'break' means i.e. s_break or s_endcase */ static TypeExpr *cur_restype, *cur_switchtype; static bool cur_fn_is_ctor, cur_fn_is_dtor; static Binder *cur_structresult; /* non-NULL if struct fn. */ #ifdef EXTENSION_VALOF static TypeExpr *valof_block_result_type; #endif ClassMember *curlex_member; /* The currently found member. @@@ Think: declared in bind.h... */ static TagBinder *curlex_scope; /* Valid if (curlex.sym & s_qualified); curlex_scope is the scope */ /* named by the last nested-name-specifier read; 0 means global. */ static Binder *curlex_binder; /* Non-0 if the named entity read is a bound entity. Set in C too. */ static Binder *curlex_typename; /* Non-0 if curlex_binder binds a type name; set in C too. */ static TypeExpr *curlex_optype; /* Valid when the post-condition (curlex.sym == s_pseudoid) holds. */ /* Non-0 when the named entity is a conversion-type-name (C++). */ static Expr *curlex_path; /* Non-0 if the name names a class data member (C struct member); */ /* it is an expr locating the member relative to the object's base. */ static TagBinder *syn_class_scope; static BindList *cur_template_formals; static ExprList **cur_template_actuals; static void rd_c_name(TagBinder *leftScope, int typenameflag) { if (curlex.sym != s_identifier) return; curlex_scope = 0; curlex_binder = curlex_typename = 0; /* NB: leftScope != 0 means "only in leftScope"... */ curlex_path = findpath(curlex.a1.sv, leftScope, typenameflag|FB_LOCALS|FB_GLOBAL, 0); if (leftScope != 0) { if (curlex_path == 0 || h0_(curlex_path) != s_dot) { cc_err(syn_err_not_found_named_member, curlex.a1.sv, leftScope); curlex_path = errornode; } return; } if (curlex_path != 0 && h0_(curlex_path) == s_binder) { curlex_binder = exb_(curlex_path); curlex_path = 0; } /* don't recognise typedefs in #if even if extension "keywords in #if"! */ if (pp_inhashif) return; if (curlex_binder != 0 && (bindstg_(curlex_binder) & bitofstg_(s_typedef))) curlex_typename = curlex_binder; } static void rd_dname(void) { if (LanguageIsCPlusPlus) rd_cpp_name(&DNAME); /* NO access checks hack... */ else rd_c_name(0, 0); } static void rd_name(TagBinder *leftScope) { if (LanguageIsCPlusPlus) rd_cpp_name(leftScope); else rd_c_name(leftScope, 0); } static void rd_type_name(void) { if (LanguageIsCPlusPlus) rd_cpp_name(0); else rd_c_name(0, FB_TYPENAME); } static bool isexprstarter(AEop op) /* implement as macro using bool array? */ { switch (op & ~s_qualified) { default: return 0; case s_lpar: /* primary expression starters */ case_s_any_string case s_integer: case s_true: case s_false: case s_floatcon: case s_int64con: case s_identifier: case s_pseudoid: /* rd_cpp_name() swallowed s_coloncolon and s_operator. */ case s_this: case s_new: case s_delete: case s_throw: case s_const_cast: case s_reinterpret_cast: case s_static_cast: case s_dynamic_cast: case s_typeid: case s_and: /* prefix expression starters */ case s_times: case s_plus: case s_minus: case s_plusplus: case s_minusminus: case s_bitnot: case s_boolnot: case s_sizeof: return 1; } } /* Calling rd_type_name() must always precede isdeclstarter2_(). */ #define isdeclstarter2_(curlex) \ (isdeclstarter_(curlex.sym) || \ (curlex.sym & ~s_qualified) == s_identifier && curlex_typename != 0) /* Ditto for isdeclstarter3_() which is currently rather a placeholder. */ #define isdeclstarter3_(curlex) \ ((isdeclstarter2_(curlex) && (!LanguageIsCPlusPlus || is_declaration(PASTCOMMA))) || \ (curlex.sym == s_asm && peepsym() == s_lpar) || curlex.sym == s_template) static Expr *mkunaryorop(AEop op, Expr *a) { if (h0_(a) == s_error) return errornode; /* @@@ correct placing? */ return LanguageIsCPlusPlus ? cpp_mkunaryorop(op, a) : mkunary(op, a); } static Expr *mkbinaryorop(AEop op, Expr *a, Expr *b) { if (h0_(a) == s_error || h0_(b) == s_error) return errornode; return LanguageIsCPlusPlus ? cpp_mkbinaryorop(op, a, b) : mkbinary(op, a, b); } static Expr *mkfnaporop(Expr *e, ExprList *l) /* Here I have special processing for a pseudo-function-call to * ___assert(bool, string) which (at this very early stage) is turned into * (void)0, but if the boolean is not a compile time nonzero constant * the string is used to generate a diagnostic. * Feb 93: for va_arg a ___cond(a,b,c) and ___fail(string) could be more * useful separated. */ { if (h0_(e) == s_binder && bindsym_(exb_(e)) == assertsym) { Expr *a1, *a2; ExprList *ll = l; if (ll != NULL) { a1 = optimise0(exprcar_(ll)); ll = cdr_(ll); if (ll != NULL) a2 = optimise0(exprcar_(ll)); else a2 = 0; } else a1 = a2 = 0; if (a1 == 0 || h0_(a1) != s_integer || intval_(a1) == 0) cc_err(syn_err_assertion, a2); /* map the assert() into (void)0 */ return mkcast(s_cast, mkintconst(te_int, 0, e), te_void); } if (h0_(e) == s_error) return errornode; return LanguageIsCPlusPlus ? cpp_mkfnaporop(e, l) : mkfnap(e,l); } #define is_globalbinder_(b) (bind_global_(bindsym_(b)) == b) static Expr *rd_idexpr(int labelhack) /* @@@ merge in operator/::operator? */ { Expr *a; Binder *b; Symstr *sv; /* @@@ surely we can do better than the following! stop S::* here too. */ if ((curlex.sym & ~s_qualified) != s_identifier) syserr("rd_idexpr"); sv = curlex.a1.sv; if (labelhack == POSSLABEL && curlex.sym == s_identifier && peepsym() == s_colon) { nextsym(); /* Here curlex.sym==s_colon so postfix forms won't be considered. */ return (Expr *)syn_list2(s_colon, sv); } if ((b = curlex_binder) == NULL && curlex_path == NULL) { AEop peek = peepsym(); if (!has_template_arg_scope()) { if (peek == s_lpar) { if (LanguageIsCPlusPlus) cc_rerr(syn_rerr_undeclared_fn, symname_(sv)); else if (warn_implicit_fns) cc_warn(syn_warn_invent_extern, symname_(sv)); else xwarncount++; } else cc_rerr(syn_rerr_undeclared, symname_(sv)); } a = (Expr *) (b = curlex_binder = implicit_decl(sv, peek==s_lpar)); } else if ((a = curlex_path) != 0 && curlex_binder != 0) /* exprdotmemfn - a is already in usable form */; else if (a != 0) { if (a == errornode) {nextsym(); return a;} /* Ordinary data member access... */ /* In C++, &A::a may be valid even when x = A::a isn't, hence */ /* defer any test for 'this' until we know the context, i.e. in */ /* coerceunary() etc. For non-qualified names there is no such */ /* problem. See [ES, p55]. Note also that in C, curlex.sym */ /* cannot have s_qualified set. */ if (curlex.sym & s_qualified) { /* We ignore the class prefix because of [ES,p55,note1]. */ /* @@@ note the potential user disaster in that &D::i has type */ /* (int B::*), not (int D::*). This will cause pain as unchecked */ /* parameters, else implicit casts will save us. */ if (h0_(a) != s_dot) syserr("rd_idexpr(non-dot data member access)"); /* LDS 06-Sep-94: Smash unshared tree in place - sorry... */ /* NB - arg1_(a) is now guaranteed to exist by path_to_member_1() which */ /* initialises it to nullbinder(class)... rooted_path() also recognises.*/ type_(a) = (TypeExpr *)syn_list3(t_coloncolon, type_(a), typespectagbind_(princtype(typeofexpr(arg1_(a))))); } else /* arguably we should defer this (for sizeof). */ a = thisify(a); } else if (bindstg_(b) & bitofstg_(s_typedef)) { if (LanguageIsCPlusPlus && (a = rd_cppcast()) != 0) return a; cc_err(syn_err_typedef, sv); a = errornode; } else if (isenumconst_(b)) /* Map enum const binders to values. */ /* @@@ move this code to coerceunary with C++ bindconst? */ a = mkintconst(bindtype_(b),bindaddr_(b),(Expr *)b); else { /* use current 'variable' binding */ if (bindstg_(b) & b_pseudonym) b = realbinder_(b); a = (Expr *)b; binduses_(b) |= u_referenced; if (chk_for_auto && !is_local_binder(b) && !is_template_arg_binder((Expr *)b) && !is_globalbinder_(b) && !(bindstg_(b) & bitofstg_(s_static)) && !(bindstg_(b) & bitofstg_(s_extern)) && (h0_(bindtype_(b)) != t_ovld)) { cc_err(syn_rerr_local_default, b); a = errornode; } } nextsym(); return a; } /* rd_primary is called with rd_name having been called */ /* on curlex.sym. (In rd_prefixexp() if not earlier.) */ static Expr *rd_primaryexp(int labelhack) { Expr *a; switch (curlex.sym & ~s_qualified) { defaultcase: default: /* rd_idexpr() parses C++ casts/constructors fns via typedef. */ if (LanguageIsCPlusPlus && isdeclstarter_(curlex.sym) && (a = rd_cppcast()) != 0) return a; cc_err(syn_err_expected_expr); return errornode; case s_lpar: nextsym(); rd_type_name(); if (isdeclstarter2_(curlex) && /* rd_declspec(stgclass) moans */ (!LanguageIsCPlusPlus || is_type_id())) { TypeExpr *t; /* The next line supports a keyword "__type" which is treated */ /* almost as whitespace here, but which is used by a few macros as a */ /* clue to the parser that certain parenthesised expressions are casts */ /* and not just arithmetic. This (only) aids error recovery. */ if (curlex.sym == s_typestartsym) nextsym(); /* if (LanguageIsCPlusPlus) { if ((a = rd_cppcast()) != 0) { checkfor_ket(s_rpar); return a; } } */ t = rd_typename(TYPENAME); checkfor_ket(s_rpar); #ifdef EXTENSION_VALOF /* invalidate syntactically top level "int a = (int){...};" */ if (curlex.sym == s_lbrace && cur_restype) { Cmd *c; TypeExpr *saver = valof_block_result_type; if ((suppress & D_VALOFBLOCKS) == 0) cc_err(syn_err_valof_block); /* Set a flag so that 'resultis' is recognized as such */ if (equivtype(t, te_void)) { cc_rerr(syn_rerr_void_valof); t = te_int; /* Fixup to be type int */ } inside_valof_block++; valof_block_result_type = t; c = rd_block(blk_INNER, YES); elselast = 0; inside_valof_block--; valof_block_result_type = saver; nextsym(); return mk_expr_valof(s_valof, t, c); } else #endif return mkcast(s_cast, rd_prefixexp(NOLABEL), t); } a = rd_expr(PASTCOMMA); checkfor_ket(s_rpar); break; case_s_any_string /* cope with ANSI juxtaposed concatenation */ a = rd_ANSIstring(); break; #ifdef CPLUSPLUS case s_this: if (!LanguageIsCPlusPlus) goto defaultcase; { Binder *b = findbinding(thissym, NULL, LOCALSCOPES); a = (b && h0_(b) == s_binder) ? (binduses_(b) |= u_referenced, (Expr *)b) : (cc_err(syn_err_ill_this), errornode); nextsym(); return a; } case s_const_cast: case s_dynamic_cast: case s_reinterpret_cast: case s_static_cast: if (!LanguageIsCPlusPlus) goto defaultcase; { /* Temporary implementation accepting correct syntax but with * incorrect behaviour: transmute into vanilla cast. A warning that * the behaviour may be incorrect will have already been given. * AC 970416. */ TypeExpr *t; nextsym(); checkfor_ket(s_less); t = rd_typename(TYPENAME); checkfor_ket(s_greater); checkfor_ket(s_lpar); a = rd_expr(PASTCOMMA); checkfor_ket(s_rpar); return mkcast(s_cast, a, t); } case s_typeid: /* Temporary implementation accepting correct syntax but with * incorrect behaviour. A warning that the behaviour may be incorrect will * have already been given. AC 970417. * Get the type of the argument, check the type_info class has a constructor * (if not, probably forgot to include the header file), and call it on the * type name. Use of exception_name here to get the type name is gross and * should be tidied up when typeid is implemented properly. */ if (!LanguageIsCPlusPlus) goto defaultcase; { TypeExpr *t; Symstr *sv; Binder *b; nextsym(); checkfor_ket(s_lpar); rd_type_name(); if (isdeclstarter2_(curlex)) { t = rd_typename(TYPENAME); } else { t = typeofexpr(rd_expr(PASTCOMMA)); } checkfor_ket(s_rpar); /* Find constructor */ sv = sym_lookup("type_info", SYM_GLOBAL); b = findbinding(sv, NULL, ALLSCOPES); if (b == NULL || h0_(b) != s_binder || (bindstg_(b) & bitofstg_(s_typedef)) == 0 || !isclasstype_(princtype(bindtype_(b)))) { cc_err(syn_err_classname_not_found, sv); return errornode; } return mkctor_t(bindtype_(b), mkExprList(0, (Expr *)exception_name(t))); } #endif case s_pseudoid: if (!LanguageIsCPlusPlus) goto defaultcase; a = (Expr *)curlex_binder; if (a == 0) syserr("binder of name $r == 0", curlex.a1.sv); nextsym(); return a; case s_identifier: if (pp_inhashif) { /* the following warning is a good idea - consider: enum foo { a,b }; #if a==b ... */ cc_warn(syn_warn_hashif_undef, symname_(curlex.a1.sv)); /* @@@ - LDS 11-Nov-92: why the @@@? */ nextsym(); a = lit_zero; } else a = rd_idexpr(labelhack); break; case s_floatcon: a = (Expr *)curlex.a1.fc; nextsym(); break; case s_int64con: a = (Expr *)curlex.a1.i64; nextsym(); break; case s_true: case s_false: a = ((curlex.sym & ~s_qualified) == s_true) ? lit_true : lit_false; nextsym(); break; case s_integer: /* invent some more te_xxx for the next line? */ a = mkintconst((curlex.a2.flag == bitoftype_(s_int) ? te_int : primtype_(curlex.a2.flag)), curlex.a1.i, 0); nextsym(); break; } return a; } static Expr *rd_postfix(Expr *a) { AEop op; for (;;) switch (op = curlex.sym) { default: #ifdef CPLUSPLUS rootOfPath = NULL; #endif return a; case s_plusplus: case s_minusminus: nextsym(); a = mkunaryorop(postop_(op), a); break; case s_lpar: nextsym(); a = mkfnaporop(a, rd_exprlist_opt()); break; case s_lbracket: nextsym(); a = mkbinaryorop(s_subscript, a, rd_expr(PASTCOMMA)); checkfor_ket(s_rbracket); break; case s_arrow: if (LanguageIsCPlusPlus) a = mkunaryorop(s_arrow, a); /* drop through */ case s_dot: nextsym(); { TypeExpr *t = princtype(typeofexpr(a)); TypeExpr *tt = h0_(t) == t_ref ? princtype(typearg_(t)) : h0_(t) == t_content ? princtype(typearg_(t)) : t; TagBinder *scope = isclasstype_(tt) ? typespectagbind_(tt) : 0; bool istemplate = (curlex.sym == s_template); if (istemplate) nextsym(); if (scope && !(tagbindbits_(scope) & TB_DEFD) && tagprimary_(scope) != NULL) syn_implicit_instantiate(tagprimary_(scope), scope); rd_name(scope); if ((curlex.sym & ~s_qualified) == s_identifier || (curlex.sym & ~s_qualified) == s_pseudoid) { if (curlex_path == errornode) /* C/C++ error already diagnosed... */ a = errornode; else if (scope == 0) /* diagnose a field selection error */ a = mkfieldselector(op, a, (ClassMember *)curlex.a1.sv); else if (LanguageIsCPlusPlus && curlex_path == 0) { if (curlex_binder != 0 && curlex_typename == 0) /* static member or enumerator binder */ { Expr *tmp; if (isenumconst_(curlex_binder)) tmp = mkintconst(bindtype_(curlex_binder), bindaddr_(curlex_binder),(Expr *)curlex_binder); else tmp = (Expr *)curlex_binder; /* retain prefix expr for side-effect; relies on dead-code elimination otherwise */ a = mkbinary(s_comma, a, tmp); } else { if (!is_dependent_type(t)) cc_err(syn_err_not_member, scope); a = errornode; } } else { if (istemplate && curlex_binder != NULL && h0_(bindtype_(curlex_binder)) == t_ovld) { if (bindftlist_(curlex_binder) == NULL) cc_err(syn_err_template_member); else rd_template_postfix(NULL, YES); } a = mkfieldselector(op, a, (ClassMember *)curlex_path); } nextsym(); } else { if (curlex_path != errornode) cc_err(syn_err_expected_member); /* C/C++ error diagnosed by rd_*_name() or above */ a = errornode; } } break; } } static int32 codeoftype(TypeExpr *x) /* * This concocts an integer to return as the value of ___typeof(xx) * where ___typeof can be used wherever sizeof can. The objective is to make * it possible to (mostly) stdarg.h to make more checks and tests to * spot errors and generate code that depends in fine ways on the types * of objects. The coding used here at present is NO GOOD, and needs to be * thought out... I rather suspect that the best fixup here is to hand * back a type descriptor as defined for use with coff. */ { x = prunetype(x); switch (h0_(x)) { case s_typespec: { SET_BITMAP m = typespecmap_(x); /* Some code here to preserve the magic numbers in <stdarg.h> */ /* Must be maintained if more type bits are added to aeops.h */ /* Map bool to int */ /*/* char might be better since this is used to detect illegal types to va_arg */ if (m & bitoftype_(s_bool)) m ^= (bitoftype_(s_int)|bitoftype_(s_bool)); /* map long long to long */ if ((m & ts_longlong) == ts_longlong) m = (m ^ ts_longlong) | bitoftype_(s_long) | bitoftype_(s_int); /* Note the following must be done from highest numbered bit */ /* down */ /* Remove longlong's bit from the bitmap */ m = (m & (bitoftype_(s_longlong)-1)) | (m & -bitoftype_(s_longlong+1)) >> 1; /* map class to struct, and remove its bit from the bitmap */ m = (m & (bitoftype_(s_class)-1)) | (m & -bitoftype_(s_class)) >> 1; return m >> 1; /* Preserve pre-bool numbering */ } case t_ref: case t_content: case t_subscript: return 0x10000000; case t_fnap: return 0x20000000; default: syserr(syserr_codeoftype); return 0x40000000; } } static int32 cpp_sizeoftype(TypeExpr *t) { t = princtype(t); /* elide typedef's maybe losing qualifiers. */ /* There are no refs of refs, but the following code looks neater.. */ while (h0_(t) == t_ref) t = princtype(typearg_(t)); return sizeoftype(t); } static Expr *expr_dtors; static Expr *rd_prefixexp(int labelhack) { AEop op; Expr *a; /* Jul-94: The following rd_name(0) <is> now needed in C <and> C++. */ /* Its placement is curious, but it's a no-op for all but a few values */ /* of curlex.sym (in C, curlex.sym == s_identifier). */ rd_name(0); /* Note ::new and ::delete are valid, but neither S::* nor S::~. */ switch (op = curlex.sym) { case s_plus: if (feature & FEATURE_PCC) cc_warn(syn_warn_unary_plus); case s_and: case s_times: /* N.B. not s_qualified+s_times. */ case s_minus: op = unaryop_(op); /* drop through */ case s_plusplus: case s_minusminus: case s_bitnot: case s_boolnot: nextsym(); return mkunaryorop(op, rd_prefixexp(NOLABEL)); case s_typeof: /* ncc extension keyword */ case s_sizeof: nextsym(); /* N.B. Ansi require sizeof to return an unsigned integer type */ if (curlex.sym == s_lpar) { nextsym(); rd_type_name(); if (isdeclstarter2_(curlex)) /* rd_declspec(stgclass) moans */ { TypeExpr *t; if (curlex.sym == s_typestartsym) nextsym(); t = rd_typename(TYPENAME); checkfor_ket(s_rpar); return mkintconst( te_size_t, op == s_sizeof ? cpp_sizeoftype(t) : codeoftype(t), (Expr *)syn_list2(op == s_sizeof ? s_sizeoftype : s_typeoftype, t)); } a = rd_expr(PASTCOMMA); checkfor_ket(s_rpar); a = rd_postfix(a); /* for sizeof (f)() etc */ } else a = rd_prefixexp(NOLABEL); return mkintconst( te_size_t, op == s_sizeof ? expr_dtors = NULL, cpp_sizeoftype(typeofexpr(a)) : codeoftype(typeofexpr(a)), (Expr *)syn_list2(op == s_sizeof ? s_sizeofexpr : s_typeofexpr, a)); case s_new: case s_qualified+s_new: case s_delete: case s_qualified+s_delete: case s_throw: if (LanguageIsCPlusPlus) return rd_cpp_prefixextra(op); default: return rd_postfix(rd_primaryexp(labelhack)); } } /* AM still needs to be convinced of the worthiness of this (as it */ /* significantly obscures the code). */ /* After all, perhaps we should ensure that each tree expr node has */ /* room for an FileLine field? */ /* Sorry: fait accompli by ARM. Revision needs preservation of function.*/ /* We could approve a FileLine field in each node - AM talk to LDS/HCM).*/ #ifndef AM_DISLIKES static Expr *addfilelinetoexpr_i(Expr *e, FileLine *fl) { if (e != NULL && hasfileline_(h0_(e))) { FileLine *flp = (FileLine *)SynAlloc(sizeof(FileLine)); *flp = *fl; /* clone the expr if it's one of our shared literals */ if (h0_(e) == s_integer && ((e == lit_zero || e == lit_one || e == lit_true || e == lit_false))) e = mkintconst(type_(e), intval_(e), intorig_(e)); exprfileline_(e) = flp; } return e; } #else # define addfilelinetoexpr_i(e,fl) (e) #endif static Expr *addfilelinetoexpr(Expr *e, FileLine *fl) { return e == NULL ? e : addfilelinetoexpr_i(optimise0(e), fl); } static Expr *rd_exprwithfileline(int n, FileLine *fl) { fl->p = dbg_notefileline(*fl); { Expr *e = rd_expr(n); e = addfilelinetoexpr_i(e, fl); return e; } } static void NoteCurrentFileLine(FileLine *fl) { *fl = curlex.fl; fl->p = dbg_notefileline(*fl); } /* note: many calls to rd_expr() are followed by a checkfor_ket(s). */ /* It would be nice if rd_expr_ket() could check for these. */ /* (This would give syntactic "inserted s" messages BEFORE knock-on */ /* semantic errs. In the past we haven't done this because of */ /* getting wrong line numbers for semantic errors/read-ahead. */ /* Re-think this bit of the compiler. */ static SynBindList *extra_flags; Expr *rd_expr(int n) { AEop op; Expr *a = rd_prefixexp(n); /* see POSSLABEL */ Expr *edtor = NULL; /* note that the loop does not go round if op == s_colon after a label */ while (lprio_(op = curlex.sym) >= n) { FileLine fl; nextsym(); if (op == s_cond) { Expr *b, *c, *bdtor, *cdtor; NoteCurrentFileLine(&fl); push_exprtemp_scope(); b = rd_exprwithfileline(PASTCOMMA, &fl); bdtor = killexprtemp(); checkfor_ket(s_colon); NoteCurrentFileLine(&fl); push_exprtemp_scope(); c = rd_exprwithfileline( (LanguageIsCPlusPlus) ? rprio_(s_assign) : rprio_(s_cond), &fl); cdtor = killexprtemp(); if (bdtor || cdtor) { TypeExpr *t = typeofexpr(a); Binder *cond = gentempbinder(t); a = mk_exprlet(s_let, t, mkSynBindList(0, cond), mkbinary(s_comma, mkbinary(s_init, (Expr *)cond, a), (Expr *)cond)); if (!bdtor) bdtor = mkintconst(te_void, 0, 0); if (!cdtor) cdtor = mkintconst(te_void, 0, 0); add_expr_dtors(mkcond((Expr *)cond, bdtor, cdtor)); } a = mkcond(a, b, c); } else if (op == s_comma || op == s_andand || op == s_oror) { Expr *sub_edtor = NULL; NoteCurrentFileLine(&fl); if (LanguageIsCPlusPlus && op != s_comma) { Expr *b; push_exprtemp_scope(); b = rd_exprwithfileline(rprio_(op), &fl); if ((sub_edtor = killexprtemp()) != NULL) { Binder *flag = gentempbinder(te_int); sub_edtor = mkcond((Expr *)flag, sub_edtor, mkintconst(te_void, 0, 0)); extra_flags = mkSynBindList(extra_flags, flag); edtor = commacons(sub_edtor, edtor); a = mkbinaryorop(op, a, commacons( mkbinary(s_assign, (Expr *)flag, lit_one), b)); } else a = mkbinaryorop(op, a, b); } else a = mkbinaryorop(op, a, rd_exprwithfileline(rprio_(op), &fl)); } else /* ANSI C */ a = mkbinaryorop(op, a, rd_expr(rprio_(op))); } add_expr_dtors(edtor); return a; } /* The next routine is used by the preprocessor to parse #if and #elif. */ /* It relies on the caller (pp) to set pp_inhashif (see cfe/pp.h). */ bool syn_hashif() { /* note that we read the largest possible expression (rather that the ANSI "constant expression" syntax which excludes (top level only!!!) '+=', ',' etc. Then we can moan better at the semantic level. */ Expr *e; /* the next few lines are somewhat yukky. Think about how to improve */ nextsym_for_hashif(); /* precondition for rd_expr() is that curlex.sym is valid */ e = optimise0(rd_expr(PASTCOMMA)); if (curlex.sym != s_eol) { cc_err(curlex.sym == s_eof ? syn_err_hashif_eof : syn_err_hashif_junk); while (curlex.sym != s_eof && curlex.sym != s_eol) nextsym(); } if (e == 0 || h0_(e) != s_integer) { if (e != 0) moan_nonconst(e, syn_moan_hashif_nonconst, syn_moan_hashif_nonconst1, syn_moan_hashif_nonconst2); return 0; } return intval_(e) != 0; /* != 0 essential if int != long */ } static Expr *exprtemp_killer(Expr *orig) { Expr *killer; TypeExpr *t; Binder *tmp; if (!expr_dtors) return orig; if (extra_flags) { SynBindList *pbl = extra_flags; for (; pbl != NULL; pbl = pbl->bindlistcdr) orig = mkbinary(s_comma, mkbinary(s_init, (Expr *)pbl->bindlistcar, lit_zero), orig); } t = typeofexpr(orig); tmp = gentempbinder(t); killer = mkbinary(s_init, (Expr *)tmp, orig); killer = mkbinary(s_comma, killer, expr_dtors); killer = mkbinary(s_comma, killer, (Expr *)tmp); killer = mk_exprlet(s_let, t, mkSynBindList(extra_flags, tmp), killer); expr_dtors = NULL; extra_flags = NULL; return optimise0(killer); } static Expr *rd_condition(AEop op) { Expr *e; push_exprtemp_scope(); if (op == s_for) e = rd_expr(PASTCOMMA); else if (curlex.sym == s_lpar) { nextsym(); e = rd_expr(PASTCOMMA); checkfor_ket(s_rpar); } else { cc_rerr(syn_rerr_insert_parens, op); e = rd_expr(PASTCOMMA); } /* It is vital for s_switch that optimise0() is not called here. */ return op == s_switch ? mkintegral(op,e) : mktest(op,e); } static Expr *syn_allocexprtemps(Expr *e) { e = optimise0(e); if (e == 0) e = lit_zero; add_expr_dtors(killexprtemp()); return exprtemp_killer(e); } /* the next routine rd_init() has a coroutine-like linkage with vargen.c */ /* it would otherwise be a nice simple recursive routine! */ static int32 syn_initdepth; /* only used by these fns and rd_declrhslist */ static Expr *syn_initpeek; /* these are clearly stubs of nice recursive calls! */ int32 syn_begin_agg(void) { if (syn_initdepth < 0) return 0; if (curlex.sym == s_lbrace) { nextsym(); if (!LanguageIsCPlusPlus && (feature & FEATURE_FUSSY) && curlex.sym == s_rbrace) cc_rerr(syn_rerr_empty_init); syn_initdepth++; return 1; } return 0; } void syn_end_agg(int32 beganbrace) { if (beganbrace) { if (curlex.sym != s_rbrace) { Expr *result; switch (beganbrace) { case 1: cc_err(syn_err_initialisers); break; case 2: cc_err(syn_err_initialisers1); break; } /* * Skip the rest quitely ! * However, beware because if a symbol like ';' if found * we end up in a never ending loop. * Thus, if an error is found bail out !!! */ for ( result=syn_rdinit(0,0,4); result && result != errornode; result=syn_rdinit(0,0,4) ); } else if (beganbrace == 2) cc_warn(syn_warn_spurious_braces); nextsym(); if (--syn_initdepth > 0 && curlex.sym != s_rbrace) { checkfor_2ket(s_comma, s_rbrace); /* @@@ improve w.r.t e.g int */ if (curlex.sym == s_semicolon) /* probably badly lost... */ syn_initdepth = -1; } if (syn_initdepth == 0) syn_initdepth = -1; } } #define syn_initcast(e, whole, t) \ (whole ? mkbinary(s_init, (Expr *)whole, e) : \ t ? mkcast(s_assign, e, t) : \ e) Expr *syn_rdinit(TypeExpr *t, Binder *whole, int32 flag) /* t is a non-aggregate type - read its initialiser. */ /* flag values: 0 normal, 1 peek only (for string), 4 skip silently. */ /* if 'whole' is non-NULL then generate an assignment to it, */ /* else if 't' is non-NULL then just generate a cast to 't'. */ /* The case whole=0 & t=0 is used with flag=1 to test-read a RHS */ /* for char x[] = "abc"; and widestring variant only. */ /* See vargen.c for call rdinit(0,0,1) (=peek) then rdinit(0,0,0) for */ /* cases like struct { char a[4]; } = { 1 }; vs. = { "abc" }; */ { Expr *e; int needs_end_agg = NO; int static_init = flag & 8; flag &= ~8; if (syn_initpeek) { e = syn_initpeek; if (flag != 1) syn_initpeek = 0; } else if (syn_initdepth < 0 || curlex.sym == s_rbrace) return 0; else if (curlex.sym == s_lbrace) /* nasty ANSI optional "int x = {1}" */ { if (flag == 1) return 0; /* treat x[] = {"abc"} as illegal */ (void) syn_begin_agg(); /* always succeeds */ e = rd_expr(UPTOCOMMA); if (curlex.sym != s_rbrace) checkfor_2ket(s_comma, s_rbrace); /* @@@ improve w.r.t e.g int */ needs_end_agg = YES; } else { e = rd_expr(UPTOCOMMA); if (flag == 1) syn_initpeek = e; if (syn_initdepth > 0 && curlex.sym != s_rbrace) checkfor_2ket(s_comma, s_rbrace); /* @@@ improve w.r.t e.g int */ if (syn_initdepth == 0) syn_initdepth = -1; /* one only */ } #ifdef CPLUSPLUS if (h0_(e) == s_addrof && h0_(arg1_(e)) == s_binder && (bindsym_(curlex_binder) == ctorsym || bindsym_(curlex_binder) == dtorsym)) { cc_rerr(syn_rerr_addrof_cdtor_taken); e = errornode; } else #endif { e = syn_initcast(e, whole, t); if (!LanguageIsCPlusPlus && whole != NULL && static_init) { e = arg2_(skip_invisible(e)); } } if (needs_end_agg) syn_end_agg(flag == 4 ? 3 : 2); /* special flags */ return e; } bool syn_canrdinit(void) { if (syn_initpeek) return 1; if (syn_initdepth < 0 || curlex.sym == s_rbrace || curlex.sym == s_semicolon) return 0; /* * The next test is intended to make recovery from * int x[] = { int y; * and similar cases at least a little better. * This is OK in C but not C++: int a[] = { int(1),int(2)}; * Putting this in stops some infinite loops in error recovery, but * the parser still gets pretty well messed up by the example shown above. * AM, Sept 91: lets have another go at initialiser error recovery. */ if (!LanguageIsCPlusPlus) { rd_type_name(); if (isdeclstarter2_(curlex)) return 0; } return 1; } /* command reading routines... */ #if 0 static SynBindList *mkSynBindList_from_Decl(DeclRhsList *d, SynBindList *r) { /* re-use DeclRhsList store to make a (reversed) SynBindList... */ while (d != 0) { SynBindList *t = (SynBindList *)d; Binder *b = d->declbind; d = d->declcdr; t->bindlistcar = b; t->bindlistcdr = r; t->bindlistdtor = 0; r = t; } return r; } #endif static Cmd *rd_block(enum blk_flavour f, bool real_block) { DeclRhsList *d,*dp; CmdList *c = NULL; SynBindList *dd; int scope_level = 0; FileLine fl; NoteCurrentFileLine(&fl); push_saved_temps(synscopeid); if (real_block) nextsym(); /* skip '{' if nec. */ if (f == blk_INNER || f == blk_SSTMT) scope_level = push_scope(0, Scope_Ord); synscope = mkSynScope(synscope, 0, ++synscopeid); d = rd_decllist(BLOCKHEAD); if (LanguageIsCPlusPlus) { CmdList *cstat = 0; for (dp = d; dp != 0; dp = dp->declcdr) /* add dynamic inits */ { Expr *e = declinit_(dp); /* see genstaticparts() */ if (e != 0) { if (dp->declstg & bitofstg_(s_auto)) { if (cstat) { c = mkCmdList(c, syn_embed_if((CmdList *)dreverse((List *)cstat))); cstat = 0; } if (h0_(e) == s_asm) c = mkCmdList (c, e); else c = mkCmdList(c, mk_cmd_e(s_semicolon, dp->fileline, mkcast(s_init, e, te_void))); } else cstat = mkCmdList(cstat, mk_cmd_e(s_semicolon, dp->fileline, mkcast(s_init, e, te_void))); } } if (cstat) { c = mkCmdList(c, syn_embed_if((CmdList *)dreverse((List *)cstat))); cstat = 0; } } else for (dp = d; dp != 0; dp = dp->declcdr) /* add dynamic inits */ { Expr *e = declinit_(dp); /* see genstaticparts() */ if (e != 0) { if (h0_(e) == s_asm) c = mkCmdList (c, e); else c = mkCmdList(c, mk_cmd_e(s_semicolon, dp->fileline, mkcast(s_init, e, te_void))); } } /* Hmm, we would prefer genreftemp()s and DeclRhsList vars interleaved. */ /* FW: Done (in rd_decl2). Pity that no more reuse of declrhslist store. */ #if NEVER synscope->car = mkSynBindList_from_Decl(d, synscope->car); #endif while (curlex.sym != s_rbrace && curlex.sym != s_eof) { c = mkCmdList(c, rd_command(LanguageIsCPlusPlus != 0 && f != blk_SSTMT)); if (curlex.sym == s_nothing) nextsym(); } if (usrdbg(DBG_ANY) && real_block) { /* If generating debug tables, terminate the block with a null */ /* statement to provide a place for the FileLine for the */ /* terminating brace to be held */ FileLine fle; NoteCurrentFileLine(&fle); c = mkCmdList(c, mk_cmd_e(s_semicolon, fle, NULL)); } if (f != blk_IMPLICIT && f != blk_STMTSEQ) checkfor_delimiter_ket(s_rbrace, syn_err_expected1, syn_err_expected1a); if (f == blk_INNER || f == blk_SSTMT) pop_scope(scope_level); dd = synscope->car; synscope = synscope->cdr; if (LanguageIsCPlusPlus) { Expr *edtor = mkdtor_v_list(dd); if (edtor) { /* just what is the right FileLine for a dtor? */ c = mkCmdList(c, mk_cmd_e(s_semicolon, fl, optimise0(edtor))); } } dd = pop_saved_temps(dd); return mk_cmd_block(fl, reverse_SynBindList(dd), (CmdList *)dreverse((List *)c)); } /* NB - many commands are terminated by a semicolon - here (rd_command()) when I find the semicolon I set curlex.sym to s_nothing rather than reading ahead further. This reduces spurious read-ahead. */ /* Beware: the code for associating case labels with their enclosing */ /* 'switch' which follows assumes that no such labelled command is */ /* later thrown away by error recovery (else cg etc. will be unhappy). */ static Cmd *adddefault(FileLine fl) { if (cur_switchcmd == 0) { cc_err(syn_err_default); return 0; } if (switch_default_(cur_switchcmd)) { cc_err(syn_err_default1); return 0; } return (switch_default_(cur_switchcmd) = mk_cmd_default(fl, 0)); } static Cmd *addcase(Expr *e, FileLine fl) { Cmd *p,*q; int32 n; if (cur_switchcmd == 0) { cc_err(syn_err_case); return 0; } if (h0_(e) != s_integer) { moan_nonconst(e, syn_moan_case_nonconst, syn_moan_case_nonconst1, syn_moan_case_nonconst2); return 0; } n = intval_(e); /* the insertion sort code which follows is linear for increasing case expressions - it sorts into reverse (int) order (reverse later)? Anyway, ACN's CG code like them this way. */ for (p = switch_caselist_(cur_switchcmd), q=0; p!=0; q=p, p=case_next_(p)) { Expr *t = cmd1e_(p); if (debugging(DEBUG_SYN)) cc_msg("Comparing cases %ld %ld\n", (long)n, (long)intval_(t)); if (n >= intval_(t)) { if (n > intval_(t)) break; cc_err(syn_err_case1, (long)n); return 0; } } { Cmd *r = mk_cmd_case(fl, e, 0, p); if (q == 0) return switch_caselist_(cur_switchcmd) = r; else return case_next_(q) = r; } } /* rd_for_2() reads the last 2 parameters and the body of a for loop. */ /* It is so factored for C++'s for(d;e;e)c and for(e;e;e)c styles. */ static Cmd *rd_for_2(Expr *e1, FileLine fl) { Expr *e2, *e3; Cmd *c; if (curlex.sym == s_semicolon) e2 = 0; else { FileLine fl; NoteCurrentFileLine(&fl); e2 = addfilelinetoexpr(syn_allocexprtemps(rd_condition(s_for)), &fl); } checkfor_ket(s_semicolon); if (curlex.sym == s_rpar) e3 = 0; else { FileLine fl; NoteCurrentFileLine(&fl); push_exprtemp_scope(); e3 = mkcast(s_for,rd_expr(PASTCOMMA),te_void); add_expr_dtors(killexprtemp()); if (expr_dtors != 0) { e3 = mkbinary(s_comma, e3, expr_dtors); expr_dtors = NULL; } e3 = addfilelinetoexpr(e3, &fl); } checkfor_ket(s_rpar); { SynScope *oldloop = cur_loopscope; AEop oldbreak = cur_break; c = mk_cmd_for(fl, e1,e2,e3,0); cur_break = s_break; cur_loopscope = synscope; cmd4c_(c) = rd_command(0); cur_loopscope = oldloop; cur_break = oldbreak; return c; } } #define cfront_semantics ((feature & FEATURE_CFRONT) && \ !(var_cc_private_flags & 16777216L)) static Cmd *rd_command(bool declposs) { rd_type_name(); if (declposs && isdeclstarter3_(curlex)) return rd_block(blk_IMPLICIT, NO); { AEop op; Cmd *c; Expr *e; bool have_exprtemp_scope = false; FileLine fl; NoteCurrentFileLine(&fl); expr_dtors = NULL; extra_flags = NULL; switch (op = curlex.sym) { case s_default: nextsym(); checkfor_ket(s_colon); if ((c = adddefault(fl)) == 0) return rd_command(declposs); /* error */ /* The next line is currently just for errors as case/default branch */ /* can never cause destructors to happen. */ if (cmd_rescope(synscope, cur_switchscope, 0) != 0) syserr("rescope(case)"); cmd1c_(c) = rd_command(declposs); return c; case s_case: nextsym(); e = mkcast(s_case, rd_expr(PASTCOMMA), cur_switchtype); if (h0_(e) == s_evalerror) { cc_rerr((msg_t)arg3_(e), h0_(arg2_(e))); e = arg1_(e); } e = optimise0(e); checkfor_ket(s_colon); if (e==0 || (c = addcase(e,fl)) == 0) return rd_command(declposs); /* error */ /* The next line is currently just for errors as case/default branch */ /* can never cause destructors to happen. */ if (cmd_rescope(synscope, cur_switchscope, 0) != 0) syserr("rescope(case)"); cmd2c_(c) = rd_command(declposs); return c; defaultcase: default: if (!isexprstarter(op)) { cc_err(LanguageIsCPlusPlus ? syn_err_expected_stmt : syn_err_expected_cmd); while (curlex.sym!=s_lbrace && curlex.sym!=s_rbrace && curlex.sym!=s_semicolon && curlex.sym!=s_eof) nextsym(); return 0; } have_exprtemp_scope = true; push_exprtemp_scope(); e = rd_expr(POSSLABEL); if (h0_(e) == s_colon) { Symstr *a = (Symstr *)type_(e); LabBind *lab = label_define(a); nextsym(); /* not previously done */ pop_exprtemp_scope(); if (lab == 0) return rd_command(declposs); /* duplicate */ syn_setlab(lab, synscope); return mk_cmd_lab(s_colon, fl, lab, rd_command(declposs)); } /* @@@ perhaps we should check the ';' first */ e = optimise0(mkcast(s_semicolon, e, te_void)); c = (e==0) ? 0 : mk_cmd_e(s_semicolon, fl, e); break; case s_semicolon: c = 0; break; case s_lbrace: c = rd_block(blk_INNER, YES); elselast = 0; return c; case s_do: case s_while: case s_for: case s_if: case s_switch: curlex.sym |= s_qualified; /* FRIGORMA */ return rd_block((!declposs) ? blk_SSTMT : (cfront_semantics) ? blk_STMTSEQ : blk_INNER, NO); case s_do|s_qualified: nextsym(); { SynScope *oldloop = cur_loopscope; AEop oldbreak = cur_break; c = mk_cmd_do(fl, 0, 0); /* amalgamate with for */ cur_break = s_break; cur_loopscope = synscope; cmd1c_(c) = rd_command(0); cur_loopscope = oldloop; cur_break = oldbreak; } if (curlex.sym == s_nothing) nextsym(); if (curlex.sym == s_while) { FileLine fl; nextsym(); NoteCurrentFileLine(&fl); e = addfilelinetoexpr( syn_allocexprtemps(rd_condition(s_while)), &fl); } else { cc_err(syn_err_expected_while); e = 0; /* treat like "do c while;" (missing e). */ } if (e == 0) e = lit_zero; /* error => while(0). */ cmd2e_(c) = e; checkfor_ket(s_semicolon); if (!(declposs && cfront_semantics)) { if (curlex.sym != s_nothing) ungetsym(); curlex.sym = s_rbrace; } elselast = 0; return c; case s_while|s_qualified: nextsym(); { FileLine fl; NoteCurrentFileLine(&fl); /* Why does 'case s_while:' have a fileline but not case s_if:'? */ e = addfilelinetoexpr( syn_allocexprtemps(rd_condition(op & ~s_qualified)), &fl); } { SynScope *oldloop = cur_loopscope; AEop oldbreak = cur_break; c = mk_cmd_for(fl, 0, e, 0, 0); cur_break = s_break; cur_loopscope = synscope; cmd4c_(c) = rd_command(0); cur_loopscope = oldloop; cur_break = oldbreak; if (!(declposs && cfront_semantics)) { if (curlex.sym != s_nothing) ungetsym(); curlex.sym = s_rbrace; } return c; } case s_for|s_qualified: { Expr *edtor; nextsym(); checkfor_ket(s_lpar); push_exprtemp_scope(); if (LanguageIsCPlusPlus) { rd_type_name(); if (isdeclstarter2_(curlex)) { DeclRhsList *d = rd_decl2(BLOCKHEAD, 0), *dp; /* is BLOCKHEAD right? */ e = 0; for (dp = d; dp != 0; dp = dp->declcdr) /* add dynamic inits */ { Expr *einit = declinit_(dp); /* see genstaticparts() */ if (einit) { if (debugging(DEBUG_SYN)) cc_msg("[Init]"); e = e ? mkbinary(s_comma, e, einit) : einit; } } e = e ? optimise0(mkcast(s_for, e, te_void)) : 0; #if NEVER synscope->car = mkSynBindList_from_Decl(d, synscope->car); #endif if (curlex.sym == s_nothing) nextsym(); goto afterInit; } } e = ((curlex.sym == s_semicolon) ? 0 : optimise0(mkcast(s_for,rd_expr(PASTCOMMA),te_void))); checkfor_ket(s_semicolon); afterInit: if ((edtor = killexprtemp()) != 0) e = mkbinary(s_comma, e, edtor); c = rd_for_2(e, fl); if (!(declposs && cfront_semantics)) { if (curlex.sym != s_nothing) ungetsym(); curlex.sym = s_rbrace; } return c; } case s_if|s_qualified: { nextsym(); /* Why does 'case s_while:' have a fileline but not case s_if:'? */ e = syn_allocexprtemps(rd_condition(op & ~s_qualified)); if (e == 0) e = lit_zero; /* error => if(0). */ c = rd_command(0); if (curlex.sym == s_nothing) nextsym(); { Cmd *c2; static int elseline = 0; if (curlex.sym == s_else) { elseline = curlex.fl.l; nextsym(); c2 = rd_command(0); elselast = 1; } else { c2 = 0; if (elselast) /* in 'c' above */ { int temp = curlex.fl.l; curlex.fl.l = elseline; /* The construction applied here seems a little bit nasty - it would */ /* certainly give trouble if diagnostics were displayed with an echo of */ /* part of the surrounding source. Still, it seems a good idea! */ cc_warn(syn_warn_dangling_else); curlex.fl.l = temp; } } if (!(declposs && cfront_semantics)) { if (curlex.sym != s_nothing) ungetsym(); curlex.sym = s_rbrace; /* FRIGORMA */ } return mk_cmd_if(fl, e, c, c2); } } case s_else: cc_err(syn_err_else); nextsym(); return rd_command(0); case s_switch|s_qualified: nextsym(); /* Why does 'case s_while:' have a fileline but not case s_if:'? */ e = rd_condition(op & ~s_qualified); { Cmd *oldswitchcmd = cur_switchcmd; AEop oldbreak = cur_break; SynScope *oldswitchscope = cur_switchscope; TypeExpr *oldswitchtype = cur_switchtype; Expr *ee = syn_allocexprtemps(e); if (ee==0) e = ee = lit_zero; /* error=>switch(0). */ cur_switchcmd = c = mk_cmd_switch(fl, ee,0,0,0); cur_break = s_endcase; cur_switchscope = synscope; cur_switchtype = typeofexpr(e); /* not optimise0(e)! */ #ifdef TARGET_IS_ALPHA /* * I make this test conditional on building code for an Alpha since it was * use of a host C compiler on that that bit me. And the fact that this * is not unconditionally included is because introducing (yet) more * warnings into the compiler without full discussion is possibly * inconsiderate. But I sort-of hope that this might be put into * general service to encourage conservative and simple-minded use of the * C language. */ #ifndef DO_NOT_WARN_ABOUT_FUNNY_SWITCHES /* * This is here because one C compiler we tried hosting on (not ncc!) seemed * to mis-compile valid programs of the form * switch (e) case c1: case c2: { ... } * so this generates a warning whenever the command that follows a switch is * not just a simple block. I could take the view that I would like to * moan if the block after 'switch' had any declarations at its head. */ if (curlex.sym != s_lbrace) cc_warn(syn_warn_switch_funny); #endif #endif cmd2c_(c) = rd_command(0); cur_switchcmd = oldswitchcmd; cur_break = oldbreak; cur_switchscope = oldswitchscope; cur_switchtype = oldswitchtype; if (!(declposs && cfront_semantics)) { if (curlex.sym != s_nothing) ungetsym(); curlex.sym = s_rbrace; /* FRIGORMA */ } return c; } case s_return: nextsym(); push_exprtemp_scope(); e = curlex.sym == s_semicolon ? 0 : rd_expr(PASTCOMMA); if (e) { e = LanguageIsCPlusPlus && cur_structresult ? /* The effect of this code is to disable the C struct-result */ /* optimisation code in cg_return. This is need significant review */ /* for classes with constructors or virtual bases. */ /* The cast on the next line is a conspiracy with cg_return(). */ mkcast(s_return, mkctor_v(mkunary(s_content, (Expr *)cur_structresult), mkExprList(0,e)), te_void) : mkcast(s_return, e, cur_restype); #ifndef NO_RETURN_EXPRESSIONS /* Make return ALSO into an *EXPR* tree node. Maybe this is */ /* dying in the advent of CPLUSPLUS changes in simplify.c. */ e = h0_(e) == s_error ? errornode : mk_expr1(s_return, cur_restype, e); #endif } if (e != 0) implicit_return_ok = 0; if (e != 0 && /*equivtype(cur_restype, te_void)*/ isprimtype_(cur_restype, s_void)) { if (cur_fn_is_ctor) cc_rerr(syn_rerr_return_expr_ctor); else if (cur_fn_is_dtor) cc_rerr(syn_rerr_return_expr_dtor); else cc_rerr(syn_rerr_return_expr_void); } if (cur_fn_is_dtor) { /* forge 'goto __generated_dtor_part' instead */ LabBind *lab = label_reference(dtorgenlabsym); /* the 0 in the mk_cmd_lab is never used */ c = syn_reflab(lab, synscope, mk_cmd_lab(s_goto, fl, lab, 0)); pop_exprtemp_scope(); /* since we won't be calling killexprtemps */ } else { if (e == 0 && !equivtype(cur_restype, te_void)) /* do also the implicit return case too in cg/flowgraph. */ { if (LanguageIsCPlusPlus) cc_rerr(syn_warn_void_return); else if (!implicit_return_ok) cc_warn(syn_warn_void_return); } if (cur_fn_is_ctor) e = (Expr*) findbinding(thissym, NULL, LOCALSCOPES); if (e && (h0_(e) != s_error)) { /* may change type (in a harmless way) and loses s_return */ e = optimise0(e); add_expr_dtors(killexprtemp()); if (expr_dtors != NULL) { if (cur_structresult != 0) { e = mkbinary(s_comma, e, mkcast(s_return, expr_dtors, te_void)); expr_dtors = NULL; extra_flags = NULL; } else e = exprtemp_killer(e); } } else pop_exprtemp_scope(); /* since we won't be calling killexprtemps */ c = cmd_rescope(0, synscope, mk_cmd_e(op, fl, (e && h0_(e) != s_error) ? e : 0)); } break; #ifdef EXTENSION_VALOF case s_resultis: nextsym(); have_exprtemp_scope = true; push_exprtemp_scope(); e = optimise0( mkcast(s_return, rd_expr(PASTCOMMA), valof_block_result_type)); c = mk_cmd_e(op, fl, e); break; #endif case s_continue: if (cur_loopscope) c = cmd_rescope(cur_loopscope, synscope, mk_cmd_0(op, fl)); else { c=0; cc_err(syn_err_continue); } nextsym(); break; case s_break: if (cur_loopscope != 0 || cur_switchcmd != 0) c = cmd_rescope(cur_break == s_break ? cur_loopscope : cur_switchscope, synscope, mk_cmd_0(cur_break, fl)); else { c=0; cc_err(syn_err_break); } nextsym(); break; case s_goto: nextsym(); if (curlex.sym != s_identifier) { cc_err(syn_err_no_label); return rd_command(declposs); } { LabBind *lab = label_reference(curlex.a1.sv); /* the 0 in the mk_cmd_lab is never used */ c = syn_reflab(lab, synscope, mk_cmd_lab(op, fl, lab, 0)); } nextsym(); break; case s_throw: if (!LanguageIsCPlusPlus) goto defaultcase; nextsym(); { Expr* e = 0; if (curlex.sym != s_semicolon) e=rd_expr(UPTOCOMMA); /* because it is an assignment-expression, not an expression */ c = mkthrow(fl, e); break; } case s_try: if (!LanguageIsCPlusPlus) goto defaultcase; nextsym(); c = rd_compound_statement(s_try); { Handler *h = rd_handler(); Cmd* handler_exit; if (0) /* in a constructor/destructor */ handler_exit = mkthrow(fl, 0); else handler_exit = mkexpop(fl); elselast = 0; #define mk_cmd_hand(fl,a,b) mk_cmd_lab(s_catch,fl, (LabBind *)(a), (Cmd *)(b)) return mk_cmd_try(fl, c, h, handler_exit); } case s_catch: if (!LanguageIsCPlusPlus) goto defaultcase; cc_err(syn_err_catch_ignored); (void)rd_handler(); return 0; #ifdef TARGET_HAS_INLINE_ASSEMBLER case s_asm: if (feature & FEATURE_FUSSY) cc_err(syn_err_asm_not_available); push_exprtemp_scope(); c = rd_asm_block(); if (killexprtemp() != NULL) syserr("exprtemp in asm block"); elselast = 0; return c; #endif } elselast = 0; checkfor_delimiter_ket(s_semicolon, syn_err_expected1_aftercommand, syn_err_expected1a_aftercommand); if (have_exprtemp_scope) { add_expr_dtors(killexprtemp()); if (expr_dtors != NULL) { c = mk_cmd_block(curlex.fl, 0, mkCmdList(mkCmdList(0, mk_cmd_e(s_semicolon, curlex.fl, expr_dtors)), c)); expr_dtors = NULL; } } return c; } } static Cmd *rd_body(TypeExpr *t, TypeExpr *fntype, bool is_ctor, bool is_dtor) { cur_switchscope = 0; cur_switchcmd = 0; cur_loopscope = 0; cur_break = s_error; cur_restype = is_ctor ? te_void : t; cur_fn_is_ctor = is_ctor; cur_fn_is_dtor = is_dtor; cur_switchtype = te_lint; cur_structresult = 0; if ((mcrepoftype(t) >> MCR_SORT_SHIFT) == 3 && !returnsstructinregs_t(fntype)) { Symstr *structresultsym = sym_insert_id("__struct_result"); /* debugger-visible name moving to builtin.c. */ cur_structresult = mk_binder(structresultsym, bitofstg_(s_auto), ptrtotype_(t)); } currentfunction.structresult = cur_structresult; /* for cg.c. */ if (curlex.sym == s_lbrace) { Cmd *c = rd_block(blk_BODY, YES); /* share scope with args... */ return c; } else { cc_err(syn_err_no_brace); return 0; } } typedef struct DeclFnAux { FnAuxFlags flags; int32 val; } DeclFnAux; typedef struct DeclSpec { TypeSpec *t; SET_BITMAP stg; int32 stgval; DeclFnAux fnaux; /* private flags for C/C++ for 'omitted type' for non-fn etc. */ #define B_DECLMADE 1 #define B_TYPESEEN 2 #define B_IMPLICITINT 4 #define B_STGSEEN 8 #define B_LINKAGE 16 /* C++ extern "x" ... (incl. extern "x" { ...) */ #define B_LINKBRACE 32 /* C++ extern "x" { ... special case */ int synflags; } DeclSpec; /* rd_declspec() reads a possibly optional list (as controlled by */ /* 'declflag') of declaration-specifiers. (Dec 88 ANSI draft section */ /* 3.5). It returns an object of TypeSpec (subtype of TypeExpr) */ /* giving a bit map of types/storage classes read (plus Tagbinder for */ /* struct/union or Binder for 'typedef') plus (local) B_TYPESEEN and */ /* B_STGSEEN serve to enable 'f();' to be faulted and 'g(){}' to merely */ /* generate a warning. We can now warn on 'static z();' (no 'int'). */ /* It also performs normalisation of 'float' to 'short double', */ /* 'register' to 'auto register' to simplify later stages. */ /* Note that defaulting of storage class depends not only on context, */ /* but also on type - e.g. { int f(); ...} so it is done later. */ /* Oct92: soon add *optional* "long long" ==> s_longlong. */ static DeclSpec rd_declspec(int declflag, ScopeSaver template_formals) { SET_BITMAP illtype = 0, typesseen = 0, typedefquals = 0; int synflags = 0; Binder *b = 0; /* typedef or struct/union/enum tag binder record */ SET_BITMAP stgseen = 0; SET_BITMAP illstg = declflag & TOPLEVEL ? (bitofstg_(s_register)|bitofstg_(s_auto)| bitofstg_(s_virtual)|bitofstg_(s_friend)) : declflag & MEMBER ? (bitofstg_(s_register)|bitofstg_(s_auto)| bitofstg_(s_extern)|bitofstg_(s_weak)| (LanguageIsCPlusPlus ? 0 : bitofstg_(s_static))) : declflag & BLOCKHEAD ? (bitofstg_(s_virtual)|bitofstg_(s_friend)) : declflag & (TFORMAL|FORMAL|ARG_TYPES|CATCHER) ? (STGBITS & ~bitofstg_(s_register)) : STGBITS; int32 stgval = 0; FnAuxFlags auxseen = 0; int32 auxval = 0; /* fnaux->val */ bool newtag = NO; bool contentdefseen = NO; bool opaque = NO; /* opaque could be handled as a typebit but I don't since it's */ /* kept only in tag binders and the error handling is different */ for (;;) { AEop s = curlex.sym; if (!isdeclstarter_(s)) { int scope_level = 0; /* A typedef may be possible, else break from loop... */ if (typesseen & ~CVBITS) break; if (template_formals) scope_level = push_var_scope(template_formals, Scope_TemplateArgs); rd_type_name(); if (template_formals) pop_scope_no_check(scope_level); if ((curlex.sym & ~s_qualified) != s_identifier) break; if (curlex_typename == 0) { if (((stgseen & bitofstg_(s_friend)) && peepsym() == s_semicolon && (feature & FEATURE_CFRONT)) /* friend X; */ || ((declflag & TFORMAL) && s == s_typename)) /* <typename T> same as <class T> */ s = s_class; /* != curlex.sym NB */ else break; /* let rd_decl() handle what follows */ } else { b = curlex_typename; if (attributes_(b) & A_TEMPLATE && !(tagbindbits_(typespectagbind_(bindtype_(b))) & (TB_DEFD|TB_BEINGDEFD))) { s = tagbindsort(typespectagbind_(bindtype_(b)))|s_qualified; } else { s = s_typedefname; typedefquals = qualifiersoftype(bindtype_(b)), binduses_(b) |= u_referenced; } } } if (isstorageclass_(s)) { SET_BITMAP stgbit = bitofstg_(s); if (s == s_globalreg || s == s_globalfreg) stgbit = b_globalregvar; if (stgbit & illstg) cc_err(syn_err_stgclass, /* storage class illegal here */ s, ctxtofdeclflag(declflag)); else if (stgbit & stgseen || stgbit & (PRINCSTGBITS|bitofstg_(s_register)) && stgseen & (PRINCSTGBITS|bitofstg_(s_register))) { cc_err(syn_err_stgclass1, /* storage class incompatible */ s, stgseen); /* for error-recovery we keep the first stg unless the */ /* new one is typedef in which case we keep it */ if (s == s_typedef) stgseen = (stgseen & ~(PRINCSTGBITS|bitofstg_(s_register))) | stgbit; } else { stgseen |= stgbit; if (s == s_weak) stgseen |= bitofstg_(s_extern); /* @@@ beware -- this leads to 'extern incompatible with extern'. */ /* we should do this defaulting later, but to disallow '__weak auto' */ /* we need a separate illstg2 bit (working like illtype). */ } nextsym(); if (stgbit == b_globalregvar) { checkfor_ket(s_lpar); stgval = evaluate(rd_expr(PASTCOMMA)) << 1; checkfor_ket(s_rpar); if (s == s_globalfreg) stgval |= 1; } } else if (isfnaux_(s)) { auxseen |= bitoffnaux_(s); nextsym(); if (s == s_swi || s == s_swi_i) { if (s == s_swi_i) auxseen |= bitoffnaux_(s_swi) | f_specialargreg; checkfor_ket(s_lpar); auxval = CheckSWIValue(evaluate(rd_expr(PASTCOMMA))); checkfor_ket(s_rpar); } } else if (s == s_opaque) { if (typesseen & ~CLASSBITS) cc_rerr(syn_err_typeclash, s, typesseen & ~CLASSBITS); else opaque = YES; nextsym(); } else { SET_BITMAP typebit = bitoftype_(s & ~s_qualified); TagBinder *instantiatetemplate = NULL; int instantiatescope = 0; if (illtype & typebit) { /* this code relies that for type symbols x,y, "x y" is legal iff "y x" is. */ cc_err(syn_err_typeclash, s, typesseen & illtypecombination[shiftoftype_(s)]); /* New error recovery: ignore previous types/stgclass and retry. */ /* This is better for things like "class T {} int f() {...}". */ /* Note that we aren't just inserting a ';', e.g. sizeof(struct{}int) */ /* and also that 'struct {} typedef const int' splits AFTER the const. */ if (declflag & TEMPLATE) pop_scope(0); return rd_declspec(declflag & ~TEMPLATE, 0); } else { if (opaque && (typebit & ~CLASSBITS)) { cc_rerr(syn_err_typeclash, s_opaque, typebit); opaque = NO; } if (declflag & SIMPLETYPE && (typesseen || typebit & (CVBITS|ENUMORCLASSBITS))) cc_err(syn_err_illegal_simple_types, typesseen | typebit); if (typebit & typesseen & bitoftype_(s_long)) { /* long + long => longlong (without allowing longlonglong etc) */ s ^= s_long ^ s_longlong; typesseen &= ~bitoftype_(s_long); typebit = bitoftype_(s_longlong); } typesseen |= typebit; illtype |= illtypecombination[shiftoftype_(s)]; } if (!(typebit & ENUMORCLASSBITS && (s & s_qualified)) && !(s == s_class && (curlex.sym & ~s_qualified) == s_identifier)) nextsym(); if (typebit & ENUMORCLASSBITS) { TagBinder *b2; TagDefSort defining; bool sawid = 0; /* Now, after "struct id" a ';' or '{' indicates a new definition at */ /* the current nesting level, but not in type names, e.g. C++ */ /* struct T *p = new struct T; */ /* The rationale is that, "class T = int" ought to be interpreted as "typedef TYPE T = int" where "T" is the declarator-id. */ if ((declflag & TFORMAL) && !(declflag & TEMPLATE) && (typebit & CLASSBITS)) { DeclSpec ds; ds.t = mk_typevar(); ds.stg = bitofstg_(s_typedef); ds.stgval = stgval; ds.fnaux.flags = 0; ds.synflags = B_TYPESEEN; return ds; } if (curlex.sym == s_identifier) { Symstr *sv; Binder *tvb; /* NB: a classname (or typedefname) followed by '<' must always be a */ /* template_postfix, not a less-than. Hence improve error recovery. */ if (LanguageIsCPlusPlus) rd_template_postfix(template_formals, YES); /* Ah: perhaps we can write "class ::t<int> ..." for a top-level */ /* template? Currently forbid. */ sv = curlex.a1.sv; sawid = 1; nextsym(); defining = (curlex.sym == s_semicolon && declflag & CONC_DECLARATOR && !(stgseen & bitofstg_(s_friend))) ? TD_Decl : /* Context TFORMAL only arises when LanguageIsCPlusPlus. */ (declflag & TFORMAL && (curlex.sym == s_comma || curlex.sym == s_greater || curlex.sym == s_semicolon)) ? TD_Decl : (curlex.sym == s_colon && s != s_enum || curlex.sym == s_lbrace) ? TD_ContentDef : TD_NotDef; if (defining == TD_ContentDef) contentdefseen = YES; #ifdef WANT_BROKEN_SUPERFLOUS_PREFIX_WARNINGS /* This code warns that the 'struct' is superflous in these cases: typedef struct T T; struct T* t; // warning typedef struct S S; struct S { int s; }; // bogus warning but not in these cases: struct R; struct R* r; // no warning struct Q; typedef struct Q Q2; // no warning Additionally the warning is not seen (by sad and LDS) as being more helpful than annoying. Probably we don't understand the reason for it. */ if (LanguageIsCPlusPlus && !(stgseen & bitofstg_(s_typedef))) { Binder *b = findbinding(sv, 0, ALLSCOPES); SET_BITMAP stgbits; if (b != NULL && ((stgbits = bindstg_(b)) & bitofstg_(s_typedef)) && !(stgbits & u_implicitdef) && isclasstype_(bindtype_(b))) cc_warn(syn_warn_superfluous_prefix); } #endif if (syn_class_scope != NULL && (tagbindbits_(syn_class_scope) & TB_TEMPLATE)) { if ((tvb = findbinding(sv, 0, ALLSCOPES)) != NULL && istypevar(bindtype_(tvb))) { SET_BITMAP tbits = typebit; if (tbits & bitoftype_(s_class)|bitoftype_(s_struct)) tbits |= bitoftype_(s_class)|bitoftype_(s_struct); typespecmap_(bindtype_(tvb)) |= tbits; binduses_(tvb) |= u_referenced; } /* Its a template because they might contain references to type para in the parent. */ bind_scope |= TEMPLATE; } /* transforms 'T' to whatever it's bounded to */ if (syn_class_scope != NULL && has_template_arg_scope()) { Binder *b = findbinding(sv, 0, ALLSCOPES); if (b != NULL && is_template_arg_binder((Expr *)b) && isclasstype_(princtype(bindtype_(b)))) sv = bindsym_(typespecbind_(bindtype_(b))); } /* GLOBALSTG is implicit in C++ */ b2 = instate_tagbinding(sv, s, defining, (declflag) == (TFORMAL|TEMPLATE) ? TEMPLATE : bind_scope, &newtag); if (declflag & TEMPLATE && defining == TD_ContentDef) tagscope_(b2) = dup_template_scope(); if ((stgseen & bitofstg_(s_friend)) && defining == TD_ContentDef) /*&& (curlex.sym != s_semicolon))*/ { cc_rerr(syn_rerr_friend_class_not_definable, b2); stgseen &= ~bitofstg_(s_friend); } /* We should share this code for "class A<1> a;" with "A<1> a;". */ /* @@@ next test should be returned as result from rd_template_postfix. */ if (LanguageIsCPlusPlus) { TagBinder *tb_old; if (defining != TD_ContentDef && bind_global_(sv) != NULL && (attributes_(bind_global_(sv)) & A_TEMPLATE) && !(declflag & SPECIALIZE) && (tb_old = tagprimary_(typespectagbind_(bindtype_(bind_global_(sv))))) != NULL) { if ((tagbindbits_(tb_old) & TB_TEMPLATE) == 0) syserr("primary template $c", tb_old); if (tagbindbits_(tb_old) & TB_DEFD && !(tagbindbits_(b2) & (TB_DEFD|TB_BEINGDEFD))) { if (debugging(DEBUG_TEMPLATE)) cc_msg("template $b[%lx] -> $b[%lx]\n", tb_old, tagbindbits_(tb_old), b2, tagbindbits_(b2)); if (curlex.sym != s_lbrace && curlex.sym != s_times) { instantiatetemplate = class_template_reduce(tb_old, taginstances_(tb_old), tagactuals_(b2)); defining = TD_ContentDef; } /* beware bind_scope=storage for members here! */ b2 = instate_tagbinding(sv, s, defining, TOPLEVEL, &newtag); /* TEMPLATE OK to use 'newtag'? */ } } } if (LanguageIsCPlusPlus && newtag) /* @@@ check ansi re things like 'struct a; int a; struct a {}' etc. */ { Binder *b = instate_classname_typedef(b2, declflag); if (declflag & TEMPLATE) { if (!(declflag & TFORMAL)) tagbindbits_(b2) |= TB_TEMPLATE; attributes_(b) |= A_PRIMARY; } } /* the 2nd condition looks unnecessary, but see t14c/_1452W12.cpp */ if (declflag & TEMPLATE && tagbindbits_(b2) & TB_TEMPLATE) { if (!newtag) { merge_default_template_args(template_formals, b2, NULL); if (!(tagbindbits_(b2) & TB_DEFD)) tagformals_(b2) = template_formals; } else { tagformals_(b2) = template_formals; merge_default_template_args(template_formals, b2, NULL); } } /* @@@ The next 6 lines should be removable now that bind.c doesn't set */ /* TB_BEINGDEFD for "struct A;". From here ... */ /* Of course, since the mip/bind.c example (see TB_BEINGDEFD removal) */ /* can't happen under C++ scope rules, TB_BEINGDEFD is a bit spurious. */ #if 0 if (curlex.sym == s_semicolon && tagbindbits_(b2) & TB_BEINGDEFD) syserr("rd_declspec tidyup"); if (curlex.sym == s_semicolon) /* @@@ what about above CONC_DECLARATOR? */ tagbindbits_(b2) &= ~TB_BEINGDEFD; /* ... to here */ #endif if (s == s_enum) { if (defining == TD_ContentDef) synflags |= B_DECLMADE; else if (!(tagbindbits_(b2) & TB_DEFD)) cc_rerr(syn_err_undef_enum, sv); } else if (defining != TD_NotDef) synflags |= B_DECLMADE; /* police 'int;' error */ } else { defining = TD_ContentDef; /* anonymous class */ b2 = instate_tagbinding(0, s, TD_ContentDef, bind_scope, &newtag); } if (defining == TD_ContentDef) { /* assert (curlex.sym == s_lbrace */ /* || curlex.sym == s_colon && s != s_enum) */ int implicit_level = 0, implicit_level2 = 0; if (declflag & TEMPLATE) { if (!template_formals) syserr("funny template $c", b2); implicit_level = push_var_scope(template_formals, Scope_TemplateArgs); if (template_formals != tagformals_(b2)) implicit_level2 = push_var_scope(tagformals_(b2), Scope_TemplateArgs); } else if (declflag & SPECIALIZE) tagbindbits_(b2) |= TB_SPECIALIZED; if (LanguageIsCPlusPlus && (declflag & (FORMAL|TFORMAL)) && !tagactuals_(b2)) cc_rerr(syn_rerr_tagdef_in_formals, b2); if (instantiatetemplate) { int h = tagtext_(instantiatetemplate); if (debugging(DEBUG_TEMPLATE)) cc_msg("instantiate $c buffer[%d]\n", instantiatetemplate, h); if (h == -1) syserr("template symbol buffer lost"); else { instantiatescope = push_var_scope(tagscope_(b2), Scope_TemplateDef); (void) push_var_scope(tagactuals_(b2), Scope_TemplateArgs); lex_openbody(h, YES, YES, bindsym_(instantiatetemplate), bindsym_(b2)); } } if (declflag & TEMPLATE) (void)lex_bodybegin(); /* avoid spurious (C++?) warning for enum { x,y }; */ if (s==s_enum) { synflags |= B_DECLMADE; rd_enumdecl(b2); checkfor_ket(s_rbrace); } else { if (stgseen & bitofstg_(s_friend)) { cc_err(syn_err_not_friend, (bindsym_(b2))); checkfor_ket(s_semicolon); } else { AEop old_access = access; bool has_local_nested_class = (LanguageIsCPlusPlus && (declflag & BLOCKHEAD)); FuncMisc func_misc; PendingFnList *old_pendingfns; if (has_local_nested_class) { save_pendingfns(&old_pendingfns); save_curfn_misc(&func_misc); } /* there is a alloc_mark() in syn_note_generated_fn() */ rd_classdecl_(b2); access = old_access; checkfor_ket(s_rbrace); if (has_local_nested_class && (syn_pendingfns || syn_generatedfns)) { Mark* mark = alloc_mark(); chk_for_auto = YES; while (syn_pendingfns || syn_generatedfns) { TopDecl *d; cg_reinit(); /* BEFORE rd_topdecl() */ /* there is a alloc_unmark() in case of syn_generatedfns */ d = rd_topdecl(NO); /* careful about function template */ if (h0_(d) != s_fndef) continue; /*(void)globalize_typeexpr(bindtype_(d->v_f.fn.name));*/ cg_topdecl(d, curlex.fl); } chk_for_auto = NO; alloc_unmark(mark); } if (has_local_nested_class) { restore_curfn_misc(&func_misc); restore_pendingfns(old_pendingfns); } } } if (declflag & TEMPLATE) tagtext_(b2) = lex_bodyend(); if (instantiatetemplate) { lex_closebody(); pop_scope_no_check(instantiatescope); } if (declflag & TEMPLATE) { if (implicit_level2) pop_scope_no_check(implicit_level2); pop_scope(implicit_level); } } else if (!sawid) { cc_err(syn_err_tag_brace, s); /* recovers for 'struct *a' or suchlike error. */ } b = (Binder *)b2; } } } if (LanguageIsCPlusPlus && declflag & TOPLEVEL && isstring_(curlex.sym) && typesseen == 0 && stgseen == bitofstg_(s_extern) && auxseen == 0) { Expr *s = rd_ANSIstring(); Linkage *p = syn_linkage_free; if (p == 0) p = (Linkage *)GlobAlloc(SU_Other, sizeof(Linkage)); else syn_linkage_free = p->linkcdr; p->linkcar = linkage_of_string((String *)s); p->linkcdr = syn_linkage; syn_linkage = p; synflags |= B_LINKAGE; if (curlex.sym == s_lbrace) nextsym(), synflags |= B_LINKBRACE; /* else the 'extern "C" typedef int foo();' form. */ /* Alternative implementation: retry rd_declspec and then */ /* pop implicitly at terminating ';' or '}'? */ { DeclSpec ds; ds.t = (TypeExpr *)DUFF_ADDR; ds.stg = stgseen; ds.stgval = stgval; ds.fnaux.flags = 0; ds.synflags = synflags; return ds; } } if (typedefquals & typesseen) cc_rerr(syn_rerr_qualified_typedef(b, typedefquals & typesseen)); /* could warn here in C (not C++) for undefined const <fntypedef>. */ if (typesseen) synflags |= B_TYPESEEN; if (stgseen) synflags |= B_STGSEEN; if ((declflag & TYPE_NEEDED) && typesseen == 0) cc_rerr(syn_rerr_missing_type), synflags |= B_TYPESEEN; if ((typesseen & NONQUALTYPEBITS) == 0) { if ((typesseen|stgseen) != 0 || !(declflag & FORMAL)) /* consider returning 0 for untyped formals? changes would be need for several routines, so pend */ { if ((typesseen & (bitoftype_(s_long)|bitoftype_(s_short)| bitoftype_(s_signed)|bitoftype_(s_unsigned))) == 0) synflags |= B_IMPLICITINT; typesseen |= bitoftype_(s_int); auxseen |= f_norettype; /* in case is a function */ } } if (typesseen & bitoftype_(s_float)) /* normalise for rest of system */ { typesseen ^= (bitoftype_(s_float) ^ bitoftype_(s_double)); if (typesseen & bitoftype_(s_long)) { if (!(suppress & D_LONGFLOAT) && !(feature & FEATURE_PCC)) { suppress |= D_LONGFLOAT; cc_rerr(syn_rerr_long_float); } typesseen &= ~bitoftype_(s_long); } else typesseen |= bitoftype_(s_short); /* float => short double */ } if (typesseen & bitoftype_(s_longlong)) /* normalise for rest of system */ { /* map type "long long" into "long short"... */ /* Storing types as bit-maps must be up for review. */ typesseen = (typesseen & ~bitoftype_(s_longlong)) | ts_longlong; } if (typesseen & bitoftype_(s_unaligned)) { TagBinder *tb = NULL; if (typesseen & CLASSBITS) { tb = (TagBinder *)b; if (newtag) { tagbindbits_(tb) |= TB_UNALIGNED; tb = NULL; } } else if (typesseen & bitoftype_(s_typedefname)) { TypeExpr *t = princtype(bindtype_(b)); if (isclasstype_(t)) tb = typespectagbind_(t); } if (tb != NULL && !(tagbindbits_(tb) & TB_UNALIGNED)) { cc_rerr(syn_rerr_not_decl_qual(tb,s_unaligned)); typesseen ^= bitoftype_(s_unaligned); } } if (opaque) { TagBinder *tb = (TagBinder *)b; if (tb == NULL) syserr("opaque confused: no TagBinder"); if (contentdefseen) { if (!(typesseen & CLASSBITS)) syserr("opaque confused: $b is not struct/class", b); tagbindbits_(tb) |= TB_OPAQUE; } else { if ((tagbindbits_(tb) & TB_DEFD) && !(tagbindbits_(tb) & TB_OPAQUE)) cc_rerr(syn_rerr_not_decl_qual(tb,s_opaque)); else tagbindbits_(tb) |= TB_OPAQUE; } } if (stgseen & bitofstg_(s_register)) /* normalise for rest of system */ stgseen |= bitofstg_(s_auto); #ifndef NON_CODEMIST_MIDDLE_END /* AM: The error recovery here is not good: this new code currently */ /* fails unpleasantly if #pragma -r is set when a function is defined. */ /* I think we can't do this until after function determination etc. */ /* Also, I want to be able be able to specify physical registers not */ /* just V1...Vn. */ if (declflag & TOPLEVEL) { if (global_intreg_var > 0) stgseen &= ~(bitofstg_(s_static)|bitofstg_(s_extern)), stgseen |= b_globalregvar, stgval = global_intreg_var << 1; else if (global_floatreg_var > 0) stgseen &= ~(bitofstg_(s_static)|bitofstg_(s_extern)), stgseen |= b_globalregvar, stgval = (global_floatreg_var << 1) | 1; } #endif { DeclSpec ds; TypeSpec *t = primtype2_(typesseen, b); /* AM: the next line is really the wrong place to do this code (it */ /* should be in the loop above) since declaration specifiers may follow */ /* the struct-specification. */ if (contentdefseen && !(suppress & D_STRUCTPADDING)) { bool padded = NO; (void)sizeoftypenotepadding(t, &padded); if (padded) cc_warn(syn_warn_struct_padded, b); } ds.t = t; ds.stg = stgseen; ds.stgval = stgval; ds.fnaux.flags = auxseen, ds.fnaux.val = auxval, ds.synflags = synflags; return ds; } } static SET_BITMAP rd_onceonlyquals(SET_BITMAP allowed) { SET_BITMAP qseen = 0; for (;;) { AEop s = curlex.sym; SET_BITMAP q; if (!isdeclstarter_(s)) break; q = bitoftype_(s); if (!(q & allowed)) break; if (q & qseen) cc_err(syn_err_typeclash, s, q); qseen |= q; nextsym(); } return qseen; } /* the following macro checks for an arg which has not been typed */ #define is_untyped_(x) (h0_(x) == s_typespec && typespecmap_(x) == 0) typedef TypeExpr Declarator; /* funny inside-out Expr */ #define sub_declarator_(x) (typearg_(x)) /* Declarators: read these backwards (inside out) to yield a name * (omitted if abstract declarator) and a TypeExpression (a la Algol68). * Then the declarator AE structure is read and an in-place pointer reverse * is done to turn a 'basictype' (possibly typedef) and a declarator into * a declaree (identifier or empty) in 'declarator_name' and TypeExpr. * For C++ we need to allow things like "int a(3);". This is currently * done by an s_cppinit Declarator node (local to rd_declarator()) and * declarator_init. 'inner' forbids (e.g.) "int (a(3))" etc. */ static Declarator *rd_formals_1(Declarator *a, const DeclFnAux *fnaux); static Declarator *rd_declarator_postfix(Declarator *a, int declflag, const DeclFnAux *fnaux, bool inner) { for (;;) switch (curlex.sym) { case s_lpar: { int scope_level = -1; if (declflag & (NEW_TYPENAME|CONVERSIONTYPE)) return a; nextsym(); if (LanguageIsCPlusPlus) { /* There is an ambiguity here with look-ahead for C++ initialisers and */ /* olde-style C function definitions. Consider: */ /* int x = 3; int a(x); int f(x) int x; { return x; }. */ /* Here we resolve this by allowing such f(x) only if x is not in scope */ /* and warning about the archaism. */ /* This represents a non-upwards compatibility of C to C++. */ /* Really we should read ahead to decide on seeing ';' (or ',' etc). */ if (a != 0 && h0_(a) == s_binder) scope_level = push_multi_scope(bindparent_((Binder *)a)); rd_type_name(); if (!inner && declflag & (TOPLEVEL|BLOCKHEAD) && !(curlex.sym == s_rpar || curlex.sym == s_ellipsis || isdeclstarter2_(curlex))) { /* could be a C++ initialiser, but be gentle if arg is an */ /* unbound simple identifier. */ if (!(declflag & TOPLEVEL && curlex.sym == s_identifier && findbinding(curlex.a1.sv, NULL, ALLSCOPES) == NULL)) /* return for caller to do rd_exprlist... */ return mk_typeexpr1(s_cppinit, a, 0); /* warn because: not C++ and because odd 'unbound' test. */ cc_warn(syn_warn_archaic_fnpara); } } a = rd_formals_1(a, fnaux); if (scope_level != -1) pop_scope_no_check(scope_level); } break; case s_lbracket: if (declflag & CONVERSIONTYPE) return a; nextsym(); { Expr *e = 0; if (curlex.sym != s_rbracket) { e = mkintegral(s_subscript, rd_expr(PASTCOMMA)); /* The next line allows new(int [n][6]) with 'n' a variable for C++. */ if (!(declflag & (NEW_TYPENAME|FLEX_TYPENAME) && h0_(a) == s_nothing)) e = check_arraysize(e); } a = mk_typeexpr1(t_subscript, a, e); } checkfor_ket(s_rbracket); break; default: return a; } } /* AM: next edit the following becomes a TypeFnAux* arg to rd_formals. */ static int32 syn_minformals, syn_maxformals; static bool syn_oldeformals; /* @@@ use in rd_decl? */ /* set by rd_formals, read by rd_declarator_1() */ static Symstr *declarator_name; /* set by rd_declarator: 0 or Symstr * */ static Binder *declarator_mbinder; /* set by rd_declarator: binder for A::x or 0. */ /* use bindstg_(memfns/memfna) + bindparent_() */ /* in fixup_fndecl/fndef. */ static TagBinder *declarator_qscope; /* set if the declaree is qualified... */ #define MEMFNBITS (b_memfna | b_memfns) /* (declarator_name could become a Binder *.) */ static bool declarator_init; /* ditto */ /* rd_declarator reads a C declarator (q.v.). We test declflag to see */ /* whether CONC_DECLARATOR or ABS_DECLARATOR's (or both) are */ /* acceptable, also TOPLEVEL (which allows old 'f(a,b)' non-prototype */ /* form). In C++ declflag is tested more. */ static Declarator *rd_declarator_1(int declflag, const DeclFnAux *fnaux, bool inner) { static Declarator emptydeclarator = { s_nothing }; /* /* @@@ kill? */ static Declarator errordeclarator = { s_error }; Declarator *a; AEop op; rd_dname(); op = curlex.sym & ~s_qualified; declarator_qscope = 0; if (declflag & CONVERSIONTYPE && !(op == s_times || op == s_and)) /* CONVERSIONTYPE declarators include *, &, S::* types only. */ op = s_nothing; switch (op) { defaultcase: default: if (declflag & CONC_DECLARATOR) { cc_err(syn_err_expected3); if (curlex.sym == s_rbrace && !(declflag & TOPLEVEL)) nextsym(); return &errordeclarator; } a = &emptydeclarator; break; case s_pseudoid: case s_identifier: if (declflag & ABS_DECLARATOR) { /* @@@ improve next error message */ cc_err(syn_err_unneeded_id); a = &emptydeclarator; } else { a = curlex.sym & s_qualified && curlex_binder ? (Declarator *) curlex_binder : (Declarator *) curlex.a1.sv; /* Symstr(s_id) is Declarator (or now s_member/s_binder). */ if (a == 0 || h0_(a) != s_identifier && h0_(a) != s_binder && h0_(a) != s_member) syserr("rd_member_name=0"); if (LanguageIsCPlusPlus) { /* @@@ we should fault no-fn s_pseudoid's later. */ if (op == s_pseudoid && curlex_optype) a = (Declarator *)syn_list3(s_convfn, a, curlex_optype); /* We could set the access context later (at declarator_mbind), this */ /* may even be better in that it matches scope retrieval for memfns. */ /* Note subtleties ANSI-resolvable in: int A::v[sizeof x], A::f(t y); */ /* of whether x and t are looked up in A:: or just global scope. */ if (bind_scope & TOPLEVEL /* @@@ nasty usage here... */ && curlex.sym & s_qualified) (void)set_access_context(curlex_scope, 0); } } if (curlex.sym & s_qualified) declarator_qscope = curlex_scope; nextsym(); break; case s_lpar: if (declflag & NEW_TYPENAME) return &emptydeclarator; /* Note that "int ()" means an abstract declarator (or nameless formal) */ /* of the type of "int x()", not "int (x)". */ /* Similarly "int (void)" or "int (typedefname)" represent fn-typenames */ /* @@@ However, the ANSI draft (Dec 88) has an ambiguity in */ /* "typedef int t; void f(int (t));" as to whether the formal to f is */ /* of type "int" and name "t" or nameless and of type "int (int)". */ /* We choose to select the latter (this seems to be the ANSI ctte's */ /* intent from the example "t f(t (t))" in section 3.5.6 (dec 88)). */ nextsym(); rd_type_name(); /* @@@ for C++ a form of ungetsym() might be an idea here so that */ /* rd_declarator_postfix can parse the '(', or maybe we need to parse */ /* ahead as 'either'. See other calls to rd_formals_1. */ if ((declflag & (ABS_DECLARATOR|FORMAL|TFORMAL|CATCHER|MEMBER)) && (curlex.sym == s_rpar || curlex.sym == s_ellipsis || isdeclstarter2_(curlex))) { a = rd_formals_1(&emptydeclarator, fnaux); } else { a = rd_declarator_1(declflag, fnaux, 1); if (h0_(a) == s_error) return a; checkfor_ket(s_rpar); } break; case s_and: if (!LanguageIsCPlusPlus) goto defaultcase; case s_times: { AEop typeop = (curlex.sym & ~s_qualified) == s_times ? t_content : t_ref; TagBinder *tb = curlex.sym & s_qualified ? curlex_scope : 0; /* @@@ What is curlex_scope/mem_scope relation? */ Declarator *aa; SET_BITMAP quals; nextsym(); quals = rd_onceonlyquals(CVBITS); a = rd_declarator_1(declflag, fnaux, inner); if (h0_(a) == s_error) return a; /* move s_cppinit to outermost level, suppress rd_declarator_postfix(). */ if (h0_(aa = a) == s_cppinit) a = sub_declarator_(a); a = mk_typeexpr1(typeop, a, (Expr *)(IPtr)quals); if (tb) a = (Declarator *)syn_list3(t_coloncolon, a, tb); if (h0_(aa) == s_cppinit) { sub_declarator_(aa) = a; return aa; } } break; } return rd_declarator_postfix(a, declflag, fnaux, inner); } static TypeExpr *fault_incomplete_type_object(TypeExpr *tt, Symstr *name, bool member, SET_BITMAP stg) { /* Fault attempts to declare an object (or member) of */ /* 'incomplete type' or function type. Members are constraint */ /* violations, objects are unclear, maybe just undefined. */ /* Note that "extern struct UNDEF x;" is allowed. */ /* C-ONLY: Note also that member <==> (stg & PRINCSTGBITS) == 0. */ TypeExpr *t = princtype(tt); if (h0_(t) == s_typespec) { SET_BITMAP m = typespecmap_(t); if (m & CLASSBITS) { TagBinder *b = typespectagbind_(t); SET_BITMAP bits = tagbindbits_(b); /* Much of the compiler can support undefined structs until */ /* first essential use, but ANSI ban. */ if (!(member && stg & bitofstg_(s_static) && bits & TB_BEINGDEFD)) { if (bits & TB_BEINGDEFD && (b == current_member_scope())) { if (member) cc_err(syn_err_selfdef_struct_member(b,name)); else cc_err(syn_err_selfdef_struct_object(b,name)); goto fixup; } if (!(bits & TB_DEFD) && !(stg & bitofstg_(s_extern)) && !((stg & bitofstg_(s_static)) && member)) { if (member) { if (!LanguageIsCPlusPlus || !(tagbindbits_(syn_class_scope) & TB_TEMPLATE)) cc_err(syn_err_undef_struct_member(b,name)); } else cc_err(syn_err_undef_struct_object(b,name)); goto fixup; } /* This is a first stab -- more work has to be to fault static members */ /* and fn args/results at the '}' in the dark corners like */ /* class C:ab { friend C(); static C x; <maybe override pure fn> }; */ /* or in explicit cast */ if (bits & TB_ABSTRACT) { if (member) cc_rerr(syn_rerr_abstract_class_member(b,name)); else cc_rerr(syn_rerr_abstract_class_object(b,name)); /* fixup is just to allow it */ } if (bits & TB_OPAQUE) { if (member) cc_rerr(syn_rerr_opaque_class_member(b,name)); else cc_rerr(syn_rerr_opaque_class_object(b,name)); /* fixup is just to allow it */ } } } if (m & bitoftype_(s_void)) { if (member) cc_err(syn_err_void_object_member(name)); else cc_err(syn_err_void_object_object(name)); goto fixup; } } /* @@@ pick up more [] cases (like auto, but not extern) below? */ if (h0_(t) == t_subscript && typesubsize_(t) == 0 && member && !(stg & bitofstg_(s_static))) { if (!(suppress & D_ZEROARRAY)) { if (suppress & D_MPWCOMPATIBLE) cc_warn(syn_rerr_open_member, name); else cc_pccwarn(syn_rerr_open_member, name); } /* ANSI ban open array members, pcc treats as [0]. */ typesubsize_(t) = globalize_int(0); } if (h0_(t) == t_fnap && LanguageIsCPlusPlus && !member) { TypeExpr *tt = princtype(typearg_(t)); TagBinder *cl; if (isclasstype_(tt) && tagbindbits_(cl = typespectagbind_(tt)) & TB_ABSTRACT) cc_rerr(syn_rerr_abst_class_rtype(cl)); } if (h0_(t) == t_fnap && (LanguageIsCPlusPlus ? (!member && !(stg & (bitofstg_(s_extern)|bitofstg_(s_static)))) : (member || !(stg & (bitofstg_(s_extern)|bitofstg_(s_static)))) )) { /* Beware: next line was syn_pccwarn, but AM sees PCC error. */ if (member) cc_rerr(syn_rerr_fn_ptr_member(name)); else cc_rerr(syn_rerr_fn_ptr_object(name)); /* Check non-typedef formals have types before fixup. */ if (h0_(tt) == t_fnap) ensure_formals_typed(typefnargs1_(tt), 1); goto fixup; } return tt; fixup: return ptrtotype_(tt); } /* @@@ AM Jan 90: The two calls to fault_incomplete_formals() make */ /* me nervous: it is ANSI illegal to have a fn prototype DEFINITION */ /* with an incomplete type (e.g. void or 'struct t' where tag t is not */ /* yet defined), but in a DECLARATION this is merely ANSI undefined. */ /* Now, to avoid syserr()s (and to be helpful) in later calls to */ /* functions with void parameters it is necessary to fault them at the */ /* time of declaration. The line below has the effect of faulting */ /* "struct a; extern void f(struct a);" too, */ /* (but of course not "extern void f(struct a *);"). */ /* In C we treat this as an error, but allow it in C++ (see below). */ /* This only concerns FORMAL's (prototype) and so is PCC-irrelevant. */ /* Also, don't use declstg_() for DeclRhsList/FormTypeList pun. */ static void fault_incomplete_formals(DeclRhsList *p, bool defn) { for (; p != NULL; p = p->declcdr) { if (LanguageIsCPlusPlus) { /* Don't moan about things like: class T { friend T f(T); ... etc. */ /* Except that we moan for void g(T x) {} if T undefined. */ TypeExpr *t = princtype(p->decltype); if (!defn && isclasstype_(t)) continue; } p->decltype = fault_incomplete_type_object( p->decltype, p->declname, 0, bitofstg_(s_auto)); } } static TypeExpr *fault_odd_fn_array(TypeExpr *t) { /* Precondition: t is a t_fnap or t_subscript node. */ /* Return t if OK, else a fixed up version -- we are sole owners. */ /* ANSI (Oct88) oddity: function returning fn/array is a constraint */ /* violation, whereas array of non-object type (void/fn/undef struct) */ /* is done by weasel words (p28). Treat similarly. */ TypeExpr *a = typearg_(t), *pa = princtype(a); /* maybe typedef! */ /* fault ref to void. */ if (h0_(t) == t_ref && isprimtype_(pa, s_void)) { /* treat as ref to int (better ideas?) */ cc_rerr(syn_rerr_ref_void); typearg_(t) = te_int; return t; } /* fault array of ref, pointer to ref and ref to ref. */ if (h0_(pa) == t_ref && (h0_(t) == t_subscript || h0_(t) == t_content || h0_(t) == t_ref)) { /* just forget the ref. */ cc_rerr(syn_rerr_ill_ref, t); typearg_(t) = typearg_(pa); return t; } /* fault function returning fn or array */ if (h0_(t) == t_fnap && (h0_(pa) == t_subscript || h0_(pa) == t_fnap)) { /* fn returning array/fn => fn returning ptr to array elt/fn. */ cc_rerr(syn_rerr_fn_returntype, pa); if (h0_(pa) == t_subscript) a = typearg_(pa); goto addptr; } /* fault arrays of fn, void, @@@???undef structs, @@@???[] arrays. */ if (h0_(t) == t_subscript && (h0_(pa) == t_fnap || isprimtype_(pa, s_void))) { /* array of fn/void => array of ptrs to fn/void. */ cc_rerr(syn_rerr_array_elttype, pa); goto addptr; } return t; addptr: typearg_(t) = mk_typeexpr1(t_content, a, 0); return t; } /* rd_declarator() returns 0 in the event that it failed to find a declarator. Note that this can only happen if 'CONC_DECLARATOR' is set. The caller is now responsible for faulting declarations of 'incomplete types' (see ansi). */ static TypeExpr *rd_declarator(int declflag, TypeExpr *basictype, const DeclFnAux *fnaux, SET_BITMAP stg) { Declarator *x; bool init = 0; /* This is one case where CPLUSPLUS can't be removed. ctorsym et al. */ #ifdef CPLUSPLUS TagBinder *mem_scope = current_member_scope(); if (LanguageIsCPlusPlus && curlex.sym == s_bitnot) { rd_dtor(mem_scope); if ((curlex.sym & ~s_qualified) == s_pseudoid) curlex_binder = findbinding(dtorsym, mem_scope, INCLASSONLY); } #endif x = rd_declarator_1(declflag, fnaux, 0); if (h0_(x) == s_cppinit) { init = 1; x = sub_declarator_(x); } for (;;) { TypeExpr *convtype = NULL; if (h0_(x) == s_convfn) { convtype = (TypeExpr *)typespecbind_(x), x = sub_declarator_(x); /* we now know x is s_identifier, s_member or s_binder. */ } switch (h0_(x)) { defaultcase: default: syserr(syserr_rd_declarator, (long)h0_(x)); case s_error: return 0; /* error from rd_declarator_1() */ case s_nothing: declarator_init = init; declarator_mbinder = 0; declarator_name = 0; return basictype; #ifdef CPLUSPLUS case s_binder: if (!LanguageIsCPlusPlus) goto defaultcase; declarator_init = init; { Binder *b = (Binder *)x; TypeExpr *t = bindtype_(b); Symstr *sv = bindsym_(b); if (sv == ctorsym || sv == dtorsym || convtype != NULL) basictype = fixup_special_member(sv, basictype, convtype != NULL ? convtype : te_void, bindparent_(b), stg); if (h0_(t) == t_ovld) { b = ovld_match_def(b, basictype, typeovldlist_(t), cur_template_formals != NULL, declflag); if (cur_template_formals) (void)applicable_template_formals(); if (b == NULL /*|| mem_scope == NULL*/) goto notmember; if (!(bindstg_(b) & b_impl)) syserr("rd_declarator $b", b); declarator_mbinder = b; /* for fixup_fndecl/def */ declarator_name = bindsym_(realbinder_(b)); return basictype; } if (bindstg_(b) & b_undef) /* static data member */ { declarator_mbinder = b; /* for rd_declrhs_exec */ declarator_name = bindsym_(b); return basictype; } } /* drop through */ case s_member: if (!LanguageIsCPlusPlus) goto defaultcase; cc_err(syn_err_no_member_here, (Binder *)x); notmember: /* in class A {...} a ... ensure typedef A gets marked as referenced */ if (isclasstype_(basictype)) use_classname_typedef(basictype); declarator_init = init; declarator_mbinder = 0; declarator_name = bindsym_((Binder *)x); return basictype; #endif case s_identifier: declarator_init = init; declarator_mbinder = 0; declarator_name = (Symstr *)x; #ifdef CPLUSPLUS if (LanguageIsCPlusPlus) { if ((declflag & MEMBER) && (declarator_name == tagbindsym_(mem_scope) || (tagprimary_(mem_scope) != NULL && declarator_name == tagbindsym_(tagprimary_(mem_scope))))) declarator_name = ctorsym; if (declarator_name == ctorsym || declarator_name == dtorsym || convtype != NULL) basictype = fixup_special_member(declarator_name, basictype, convtype != NULL ? convtype : te_void, mem_scope, stg); else if (isclasstype_(basictype)) /* in class A {...} a ... ensure typedef A gets marked as referenced */ use_classname_typedef(basictype); } #endif return basictype; case t_fnap: { Declarator *y = sub_declarator_(x); #ifdef CPLUSPLUS if (LanguageIsCPlusPlus && h0_(y) == s_nothing && (declflag & MEMBER)) { TypeExpr *t = princtype(basictype); if (isclasstype_(t) && typespectagbind_(t) == mem_scope) { sub_declarator_(x) = y = (Declarator *)ctorsym; basictype = te_int; typefnaux_(x).flags |= f_norettype; } else { cc_err(syn_err_missing_named_mfn); sub_declarator_(x) = y = (Declarator *)gensymval(1); } } #endif if (!(h0_(y) == s_identifier && (declflag & TOPLEVEL))) /* all cases except outermost () of TOPLEVEL declarator */ ensure_formals_typed(typefnargs1_(x), 1); } /* drop through */ case t_ref: case t_content: case t_subscript: case t_coloncolon: { Declarator *temp = sub_declarator_(x); if (is_untyped_(basictype)) /* e.g. f(int a,*b) */ { cc_rerr(syn_rerr_missing_type1); basictype = te_int; } sub_declarator_(x) = (Declarator *)basictype; basictype = fault_odd_fn_array((TypeExpr *)x); if ( h0_(x) == t_fnap && (typefnaux_(basictype).flags & bitoffnaux_(s_pure)) && (mcrepoftype(typearg_(basictype)) & MCR_SORT_MASK) == MCR_SORT_STRUCT && !(typefnaux_(basictype).flags & bitoffnaux_(s_structreg))) typefnaux_(basictype).flags &= ~bitoffnaux_(s_pure); x = temp; } break; } } } static TypeExpr *rd_typename(int declflag) { DeclSpec ds; ds = rd_declspec(declflag, 0); /* TYPE_NEEDED and ~STGCLASS_OK */ if (ds.synflags & B_IMPLICITINT && (LanguageIsCPlusPlus || !(suppress & D_FUTURE))) { if (LanguageIsCPlusPlus && !(suppress & D_IMPLICITINT)) cc_rerr(syn_rerr_missing_type); else cc_warn(syn_rerr_missing_type); } if (!(declflag & SIMPLETYPE)) return rd_declarator(declflag, ds.t, &ds.fnaux, ds.stg); else { TypeExpr *t = princtype(ds.t); TagBinder *tb; if (isclasstype_(t) && (tagbindbits_(tb = typespectagbind_(t)) & TB_TEMPLATE)) { Symstr *sv = specialized_name_of(tb); BindList *bl = taginstances_(tb); for(; bl != NULL; bl = bl->bindlistcdr) if (bindsym_(bl->bindlistcar) == sv) return tagbindtype_((TagBinder *)bl->bindlistcar); } return ds.t; } /* Ignore the value in declarator_name as abstract declarator. */ /* Incomplete types are valid here (or faulted later (e.g. sizeof)) */ } /* note that in general we cannot default storageclasses on parsing them due to the differing default classes in "{ int a,f();...}". On the other hand nonsensical combinations SHOULD be detected by rd_typename(). */ static void defaultstorageclass(DeclRhsList *d, int declflag, Binder *mbind) { if ((declflag & STGCLASS_OK) && (d->declstg & PRINCSTGBITS) == 0) { SET_BITMAP s = d->declstg; TypeExpr *t = d->decltype; if (debugging(DEBUG_BIND)) cc_msg("defaultstg $r[%lx]%x\n", d->declname, (long)s, declflag); if (declflag & (BLOCKHEAD|FORMAL|ARG_TYPES|CATCHER)) /* of course, by now there are no arg fns (mapped to ptrs). */ s |= isfntype(t) ? bitofstg_(s_extern) : bitofstg_(s_auto); else if (declflag & TOPLEVEL) { if (isfntype(t)) { /* as of CD #2 inline no longer effects linkage */ if (mbind == 0) s |= bitofstg_(s_extern); else s |= attributes_(bindparent_(mbind)) & A_NOLINKAGE ? bitofstg_(s_static) : bitofstg_(s_extern); } else s |= LanguageIsCPlusPlus && (qualifiersoftype(t) & bitoftype_(s_const)) ? bitofstg_(s_static)|b_implicitstg : bitofstg_(s_extern)|b_implicitstg; } else syserr(syserr_defaultstgclass, (int)declflag); d->declstg = s; } } static void ensure_formals_typed(DeclRhsList *d, bool proto) { /* proto is here true if olde-style is not acceptable: */ /* e.g. non-top level. */ for (; d; d = d->declcdr) { TypeExpr *t = d->decltype; if (is_untyped_(t)) { if (proto) /* @@@ ensure that f(,) error has not got this far */ cc_rerr(syn_rerr_missing_type2, d->declname); else if (!(feature & FEATURE_PCC)) /* God knows why ANSI do not consider this an error */ cc_warn(syn_warn_undeclared_parm, d->declname); d->decltype = te_int; } } } /* (local to rd_formals). merge this fn with previous? */ static bool is_proto_arglist(DeclRhsList *d, int map) { /* map is 1 if ellipsis seen, else 0. Error if ansi/old-style mix */ for (; d; d = d->declcdr) { TypeExpr *t = d->decltype; map |= (is_untyped_(t)) ? 2 : 1; } if (map == 3) cc_rerr(syn_rerr_mixed_formals); /* The caller can indicate that () is considered empty id-list with */ /* map=0, or empty decl-list with map=1 (e.g. for ellipsis). */ return (map & 1) != 0; } static void merge_formal_decl(DeclRhsList *d, DeclRhsList *dnew) { /* Here I have a formal parameter (d) which is now being given an */ /* explicit declaration (dnew). Merge new information in with the old. */ TypeExpr *t = d->decltype; if (!is_untyped_(t)) /* previous type info */ cc_err(syn_err_duplicate_type, d->declname); d->declstg = dnew->declstg; d->decltype = dnew->decltype; } static void CheckReturnType(TypeExpr *fntype) { if (!LanguageIsCPlusPlus && (feature & FEATURE_FUSSY)) { /* dr 113: only 'void' is allowed as a function's return type */ /* not any void type. */ TypeExpr *resulttype = typearg_(fntype); if (isprimtype_(resulttype, s_void) ? typespecmap_(resulttype) & CVBITS : isprimtype_(princtype(resulttype), s_void)) cc_rerr(syn_rerr_qualified_void); } } static void fixup_fndef(DeclRhsList *temp, Binder *mbind) { TypeExpr *fntype = temp->decltype; DeclRhsList *fnpars = typefnargs1_(fntype); CheckReturnType(fntype); if (LanguageIsCPlusPlus) { /* current_member_scope is uncomfortable as a static reference. */ /* mbind is set if the declaration had a '::', e.g. friend A::f(). */ SET_BITMAP memflags = mbind ? bindstg_(realbinder_(mbind)) & MEMFNBITS : 0; temp->declstg |= memflags; if (memflags & b_memfna) memfn_typefix(temp, mbind ? bindparent_(mbind) : current_member_scope()); } if (curlex.sym != s_lbrace && curlex.sym != s_colon) { if (feature & FEATURE_WARNOLDFNS) cc_warn(syn_warn_old_style, temp->declname); } else { if ((feature & (FEATURE_PCC|FEATURE_FUSSY)) == (FEATURE_PCC|FEATURE_FUSSY)) /* @@@ The next line considers f(){} ANSI only! */ cc_warn(syn_warn_ANSI_decl, symname_(temp->declname)); } /* Next additional C++ could sensibly be done for C as f(...) is */ /* illegal in C. The ellipsis will have set oldstyle==0 anyway. */ /* This old PCC-compatibility code could be tidied too. */ if (!fntypeisvariadic(fntype)) { if (fnpars == 0) { maxargs_(fntype) = 0; if (!(feature & FEATURE_PCC)) /* treat f() {} as f(void) {} in ANSI mode... */ typefnaux_(fntype).oldstyle = 0; } } temp->declstg |= b_fnconst; } static void fixup_fndecl(DeclRhsList *temp, Binder *mbind) { CheckReturnType(princtype(temp->decltype)); if (LanguageIsCPlusPlus) { /* current_member_scope is uncomfortable as a static reference. */ /* mbind is set if the declaration had a '::', e.g. friend A::f(). */ SET_BITMAP memflags = mbind ? bindstg_(realbinder_(mbind)) & MEMFNBITS : 0; temp->declstg |= memflags; if (memflags & b_memfna) memfn_typefix(temp, mbind ? bindparent_(mbind) : current_member_scope()); } temp->declstg |= b_fnconst|b_undef; /* really 999 can't happen in C++, but leave this in for a bit. */ if (maxargs_(princtype(temp->decltype)) == 999) { if (warn_deprecated) /* The follow warning enables us to root out */ /* insecurities/errors of the form: */ /* extern f(); g() { f(1); } f(int x,int y) {...} */ cc_warn(syn_warn_give_args, symname_(temp->declname)); else xwarncount++; } } static void rd_declrhs_exec(DeclRhsList *d, int declflag, bool cppinit, Binder *mbind) { int initflag = 0; bool haveinit = NO; int scope_level = 0; Expr *dyninit = 0; push_exprtemp_scope(); /* this wraps up any potential mkcast not invoked under a rd_expr(). */ if (d->declstg & (bitofstg_(s_extern)|bitofstg_(s_static)|b_globalregvar)) d->declstg |= b_undef; if (curlex.sym == s_assign || archaic_init(curlex.sym) || (LanguageIsCPlusPlus && /* 'cppinit' is true when e.g. int a(3) and we have read the '('. */ /* @@@ C++ rules should be more severe than this... */ (cppinit || (!(d->declstg & bitofstg_(s_extern)) || d->declstg & b_implicitstg) && typehasctor(d->decltype))) ) /* Extern init only at TOPLEVEL. Static init at AUTO scope too: */ { haveinit = YES; if (((d->declstg & bitofstg_(s_extern)) && !(declflag & TEMPLATE) && (declflag & TOPLEVEL)) || (d->declstg & bitofstg_(s_static))) { d->declstg &= ~b_undef; } if (d->declstg & b_fnconst) { cc_rerr(syn_rerr_fn_ptr1, d->declname); d->decltype = ptrtotype_(d->decltype); d->declstg &= ~(b_fnconst | b_undef); } } /* Fault: template <...> class A {...} x; etc. A less clear case is */ /* template <...> typedef class A {...} B, *C; */ /* where C is unreasonable but arguably B is OK. */ /* Beware: control flow is nasty in the following (share more code). */ /* FW: the above is not strictly true. It's OK to say, */ /* template <class T> class A<T>::x; */ if (declflag & TEMPLATE && !(isclasstype_(d->decltype) || (!(d->declstg & bitofstg_(s_typedef)) && isfntype(d->decltype))) && (curlex_member == NULL || (bindstg_(curlex_member) & bitofstg_(s_static)))) { cc_rerr(syn_err_template_notclassorfunction); /* Note the above allows the function via a typedef. OK? */ if (cppinit) (void)rd_exprlist_opt(); else if (curlex.sym == s_assign) { nextsym(); syn_initdepth = 0, syn_initpeek = 0, (void)syn_rdinit(0,0,4); } /* pop_scope(scope_level); ??? */ /* @@@ we should probably kill gen_reftemps() here. */ return; } /* do the next line AFTER above type patching but before reading possible initialiser. Save Binder in ->declbind. d->declstg now always has b_undef for statics & externs if there is no initialiser to read. instate_declaration removes for local statics not going in bss. */ d->declbind = instate_declaration(d, declflag); if (LanguageIsCPlusPlus) { if ((declflag == (TOPLEVEL|SPECIALIZE)) && (curlex_scope != NULL)) { tagbindbits_(curlex_scope) |= TB_SPECIALIZED; if (isfntype(d->decltype)) bindstg_(d->declbind) &= ~bitofstg_(s_inline); } scope_level = push_multi_scope(curlex_scope); if (declflag & ANONU) instate_anonu_members(declflag, d->declbind); if (cppinit) { /* Only happens when (curlex.sym != s_rpar). */ ExprList *init = rd_exprlist_opt(); /* /* overkill for 'const int k(5);' and 'const int& r(k);' */ dyninit = mkctor_v((Expr *)d->declbind, init); initflag = 3; } else if (!(d->declstg & bitofstg_(s_typedef)) && (!(d->declstg & bitofstg_(s_extern)) || d->declstg & b_implicitstg || curlex.sym == s_assign)) { syn_initdepth = 0; dyninit = rd_declrhs_exec_cpp(d, &initflag); } } if (initflag == 0 && (curlex.sym == s_assign || archaic_init(curlex.sym))) { haveinit = YES; if (d->declstg & (bitofstg_(s_auto)|bitofstg_(s_static)) || (d->declstg & (bitofstg_(s_extern)|b_undef)) == (bitofstg_(s_extern))) initflag = 1; else cc_err(syn_err_cant_init, d->declstg), initflag = 2; if (archaic_init(curlex.sym)) cc_pccwarn(syn_rerr_archaic_init); else nextsym(); } #ifdef CPLUSPLUS if (LanguageIsCPlusPlus && !haveinit && !(d->declstg & (b_undef|bitofstg_(s_typedef)))) { TypeExpr *t = princtype(d->decltype); if (!(isclasstype_(t) || (isarraytype(t, &t) && isclasstype_(t)))) { if (h0_(t) == t_ref) cc_rerr(syn_rerr_ref_not_initialised, d->declbind); if (qualifiersoftype(d->decltype) & bitoftype_(s_const)) cc_rerr(syn_rerr_const_not_initialised, d->declbind); } } #endif if (initflag == 2) syn_initdepth = 0, syn_initpeek = 0, (void)syn_rdinit(0,0,4); syn_initdepth = (initflag == 1) ? 0 : -1; syn_initpeek = 0; if (dyninit != NULL && declflag & TEMPLATE && declflag & TOPLEVEL && d->declstg & (bitofstg_(s_extern)|b_implicitstg)) { /* file scope template static data member definition */ if (h0_(dyninit) != s_init) syserr("init expr expected for dyninit"); bindconst_(d->declbind) = globalize_expr(skip_invisible_or_cast(arg2_(dyninit))); } else declinit_(d) = genstaticparts(d, (declflag & TOPLEVEL) != 0, initflag != 1, dyninit); add_expr_dtors(killexprtemp()); if (declinit_(d) != NULL) declinit_(d) = exprtemp_killer(declinit_(d)); /* Missing init expr & non-null edtor can never happen; however, genstaticparts() maps a previous error to a missing expr. In this case edtor can be safely ignored. Moreover, operations involving t_unknown will eventually result in errornode to prevent code generation. */ if (declinit_(d)) attributes_(d->declbind) |= A_DYNINIT; /* The positioning of the next line is subject to some debate */ /* -- I put it here so that the line number is exact, but */ /* note that (a) TOPLEVEL vars are done in vargen.c, */ /* (b) LOCAL vars BLOCKHEAD|FORMAL are not yet complete in */ /* that we have not yet decided on their eventual storage; */ /* this is done by dbg_scope(). See other dbg_locvar() call. */ if (usrdbg(DBG_VAR) && (declflag & BLOCKHEAD)) dbg_locvar(d->declbind, d->fileline); if (LanguageIsCPlusPlus) { pop_scope(scope_level); if (declflag & TOPLEVEL) gen_reftemps(); } IGNORE(mbind); } /* but for its size rd_declrhslist() would be part of rd_decl() maybe it will become so anyway! It reads any of K&R's "(last part of undefined category)type-decl-list(see function-body)", "init-declarator-list" or "struct-declarator-list" */ static bool topfnflag; /* extra result of rd_declrhslist() */ static TagBinder *topfnscope; /* ditto (temp?) */ static Symstr *unmangledfnname; /* ditto, only valid if topfnflag */ static DeclRhsList *syn_formals; /* rd_declrhslist()+rd_fndef() only. */ static ScopeSaver syn_formaltags; /* A marker for deferred binding of default argument expressions... */ static Binder deferred_default_arg_expr = {s_binder, 0, 0, 0, A_GLOBALSTORE}; static DeclRhsList *rd_declrhslist(const DeclSpec *ds, const int declflag, ScopeSaver template_formals) { DeclRhsList *p,*q; const SET_BITMAP ss = ds->stg; TypeSpec *const tt = ds->t; /* note - do NOT change ss, tt or declflag since used in loop below */ for (p = q = 0; ;) /* 3 exits - all 'return's */ { DeclRhsList *temp = mkDeclRhsList(0, 0, ss); bool cppinit = 0; Binder *mbind = 0; /* MEMFNBITS */ NoteCurrentFileLine(&temp->fileline); declstgval_(temp) = ds->stgval; if ((declflag & MEMBER) && curlex.sym == s_colon) temp->decltype = tt; /* anon. bit field: 0 declaree */ /* anon unions only happen when a ';' follows -- invent a name. */ else if (declflag & ANONU) temp->decltype = tt, temp->declname = gensymval(1); else { int varlevel = -1; if (declflag & TEMPLATE) varlevel = push_var_scope(template_formals, Scope_TemplateArgs); temp->decltype = rd_declarator(declflag, tt, &ds->fnaux, ds->stg); if (declflag & TEMPLATE) { if (declflag & MEMBER || curlex.sym == s_lbrace) pop_scope_no_check(varlevel); else pop_scope(varlevel); } if (temp->decltype == 0) { /* error in rd_declarator already reported */ if (declflag & TOPLEVEL) bind_scope = TOPLEVEL; while (curlex.sym!=s_lbrace && curlex.sym != s_rbrace && curlex.sym!=s_semicolon && curlex.sym!=s_eof) nextsym(); if ((declflag & TOPLEVEL) && curlex.sym == s_rbrace) nextsym(); topfnflag = 0; return p; /* return decls so far to recover */ } /* <<< dying */ if (h0_(temp->decltype) == t_coloncolon) syserr("rd_declarator(::)"); cppinit = declarator_init; mbind = declarator_mbinder; temp->declname = declarator_name; /* 2nd result */ if (!(declflag & TOPLEVEL) && (declarator_qscope != 0) && (!(declflag & MEMBER) || !(ss & bitofstg_(s_friend)) && (declarator_qscope != current_member_scope()))) cc_rerr(syn_rerr_declaree_out_of_scope, declarator_qscope, declarator_name); } if (declflag & (FORMAL|TFORMAL|ARG_TYPES|CATCHER)) temp->decltype = modify_formaltype(temp->decltype); /* transform f() -> (*f)() and a[] -> *a */ /* these get seen by all - even the CG. */ defaultstorageclass(temp,declflag, mbind); /* AM: because f(void) is OK, but not f(void, int), checks on the */ /* use of 'void' in parameter lists are postponed to rd_formals(). */ /* Other incomplete types (like struct t) are done there too. */ /* However, it might be nice for early reporting to fault some cases */ /* here (e.g. named void parameters). See fault_incomplete_formals(). */ if (!(declflag & (FORMAL|TFORMAL)) && !(temp->declstg & bitofstg_(s_typedef))) temp->decltype = fault_incomplete_type_object( temp->decltype, temp->declname, (declflag & MEMBER) != 0, temp->declstg); if (h0_(temp->decltype) == t_fnap) /* but NOT via typedef */ { if ((typeptrmap_(temp->decltype) & CVBITS) && ((mbind != 0) ? (bindstg_(mbind) & b_memfns) : ((temp->declstg & bitofstg_(s_static)) || !(declflag & MEMBER)))) { cc_rerr(syn_rerr_no_quals_allowed); typeptrmap_(temp->decltype) &= ~ CVBITS; } /* see if the fn declaration is a fn definition, we have */ /* already (in rd_formals()) changed f(void) to f() */ /* Allow also in MEMBER's -- only reach here if CPLUSPLUS */ if (declflag & (TOPLEVEL|MEMBER) && /* top level or class */ p == 0 && /* first in list */ !(temp->declstg & bitofstg_(s_typedef)) && !cppinit && /* not typedef and suitable following symbol... */ /* (CPLUSPLUS use of s_colon.) */ (curlex.sym == s_lbrace || curlex.sym == s_colon || /* olde-style C "void f(x) type x; {...}": */ /* @@@ it would improve error recovery if we refuse extern here. */ /* Note also that "int A::f() const;" shouldn't come here. */ (declflag & TOPLEVEL && (rd_type_name(), isdeclstarter2_(curlex))))) { fixup_fndef(temp, mbind); /* MEMFNBITS */ unmangledfnname = temp->declname; /* move the next few lines to fixup_fndef? */ if (declflag & MEMBER) { Binder *b; ensure_formals_typed(typefnargs1_(temp->decltype), 1); temp->declstg |= bitofstg_(s_inline); b = instate_member(temp, (declflag & TEMPLATE)|bind_scope); temp->declbind = b; /* used? */ /* 'b' may either be a Binder for a member function or a realbinder_() */ /* for a friend (or friend member) function: */ if (bindstg_(b) & b_impl) b = realbinder_(b); if (h0_(b) != s_binder) syserr("rd_declrhslist(inline $b)", b); temp->declstg &= ~b_undef; temp->declstg |= bindstg_(b) & MEMFNBITS; temp->declname = bindsym_(b); if (declflag & TEMPLATE) { if (bindformals_(temp->declbind)) { merge_default_template_args(template_formals, NULL, temp->declbind); bindformals_(temp->declbind) = template_formals; } else { bindformals_(temp->declbind) = template_formals; merge_default_template_args(template_formals, NULL, temp->declbind); } } } else fault_incomplete_formals(typefnargs1_(temp->decltype), 1); /* @@@ not yet right for friends?? */ if (mbind) topfnscope = bindparent_(mbind); else topfnscope = 0; topfnflag = 1; /* @@@@@@ Why is return (instead of fn call) a good idea here???? */ return temp; } /* ANSI C disallows 'extern f(a,b);' (types needed).: */ ensure_formals_typed(typefnargs1_(temp->decltype), 1); /* drop through into next 'if'... */ } #define FNSTGBITS \ (bitofstg_(s_friend)|bitofstg_(s_inline)|bitofstg_(s_virtual)) if (isfntype(temp->decltype)) /* possibly via typedef */ fixup_fndecl(temp, mbind); /* MEMFNBITS */ /* The following two lines anticipate __inline for ANSI C; */ /* otherwise they would be #ifdef CPLUSPLUS. */ else if (temp->declstg & FNSTGBITS) { cc_rerr(syn_rerr_ignored_non_fn, temp->declstg & FNSTGBITS, temp->declname); temp->declstg &= ~FNSTGBITS; } if (declflag & ARG_TYPES) /* special code to save up info */ { DeclRhsList *p; /* instate_decl is called later */ Symstr *sv = temp->declname; for (p = syn_formals; p != 0; p = p->declcdr) if (sv == p->declname) { merge_formal_decl(p,temp); /* update syn_formals */ break; } if (p==0) cc_err(syn_err_not_a_formal, sv); } if (declflag & (TOPLEVEL|BLOCKHEAD)) { rd_declrhs_exec(temp, declflag, cppinit, mbind); if (declflag & TEMPLATE && temp->declbind) { if (bindformals_(temp->declbind)) { merge_default_template_args(template_formals, NULL, temp->declbind); bindformals_(temp->declbind) = template_formals; } else { bindformals_(temp->declbind) = template_formals; merge_default_template_args(template_formals, NULL, temp->declbind); } } } /* all the same whether type-para or not; needs a holder anyway in case there is default. */ if (declflag == TFORMAL && temp->declname == NULL) temp->declname = gensymval(YES); if ((declflag & (TFORMAL|FORMAL)) && (temp->declname != 0)) { if (declflag & TFORMAL) { if (isprimtypein_(temp->decltype, bitoftype_(s_double))) /* float has been transformed to short double by now? */ cc_err(sem_err_temp_type_float); /* non-type parameter has no storage */ if (h0_(temp->decltype) != t_unknown) temp->declstg = 0; } temp->declbind = instate_declaration(temp, (declflag & TFORMAL) ? declflag|GLOBALSTG : declflag); } if (LanguageIsCPlusPlus) { if (declflag & MEMBER && curlex.sym == s_assign) { Expr *e; /* parse "virtual f() = 0;" */ TagBinder *mem_scope = current_member_scope(); nextsym(); /* if statement below is used rather than ?: due to Watcom C32 v9.5 problem */ if (curlex.sym == s_lbrace) e = 0; else e = rd_expr(UPTOCOMMA); if (temp->declstg & bitofstg_(s_virtual) && e != 0 && ispurefnconst(e)) { tagbindbits_(mem_scope) |= TB_ABSTRACT; temp->declstg |= b_purevirtual; } else cc_err(syn_err_member_cannot_init, temp->declname); } if (declflag & (TFORMAL|FORMAL) && curlex.sym == s_assign) { nextsym(); if (declflag & TFORMAL) { ExprList *a = rd_template_actuals(NO); if (a != NULL && h0_(exprcar_(a)) != s_evalerror) { Expr *e = globalize_expr(exprcar_(a)); if (declflag & TEMPLATE) { Binder *b; if (!isclasstype_(ds->t)) syserr("what sort of template type is this?"); b = findbinding(tagbindsym_(typespectagbind_(ds->t)), NULL, LOCALSCOPES); if (!b) syserr("missing template typedef"); bindconst_(b) = e; } else { if (temp->declbind == NULL) syserr("missing declbind"); bindconst_(temp->declbind) = e; } } } else { Expr *init; /* parse "void f(int x = 42);" */ TagBinder *tb; ensure_formals_typed(temp, 1); /* Non-member function default arguments are bound at their point of */ /* declaration. Member function default arguments are bound at the end */ /* of the class declaration (by cpp_endstrdecl()). We treat friends as */ /* members for this purpose... the standard is unclear... */ if ((tb = current_member_scope()) == 0 || !(tagbindbits_(tb) & TB_BEINGDEFD)) { /* AM is now of the opinion that the following code (and similar code */ /* in mkfnap()) to widen_formaltype() is somewhat wrong-minded. */ /* It means that "void f(char); void g() { f(257); }" is treated */ /* differently from the similar "char x = 257". Maybe we should defer */ /* some of this code to cg.c. */ SynBindList *bl = NULL; TypeExpr *t; push_saved_temps(synscopeid); push_exprtemp_scope(); init = optimise0(mkcast(s_fnap, rd_expr(UPTOCOMMA), (t = widen_formaltype(temp->decltype)))); add_expr_dtors(killexprtemp()); bl = pop_saved_temps(bl); if (init && bl) { init = (!expr_dtors) ? mk_exprlet(s_let, t, bl, init) : mk_exprlet(s_qualified|s_let, t, bl, commacons(init, expr_dtors)); expr_dtors = NULL; extra_flags = NULL; } /* Note that optimise0() on the next line means (1) the top-type may */ /* be incompatible changed (so don't check it again) and moreover that */ /* (2) optimise0() will get called on it again. Hmm @@@. */ /* Add a special 'optimise0'd flag node? */ /* optimise0() maps errornode => NULL; moved above */ /* LDS: 12-Jul-94 - need to globalize here or disaster can ensue... */ declinit_(temp) = (init) ? globalize_expr(init) : NULL; } else /* There are several subtle effects here: 1) we need a hook on which to */ /* to hang the lex token handle; 2) we need an (Expr *) in declinit_() */ /* so that xbind.c::merge_default_arguments() can work correctly... and */ /* 3) we need to mark this Expr as special (with the Binder *)... */ declinit_(temp) = mkintconst(te_int, lex_saveexpr(), (Expr *)&deferred_default_arg_expr); } } } /* @@@ the next comment is for old C implementation -- instating */ /* formals fixes the C bug in 'void f(int a, int (*b)[sizeof a]) {...} */ /* and instating members is invisible to C. @@@ It is out of date. */ /* do not instate formals (or in casts "(int ()(int a,b))foo") nor structure elements. */ if (declflag & MEMBER) { if (curlex.sym == s_colon) { TypeExpr *t = prunetype(temp->decltype); /* NB. The code here is most important -- BITFIELD types have any */ /* typedefs removed with prunetype so that later prunetype/princtype's */ /* (e.g. isbitfield_type()) do not skip over BITFIELD. */ nextsym(); /* declbits holds bit size (= new arg to instate_mem?) */ declbits_(temp) = check_bitsize( rd_expr(UPTOCOMMA), t, temp->declname); temp->decltype = check_bittype(t); } else declbits_(temp) = NULL; temp->declbind = instate_member(temp, (declflag & TEMPLATE)|bind_scope); if (declflag & TEMPLATE && isfntype(temp->decltype)) { if (bindformals_(temp->declbind)) { merge_default_template_args(template_formals, NULL, temp->declbind); bindformals_(temp->declbind) = template_formals; } else { bindformals_(temp->declbind) = template_formals; merge_default_template_args(template_formals, NULL, temp->declbind); } } if (LanguageIsCPlusPlus && (declflag & ANONU)) instate_anonu_members(declflag, temp->declbind); } /* The next line loses all local vars/tags at the end of each TOPLEVEL */ /* declarator. This is still not quite right, but enables vars/tags */ /* to be local to (toplevel) parameter lists. @@@ More fixing required */ /* for parameter lists within parameter lists. */ if (declflag & TOPLEVEL) bind_scope = TOPLEVEL, pop_scope(0); if (p == 0) p = q = temp; else { q->declcdr = temp; q = temp; } if (declflag & (FORMAL|TFORMAL|CATCHER) || curlex.sym != s_comma) { topfnflag = 0; return p; } nextsym(); } } /* AM, Sept 91: memo: too much effort is spent mapping between */ /* DeclRhsList and FormTypeLists, and Binders. @@@ Think. */ /* FormTypeList is now an initial sub-struct of DeclRhsList. */ static TopDecl *rd_fndef(DeclRhsList *d, int declflag, TagBinder *parent, ScopeSaver formaltags, ScopeSaver tformals) /* d has exactly 1 item */ { TypeExpr *fntype = d->decltype; /* known to be fn type */ Binder *fnbind; Cmd *body = NULL; DeclRhsList *fpdecllist = typefnargs1_(fntype), *fpe; SynBindList *lambdap = 0, *lambdaq = 0; SynBindList *narrowformals = 0; Expr *arginit = NULL, *argcopy = NULL; Symstr *sv; int varlevel = 0, scope_level = 0; SynScope *saved_synscope = synscope; synscopeid = 0; synscope = mkSynScope(0, 0, ++synscopeid); sv = currentfunction.symstr = d->declname; if (debugging(DEBUG_FNAMES+DEBUG_CG+DEBUG_CSE+DEBUG_REGS+DEBUG_SR)) cc_msg("Start of function $r\n", currentfunction.symstr); if (LanguageIsCPlusPlus) scope_level = push_multi_scope(parent); else IGNORE(parent); /* The next line re-creates the argument scope -- remember this may not */ /* be the most recently popped scope, e.g. int (*f(int a))(int b){}. */ /* Actually it just makes a scope for instate_declaration below. */ /* This needs weasel-word reading of C++ (no class defs in args). */ varlevel = push_var_scope(formaltags, Scope_Ord); /* when ARG_TYPES is set in declflag any identifiers declared will have */ /* been seen before (as formal parameters) and rd_decllist works by */ /* updating these existing declaration records in a side-effect-full way */ bind_scope = GLOBALSTG; /* local scope for any structs! */ { /* syn_formals is examined by rd_declrhslist if ARG_TYPE is set */ syn_formals = fpdecllist; (void) rd_decllist(ARG_TYPES); } #if 0 if (LanguageIsCPlusPlus) { Symstr *s = d->declname; /* We could also do this for declarations... */ if (symname_(s)[0] == '_' && /* short cut for usual case. */ (s == operator_name(s_assign) || s == operator_name(s_comma) || s == operator_name(s_addrof) && fpdecllist && !fpdecllist->declcdr)) cc_warn(syn_warn_special_ops); /* See [ES, p335], AM adds last two cases (consistency). */ } #endif /* do some checking and defaulting on the arguments and types BEFORE instate_decl ... */ for (fpe = fpdecllist; fpe != 0; fpe = fpe->declcdr) { if (fpe->declname == 0) { if (!LanguageIsCPlusPlus) cc_rerr(syn_rerr_missing_formal); /* not an error in C++ */ /* fixup so we can continue (@@@ soon alter callers)... */ fpe->declname = gensymval(1); } /*if (actualized) fpe->decltype = princtype(fpe->decltype);*/ } ensure_formals_typed(fpdecllist, 0); /* do the declaration of the function - this will copy the types just * updated in fpdecllist as part of globalize_ing the type of d. */ { SET_BITMAP obinduses; FileLine fl; NoteCurrentFileLine(&fl); /* The following pop_scope...() ... push_var_scope() bracketing the */ /* instate_declaration is needed BOTH for C++ and for correct */ /* upscoping of implicitly declared struct tags in argument lists */ /* (and not upscoping when the arg scope becomes the body scope). */ formaltags = pop_scope_no_check(varlevel); fnbind = instate_declaration(d, TOPLEVEL|declflag); /* remanant from primary ex-plunged */ if (declflag == (TOPLEVEL|SPECIALIZE) && !(d->declstg & bitofstg_(s_inline))) bindstg_(fnbind) &= ~bitofstg_(s_inline); /* @@@ bindscope_(fnbind) = dup_template_scope() */ if (declflag & TEMPLATE) { if (bindformals_(fnbind)) { merge_default_template_args(tformals, NULL, fnbind); bindformals_(fnbind) = tformals; } else { bindformals_(fnbind) = tformals; merge_default_template_args(tformals, NULL, fnbind); } (void) push_var_scope(bindformals_(fnbind), Scope_TemplateArgs); } push_var_scope(formaltags, Scope_Ord); obinduses = binduses_(fnbind); if (LanguageIsCPlusPlus) { (void)set_access_context(0, fnbind); /* complete the friend access context */ if (bindstg_(fnbind) & b_impl) fnbind = realbinder_(fnbind); currentfunction.symstr = bindsym_(fnbind); } if (!(declflag & TEMPLATE) && usrdbg(DBG_PROC+DBG_VAR)) { #ifndef NEW_DBG_PROC_INTERFACE /* Perhaps we ought to extend the dbg_proc() interface */ bindparent_(fnbind) = parent; dbg_proc(bindsym_(fnbind), bindtype_(fnbind), (bindstg_(fnbind) & bitofstg_(s_extern)) != 0, fl); bindparent_(fnbind) = NULL; #else dbg_proc(fnbind, parent, (bindstg_(fnbind) & bitofstg_(s_extern)) != 0, fl); #endif } /* @@@ The following comment about re-using store is now a lie. */ /* Now, instate_declaration above globalize_d the d->decltype field (since * all fns are TOPLEVEL beasties). This leaves us free to construct a * BindList of instated formal parameters from the uncopied (local-store) * version fpdecllist above. Start by instantiating the FORMAL's. * This is not so simple as it seems because we have to create new binders * (sharing the same name) for any narrow (char, float, short) formals * and a widened (int, double) binder too. */ for (fpe = fpdecllist; fpe != 0; fpe = fpe->declcdr) { TypeExpr *at = fpe->decltype, *wt = widen_formaltype(at), *pt; Binder *ab, *wb; bool byref = NO; /* lookup/instate the binder with its original type; swap to */ /* wide type later.. */ wb = findbinding(fpe->declname, 0, FB_LOCALS|FB_THISSCOPE); if (wb == 0) wb = instate_declaration(fpe, FORMAL); else bindtype_(wb) = at; ab = wb; pt = princtype(at); if (isclasstype_(pt)) { TagBinder *cla = typespectagbind_(pt); if (TB_NOTPODU_(cla, TB_NEEDSCCTOR)) { /* NOTPOD classes are pased by reference and callee- */ /* copy constructed...; op= is of no concern here */ wt = ptrtotype_(at); byref = YES; } } if (wt != at) /* pointer equality is fine here */ { Expr *e = (Expr *)wb; bindtype_(wb) = wt; if (byref) e = mkunary(s_content, e); #ifndef NARROW_FORMALS_REUSE_ARG_BINDER binduses_(wb) |= u_referenced; { DeclRhsList *narrowedformal = mkDeclRhsList(fpe->declname, at, fpe->declstg); /* do the original binder second so it gets seen first */ ab = instate_declaration(narrowedformal, FORMAL|DUPL_OK); narrowformals = mkSynBindList(narrowformals, ab); } #endif /* make a (reverse) list of copy-constructed arguments */ /* which need to be destroyed on scope exit... */ if (byref) synscope->car = mkSynBindList(synscope->car, ab); /* now narrow types which have been widenend and copy- */ /* construct class types passed by reference... */ /* (separately, to ensure that all narrowing comes first */ /* to make inlining calls to the function easier (all */ /* narrowing in the first block). */ e = mkbinaryorop(s_init, (Expr *)ab, mkcast(s_cast, e, bindtype_(ab))); if (byref) argcopy = argcopy ? mkbinary(s_comma, argcopy, e) : e; else arginit = arginit ? mkbinary(s_comma, arginit, e) : e; } if (fpe == fpdecllist && bindstg_(fnbind) & bitofstg_(s_virtual)) /* Flag 'this' used in virtual member fn (implicit use). */ binduses_(ab) |= u_referenced; if (!LanguageIsCPlusPlus && !(feature & FEATURE_PREDECLARE)) /* preclude any whinge about unused fn args */ /* Allow whinges in C++ since formal names are omittable. */ binduses_(ab) |= u_referenced; if (fpe == fpdecllist) instate_alias(first_arg_sym, wb); if (fpe->declcdr == 0) instate_alias(last_arg_sym, wb); /* The positioning of the next line is subject to some debate */ /* note that (a) TOPLEVEL vars are done in vargen.c, */ /* (b) LOCAL vars BLOCKHEAD|FORMAL are not yet complete in */ /* that we have not yet decided on their eventual storage; */ /* this is done by dbg_scope(). See other dbg_locvar() call. */ /* Further debate whether the user wishes to see the wide */ /* (i.e. entry) arg (wb), which is unchanging, or the narrow, */ /* updatable arg (ab) which is not valid on entry. */ if (usrdbg(DBG_VAR)) { dbg_locvar(ab, fl); } if (lambdap == 0) lambdap = lambdaq = mkSynBindList(0,wb); else lambdaq = lambdaq->bindlistcdr = mkSynBindList(0,wb); } if (syn_reftemps != NULL) syserr("syn_reftemps/rd_fndef"); if (argcopy != NULL) arginit = (arginit != NULL) ? mkbinary(s_comma, arginit, argcopy) : argcopy; { Cmd *argstuff = arginit==0 ? 0 : mk_cmd_e(s_semicolon, syn_invented_fl, optimise0(arginit)); Cmd *precmd = 0, *postcmd = 0; Expr *edtor = 0; Cmd *meminit = 0; SynBindList *initreftemps = 0; bool is_ctor = LanguageIsCPlusPlus && strncmp(symname_(bindsym_(fnbind)), "__ct", 4) == 0; bool is_dtor = LanguageIsCPlusPlus && strncmp(symname_(bindsym_(fnbind)), "__dt", 4) == 0; if (LanguageIsCPlusPlus) /* @@@ we should pass 0 to rd_meminit if not a ctor (bit in bindstg_). */ { TypeExpr *arg1t = bindstg_(fnbind) & b_memfna && lambdap ? bindtype_(lambdap->bindlistcar) : te_int; TypeExpr *arg1s = h0_(arg1t)==t_content ? typearg_(arg1t) : te_int; TagBinder *cl = isclasstype_(arg1s) ? typespectagbind_(arg1s) : 0; int has_core = (attributes_(fnbind) & CB_CGEN) && (cl != 0 && core_class(cl) != cl); synscope = mkSynScope(synscope, 0, ++synscopeid); meminit = rd_meminit(cl, fnbind, lambdap, &precmd, &postcmd); initreftemps = synscope->car; if (is_dtor) { push_exprtemp_scope(); edtor = syn_memdtor(cl, fnbind, lambdap, &precmd); add_expr_dtors(killexprtemp()); if (expr_dtors != NULL) syserr("genexprtemp() used by memdtor"); } if (synscope->car != initreftemps) syserr("genreftemp() used by memdtor"); synscope = synscope->cdr; synscopeid = synscope->scopeid; if (has_core) fnbind = realbinder_(fnbind); } bind_scope = LOCALSCOPE; /* @@@ Warn about templated main?? What does the std say?*/ if (declflag == (TEMPLATE|TOPLEVEL) && bindsym_(fnbind) != mainsym) (void)lex_bodybegin(); body = rd_body(typearg_(fntype), fntype, is_ctor, is_dtor); if (declflag == (TEMPLATE|TOPLEVEL) && bindsym_(fnbind) != mainsym) { bindtext_(fnbind) = lex_bodyend(); #if 0 /* CD2, 14.5.5, para 2 last sentence footnote explicitly prohibit the implicit generation of non-template overloaded function. */ Binder *bgeneric = findbinding(sv, 0, ALLSCOPES); bool has_failed = NO; TypeExpr *t; BindList *bl; int len = length((List *)typefnargs_(bindtype_(fnbind))); ScopeSaver env; if (bgeneric == NULL || h0_(bindtype_(bgeneric)) != t_ovld) syserr("No generic $r", sv); /* first, any b_undef ovld instance requiring instantiation */ for (bl = typeovldlist_(bindtype_(bgeneric)); bl; bl = bl->bindlistcdr) { Binder *b = bl->bindlistcar; FormTypeList *ft = typefnargs_(bindtype_(b)); int len2 = length((List *)ft); ExprList *l = NULL; if (!(bindstg_(b) & b_undef) || len != len2) continue; for (; ft; ft = ft->ftcdr) l = mkExprList(l, gentempbinder(ft->fttype)); env = bindenv_(fnbind); t = type_deduction(bindtype_(fnbind), dreverse(l), NULL, &env, YES, &has_failed); /* For an ovld instance, make sure it's an exact match. */ if (!has_failed) has_failed = !equivtype(t, bindtype_(b)); if (!has_failed && !contains_typevars(t) && (bindstg_(b) & (b_addrof|u_referenced)) && /* check for non template function specific */ !is_an_instance(bindinstances_(fnbind), b)) { if (debugging(DEBUG_TEMPLATE)) cc_msg("generating $r @ $b\n", bindsym_(fnbind), b); env = globalize_env(env); fixup_template_arg_type(t, env); t = globalize_typeexpr(t); /* @@@ unstructured */ bindtype_(b) = t; bindenv_(b) = env; parameter_names_transfer(typefnargs_(d->decltype), typefnargs_(bindtype_(b))); add_pendingfn(sv, NULL, bindtype_(b), bindstg_(b), NULL, bindenv_(b), bindtext_(fnbind), YES); bindstg_(b) &= ~b_undef; } } #endif /* then, instantiates for all b_undef instances */ if (binduses_(fnbind) & u_referenced) { BindList *instances = bindinstances_(fnbind); for (; instances; instances = instances->bindlistcdr) { Binder *b = instances->bindlistcar; int level = push_var_scope(bindformals_(b), Scope_TemplateArgs); bool has_typevar = contains_typevars(bindtype_(b)); pop_scope_no_check(level); if (has_typevar) continue; parameter_names_transfer(typefnargs_(d->decltype), typefnargs_(bindtype_(b))); add_pendingfn(sv, ovld_tmptfn_instance_name(d->declname, bindenv_(b)), bindtype_(b), bindstg_(b), NULL, NULL, bindtext_(fnbind), bindenv_(b), YES); bindstg_(b) &= ~b_undef; if (debugging(DEBUG_TEMPLATE)) cc_msg("generating $r @ $b\n", bindsym_(fnbind), b); } } } bind_scope = TOPLEVEL; if (LanguageIsCPlusPlus) { Expr *bdtor = mkdtor_v_list(synscope->car); if (bdtor) { cmd2c_(body) = (Cmd *) nconc((CmdList *)cmd2c_(body), mkCmdList(0, mk_cmd_e(s_semicolon, fl, optimise0(bdtor)))); } if (meminit) { Expr *idtor = mkdtor_v_list(initreftemps); CmdList *cdtor = idtor == NULL ? 0 : mkCmdList(0, mk_cmd_e(s_semicolon, fl, optimise0(idtor))); body = mk_cmd_block(syn_invented_fl, initreftemps, mkCmdList(mkCmdList(cdtor, body), meminit)); } if (precmd) body = mk_cmd_block(fl, 0, mkCmdList(mkCmdList(0, body), precmd)); if (is_dtor) { LabBind *lab = label_define(dtorgenlabsym); if (lab != NULL) /* not a duplicate label */ { Cmd *edtorcmd; syn_setlab(lab, synscope); lab->labuses |= l_referenced; /* suppress warning if unused */ /* just what is the right FileLine for a dtor? */ edtorcmd = mk_cmd_lab(s_colon, syn_invented_fl, lab, edtor != NULL ? mk_cmd_e(s_semicolon, fl, optimise0(edtor)) : NULL); body = mk_cmd_block(syn_invented_fl, 0, mkCmdList(mkCmdList(0, edtorcmd), body)); } if (!(tagbindbits_(parent) & TB_HASVBASE)) { /* if this class has a core we are actually building the core dtor */ Cmd *cdel = conditionalised_delete(lambdap->bindlistcar, lambdap->bindlistcdr->bindlistcar, parent); body = mk_cmd_block(fl, 0, mkCmdList(mkCmdList(0, cdel), body)); } } if (postcmd) body = mk_cmd_block(fl, 0, mkCmdList(mkCmdList(0, postcmd), body)); } if (argstuff) body = mk_cmd_block(syn_invented_fl, narrowformals, mkCmdList(mkCmdList(0,body), argstuff)); } label_resolve(); pop_scope(scope_level); if (synscope->cdr != 0) syserr("rd_fndef/synscope"); synscope = saved_synscope; if (saved_synscope != 0) synscopeid = saved_synscope->scopeid; /* Remove recursive references. One day improve to consider the whole */ /* of the call graph so unreferenced mutually recursion is warned of. */ binduses_(fnbind) &= ~(~obinduses & u_referenced); if (declflag & TEMPLATE) { DeclRhsList *d = mkDeclRhsList(bindsym_(fnbind), bindtype_(fnbind), 0); d->declbind = fnbind; return (TopDecl *) syn_list2(s_decl, d); } else /* h4_(result) is a flag to indicate the presence of an ellipsis in */ /* the list of formal arguments for this function. */ return mkTopDeclFnDef(s_fndef, fnbind, lambdap, body, /* * Beware !!!. In PCC mode all functions are considered as * Having a trailing '...'. This is activated by the * code in cg.c which checks whether the address of ANY of the * args has been taken. If so all args go to stack !!! */ #ifdef TARGET_HAS_SPECIAL_VARARGS fntypeisvariadic(fntype) #else (fntypeisvariadic(fntype) || (lambdap!=0) && (feature&FEATURE_PCC)) #endif ); } } static ScopeSaver globalize_formaltags(ScopeSaver l) { Binder *h = (Binder *)l; if (h == 0) return 0; bindcdr_(h) = (Binder *)globalize_formaltags((ScopeSaver)bindcdr_(h)); if (h0_(h) == s_binder) h = global_mk_binder(bindcdr_(h), bindsym_(h), bindstg_(h), globalize_typeexpr(bindtype_(h))); return (ScopeSaver)h; } /* rd_decl reads a possibly top-level decl, see also rd_decl2() */ static TopDecl *rd_decl(int declflag, SET_BITMAP accbits) /* AM: Structure decls are tantalisingly close to ordinary decls (but no storage class) except for length specs replacing initialisation. Type specs are compulsory for structure members, but not for vars (e.g. auto a=1;). Read them all them with a single parameterised routine. Note that 'accbits' is or-able with declstg_() (non-zero if MEMBER). @@@ Feb 93: It is in a different bit position from in attributes_()!!! */ { DeclRhsList *d; DeclSpec ds; int declsynflags; ScopeSaver template_formals = NULL; FileLine fl; NoteCurrentFileLine(&fl); if (curlex.sym == s_asm && peepsym() == s_lpar) { Expr *e; if (declflag == TOPLEVEL) cc_err(syn_err_illegal_asm_decl); push_exprtemp_scope(); e = rd_asm_decl(); add_expr_dtors(killexprtemp()); if (expr_dtors != NULL) syserr("exprtemp in asm decl"); if (declflag == TOPLEVEL) return (TopDecl *)errornode; d = mkDeclRhsList(gensymval(0), te_int, bitofstg_(s_auto)); declinit_(d) = e; d->declbind = gentempbinder(te_int); return (TopDecl *) syn_list2(s_decl, d); } if (LanguageIsCPlusPlus) { if (declflag & (TOPLEVEL|BLOCKHEAD|MEMBER)) cur_template_formals = NULL; if (curlex.sym == s_using) { do nextsym(); while (curlex.sym != s_semicolon); return (TopDecl *)errornode; } if (curlex.sym == s_export && peepsym() == s_template) { cc_warn("$l ignored for template"); nextsym(); } while (curlex.sym == s_template) { nextsym(); if (curlex.sym == s_less) { ScopeSaver tmp_temp_formals = NULL; if (declflag & INSTANTIATE) cc_rerr(xsyn_rerr_instantiate_mixup); nextsym(); tmp_temp_formals = rd_template_formals(); if (template_formals == NULL) template_formals = tmp_temp_formals; else { Binder *t = template_formals; while (bindcdr_(t) != NULL) t = bindcdr_(t); bindcdr_(t) = tmp_temp_formals; } cur_template_formals = binder_cons2(cur_template_formals, tmp_temp_formals); declflag |= (tmp_temp_formals != NULL) ? TEMPLATE : SPECIALIZE; } else { if (declflag & (TEMPLATE|SPECIALIZE)) cc_rerr(xsyn_rerr_instantiate_mixup); else { if (declflag & INSTANTIATE) cc_rerr(xsyn_rerr_spurious_instantiate); declflag |= INSTANTIATE; } } } cur_template_formals = (BindList *)dreverse((List *)cur_template_formals); } ds = rd_declspec(declflag, template_formals); if (fpregargs_disabled) ds.fnaux.flags |= f_nofpregargs; if (no_side_effects) ds.fnaux.flags |= bitoffnaux_(s_pure); if (no_tail_calls) ds.fnaux.flags |= f_notailcall; ds.stg |= accbits; /* merge in access bits if C++ MEMBER */ declsynflags = ds.synflags; /* local copy of error check bits. */ if (declflag & TFORMAL && declsynflags & B_IMPLICITINT) { declsynflags &= ~B_IMPLICITINT; ds.t = mk_typevar(); declsynflags |= B_TYPESEEN; } /* extern "C" is ignored for typedefs and statics */ if (LanguageIsCPlusPlus && !(ds.stg & (bitofstg_(s_typedef)|bitofstg_(s_static))) && syn_current_linkage() == LINK_C) ds.stg |= b_clinkage; if (LanguageIsCPlusPlus && declsynflags & B_LINKAGE) { if (declsynflags & B_LINKBRACE) d = 0; /* treat 'extern "x" {' as empty decl. */ else { /* The 'extern "C" typedef int foo();' form. Push back an */ /* 'extern'. We could just dd.stg |= bitofstg_(s_extern) */ /* but we need to fault things like 'extern "C" static ...'.*/ TopDecl *dd; ungetsym(); curlex.sym = s_extern; dd = rd_decl(TOPLEVEL, 0); syn_pop_linkage(); return dd; } } else { if (curlex.sym == s_semicolon && !(declflag & (FORMAL|TFORMAL)) || curlex.sym == s_rbrace && (declflag & MEMBER)) { /* * Found an empty declaration or an empty declaration within a * struct or union in which the terminating ';' has been omitted. */ TypeExpr *t = ds.t; /* no 'princtype(ds.t)' */ if (LanguageIsCPlusPlus && declflag & MEMBER && ds.stg & bitofstg_(s_friend)) { if (!isclasstype_(t)) t = princtype(t); if (isclasstype_(t)) { if (t != ds.t && !(feature & FEATURE_CFRONT)) cc_rerr(syn_err_friend_type); mk_friend_class(typespectagbind_(t), current_member_scope()); } else cc_err(syn_err_friend_type); /* (and not 'enum foo' either, but let's not say this!) */ } else if (LanguageIsCPlusPlus && declflag & (MEMBER|BLOCKHEAD|TOPLEVEL) && !(ds.stg & bitofstg_(s_typedef)) && isprimtype_(t, s_union) && isgensym(bindsym_(typespectagbind_(t))) && tagbindmems_(typespectagbind_(t)) != NULL) { if (declflag & TOPLEVEL && !(ds.stg & bitofstg_(s_static))) { cc_rerr(syn_rerr_global_anon_union); ds.stg = ds.stg & ~STGBITS | bitofstg_(s_static); } declflag |= ANONU; goto anonu; } else if ((declflag & TEMPLATE) && !(isclasstype_(t) || (!(ds.stg & bitofstg_(s_typedef)) && isfntype(t)))) cc_rerr(syn_err_template_notclassorfunction); else if (!(declsynflags & B_DECLMADE)) { if (LanguageIsCPlusPlus) cc_warn(syn_rerr_ineffective); else cc_pccwarn(syn_rerr_ineffective); } else { if (declsynflags & B_STGSEEN) /* e.g. "static struct A {};". */ /* harder error in C++? */ cc_warn(syn_warn_storageclass_no_declarator); /* * Here we have just got a new struct/union/enum tag * so let's tell the debugger about it, lest it never * finds out about it until its too late. */ if (usrdbg(DBG_PROC)) dbg_type(gensymval(1), ds.t, fl); } d = 0; } else anonu: /* what a horrible place to put a label! */ { TagBinder *parent = current_member_scope(); syn_formaltags = 0; /* overzealous safety */ d = rd_declrhslist(&ds, declflag, template_formals); if (d != 0) { d->fileline = fl; if (d->declstg & bitofstg_(s_friend) && !template_formals && d->declbind && is_dependent_type(d->decltype) && tagbindbits_(parent) & TB_TEMPLATE) bindformals_(d->declbind) = tagformals_(parent); } if (declflag == (TOPLEVEL|SPECIALIZE) && parent != NULL) tagbindbits_(parent) |= TB_SPECIALIZED; if (topfnflag) { /* NB. it is vital that when topfnflag is set on return */ /* from rd_declrhslist we must soon pop_varenv/tagenv. */ /* This has to be done after reading the body due to ANSI */ /* scope joining of formals and body top block. */ if (d == NULL) syserr("rd_decl: no top fn"); if (feature & FEATURE_PCC && !(declflag & MEMBER)) implicit_return_ok = syn_oldeformals; if (!(declsynflags & (B_TYPESEEN|B_STGSEEN)) || ((LanguageIsCPlusPlus || !(suppress & D_FUTURE)) && (declsynflags & B_IMPLICITINT))) { if (LanguageIsCPlusPlus) { if (cpp_special_member(d)) { /* nothing */ } else if (suppress & D_IMPLICITINT) cc_warn(syn_warn_untyped_fn, d->declname); else cc_rerr(syn_warn_untyped_fn, d->declname); } else if (suppress & D_IMPLICITVOID) { xwarncount++; /* The next line allows us also to suppress 'implicit return' warning */ /* in f(){}. */ implicit_return_ok = 1; } else cc_warn(syn_warn_untyped_fn, d->declname); } if (LanguageIsCPlusPlus && (declflag & MEMBER)) { if (tagprimary_(parent) != NULL && !(declflag & TEMPLATE) && !(tagbindbits_(parent) & TB_SPECIALIZED)) { if (d->declstg & bitofstg_(s_friend)) { bool done = NO; int braces = 0; /* waste the inline friend defn */ while (!done) switch (curlex.sym) { case s_lbrace: braces++; default: nextsym(); break; case s_rbrace: if (--braces == 0) done = YES; else nextsym(); break; } } else { /* parent is an instantiation. */ /* could share the body of the counterpart in the primary except */ /* for name substitution during an instantiation. */ /* @@@ virtual fns may have to be generated immediately */ add_memfn_template(parent, d->declname, NULL, globalize_typeexpr_no_default_arg_vals(d->decltype), /* @@@ Suppress inlining maybe morally wrong; but ANSI permits since it is only a hint. */ d->declstg & ~bitofstg_(s_inline), parent, /* @@@ the next line gets the wrong bindings in */ /* int (*f(int a))(int b) */ /* and probably if 'a' had a sizeof(struct defn).*/ /* This only affects (C++ illegal) arg-declared */ /* classes currently. */ globalize_formaltags(syn_formaltags), lex_savebody(), bindformals_(d->declbind)); /* Forgery */ bindstg_(d->declbind) |= b_undef; d->declstg |= b_undef; } } else { int h = lex_savebody(); ScopeSaver env = NULL; bool is_template = (tagbindbits_(parent) & TB_TEMPLATE) ? YES : NO; if (declflag & TEMPLATE || (d->declstg & bitofstg_(s_friend) && bindformals_(d->declbind))) { Binder *ftemp = (d->declstg & bitofstg_(s_friend)) ? (parent = NULL, d->declbind) : findbinding(bindsym_(d->declbind), parent, INCLASSONLY); if (ftemp == 0) syserr("missing member/friend template $r", bindsym_(d->declbind)); bindtext_(ftemp) = h; if (!(d->declstg & bitofstg_(s_friend))) bindstg_(ftemp) &= ~b_undef; env = bindformals_(ftemp); is_template = YES; } add_pendingfn((d->declstg & MEMFNBITS) ? d->declname : unmangledfnname, NULL, globalize_typeexpr_no_default_arg_vals(d->decltype), d->declstg, parent, /* @@@ the next line gets the wrong bindings in */ /* int (*f(int a))(int b) */ /* and probably if 'a' had a sizeof(struct defn).*/ /* This only affects (C++ illegal) arg-declared */ /* classes currently. */ globalize_formaltags(syn_formaltags), h, env, is_template); } curlex.sym = s_nothing; /* Just pretend all is sweetness and light 'til later: */ return (TopDecl *) syn_list2(s_memfndef, d); } return rd_fndef(d, declflag, topfnscope, syn_formaltags, template_formals); /* d != 0 by fiat */ } /* ANSI C requires a complaint at top level for "*x;", but not "*f(){}" */ /* This message is a little late, but cannot occur 'on time'. */ /* C++: we might want to warn about more implicit int fns: */ /* e.g. friend f(); virtual g(); static h(); */ if ((!(declsynflags & (B_TYPESEEN|B_STGSEEN)) || ((LanguageIsCPlusPlus || !(suppress & D_FUTURE)) && (declsynflags & B_IMPLICITINT))) && !((declflag & FORMAL) && is_untyped_(d->decltype)) && !(feature & FEATURE_PCC)) { DeclRhsList *x = d; /* the case d==0 has already been reported by rd_declarator/DeclRhslist */ bool complained = false; bool have_needs_type = false; Symstr *first_no_implict_int = NULL; for (; x != NULL; x = x->declcdr) { /* Don't moan about missing type for ctors/dtors/conversion functions */ /* (the test for this should be handled by some form of attribute flag).*/ /* And only warn of omitted type/stgclass for member functions. */ /* errors: 'x, *y, f(), *g();' 'struct { x, *y, f(); };' */ /* warnings from elsewhere: 'f() {} struct { g() {} };' */ /* ok (silent): 'struct T { T(); ~T(); operator int(); };' */ bool needs_type = x->declname == NULL || !cpp_special_member(x); if (needs_type) { have_needs_type = true; if (first_no_implict_int == NULL) first_no_implict_int = x->declname; } if (LanguageIsCPlusPlus && (declflag & MEMBER)) { if (needs_type) { #if CFRONT_MODE_WARN_LACKS_STORAGE_TYPE /* Cfront allows any member function decl */ /* to have implicit int return type. But the */ /* Newton sources do not need this. */ if (isfntype(x->decltype) && (feature & FEATURE_CFRONT)) cc_warn(syn_warn_lacks_storage_type, x->declname); else #endif /* CFRONT_MODE_WARN_LACKS_STORAGE_TYPE */ if (suppress & D_IMPLICITINT) cc_warn(syn_warn_lacks_storage_type, x->declname); else cc_rerr(syn_warn_lacks_storage_type, x->declname); complained = true; } } else if (!(declsynflags & (B_TYPESEEN|B_STGSEEN))) { cc_rerr(syn_warn_lacks_storage_type, x->declname); complained = true; } } if (!complained && have_needs_type && (declsynflags & B_IMPLICITINT)) { if (LanguageIsCPlusPlus && !(suppress & D_IMPLICITINT)) { if (first_no_implict_int != NULL) cc_rerr(syn_rerr_missing_type_for, first_no_implict_int); else cc_rerr(syn_rerr_missing_type); } else if (LanguageIsCPlusPlus || !(suppress & D_FUTURE)) { if (first_no_implict_int != NULL) cc_warn(syn_rerr_missing_type_for, first_no_implict_int); else cc_warn(syn_rerr_missing_type); } } } } if (!(declflag & (FORMAL|TFORMAL|CATCHER))) { if (!(feature & FEATURE_PCC) || curlex.sym != s_rbrace) checkfor_delimiter_2ket(s_semicolon, s_comma); } } return (TopDecl *) syn_list2(s_decl, d); } /* rd_decl2() reads a 'decl-specifiers-opt declarator-list;' decl. */ /* 'declflag' is FORMAL, TFORMAL, BLOCKHEAD, ARG_TYPES or CATCHER. */ static DeclRhsList *rd_decl2(int declflag, SET_BITMAP accbits) { TopDecl *d; if (curlex.sym == s_asm && declflag != BLOCKHEAD) cc_err(syn_err_illegal_asm_decl); d = rd_decl(declflag, accbits); if (declflag & BLOCKHEAD) { DeclRhsList *dp = d->v_f.var; for (; dp; dp = dp->declcdr) if (dp->declbind) synscope->car = mkSynBindList(synscope->car, dp->declbind); } if (h0_(d) != s_decl) syserr(syserr_rd_decl2, d, (long)h0_(d)); return d->v_f.var; } /* rd_formals_2() is only used once in rd_formals_1(). It behaves */ /* very much like rd_decllist, but different concrete syntax. */ /* It copes with both ANSI and olde-style formals (and now C++). */ /* @@@ sort out the 999/1999 confusion. */ static DeclRhsList *rd_formals_2(void) { DeclRhsList *p,*q,*temp; if (curlex.sym == s_rpar) { if (LanguageIsCPlusPlus) syn_minformals = 0, syn_maxformals = 0, syn_oldeformals = 0; else syn_minformals = 0, syn_maxformals = 999, syn_oldeformals = 1; return 0; } for (p = q = 0;;) { if (curlex.sym == s_ellipsis) { if (!LanguageIsCPlusPlus && p == 0) cc_rerr(syn_rerr_ellipsis_first); fault_incomplete_formals(p,0); nextsym(); /* @@@ what about int f(int x, int y = 2, ...)? */ /* Answer f(1), f(1,3), f(1,3,4) all OK. */ syn_minformals = length((List *)p); syn_maxformals = 1999; /* @@@ remove the 999/1999 hack */ syn_oldeformals = !is_proto_arglist(p,1); return p; /* to checkfor_ket(s_rpar) */ } if (LanguageIsCPlusPlus) chk_for_auto = YES; temp = rd_decl2(FORMAL, 0); if (LanguageIsCPlusPlus) chk_for_auto = NO; if (curlex.sym == s_nothing) nextsym(); for (; temp != 0; temp = temp->declcdr) { if (debugging(DEBUG_BIND)) cc_msg(" Formal: $r\n", temp->declname); if (p == 0) p = q = temp; else q->declcdr = temp, q = temp; } if (LanguageIsCPlusPlus && curlex.sym == s_ellipsis) continue; /* can omit comma */ else /* all that should legally appear here are ',' and ')', but fix */ /* ';' as ',' a la pascal and treat all other symbols as ')' to be */ /* faulted by the caller (rd_declarator_1()). */ if (curlex.sym == s_semicolon) /* error recovery */ cc_rerr(syn_rerr_semicolon_in_arglist); else if (curlex.sym != s_comma) { /* arg list end, but first check for ANSI "(void)" argument list * and remove it. Note that "f(void) {}" is also OK by ANSI * if somewhat curious. */ bool b = is_proto_arglist(p,0); if (p != 0 && p->declcdr == 0 && /* 1 parameter */ p->declname == 0 && /* no name */ isprimtype_(p->decltype, s_void)) /* void (or typedef) */ #if 0 /* was equivtype(p->decltype, te_void) */ #endif p = 0; /* then clear arglist */ fault_incomplete_formals(p,0); syn_maxformals = length((List *)p); syn_minformals = length((List *)p); syn_oldeformals = !b; return p; } nextsym(); } } static Declarator *rd_formals_1(Declarator *a, const DeclFnAux *fnaux) { int old_bind_scope = bind_scope; int scope_level = push_scope(0, Scope_Args); SET_BITMAP quals = 0; DeclRhsList *f; TypeExprFnAux s; Declarator *d; if (bind_scope == TOPLEVEL) bind_scope = GLOBALSTG; /* @@@ nasty */ f = rd_formals_2(); bind_scope = old_bind_scope; /* @@@ beware: this gets tags from the wrong scope in things like */ /* void (*f(struct a { } x))(struct b { } y); Banned in C++ anyway. */ syn_formaltags = pop_scope_no_check(scope_level); checkfor_2ket(s_rpar, s_comma); /* careful with C++ archaism: int f(x) const int *x; { ... } */ if (LanguageIsCPlusPlus && !syn_oldeformals) { quals = rd_onceonlyquals(CVBITS); rd_exception_spec(); } /* @@@ beware that ANSI disallow the use of pragma's which change */ /* semantics -- those for printf requesting extra warnings are ok, but */ /* not those like 'no_side_effects' which can screw code. */ /* extra results for minargs_(), maxargs_()... */ d = mkTypeExprfn(t_fnap, a, quals, (FormTypeList *)f, packTypeExprFnAux1(s, (int)syn_minformals, (int)syn_maxformals, (int)special_variad, syn_oldeformals, fnaux->flags, fnaux->val)); if (fntypeisvariadic(d)) typefnaux_(d).flags |= f_nofpregargs; return d; } static DeclRhsList *rd_decllist(int declflag) /* reads a list of Decls and NCONC's them togther. Used for struct/union elements, type specs after formal lists, rd_block(). NB: It should not be used when TOPLEVEL is set as it does not look for functions. It should not be used either when MEMBER is set (no 'accbits' facility). Identical to rd_formals modulo concrete syntax - unify??? Note the Symstr's may be 0 (abstract), or s_id. */ { DeclRhsList *p,*q,*temp; p = q = 0; while (rd_type_name(), (declflag & BLOCKHEAD ? isdeclstarter3_(curlex) : isdeclstarter2_(curlex))) { if (curlex.sym == s_typestartsym) nextsym(); temp = rd_decl2(declflag, 0); if (curlex.sym == s_nothing) nextsym(); for (; temp != 0; temp = temp->declcdr) { if (p == 0) p = q = temp; else q->declcdr = temp, q = temp; if (debugging(DEBUG_BIND)) cc_msg(" Identifier: $r", q->declname); } } return p; } static void rd_strdecl(TagBinder *b, ClassMember *bb) { int nameseen = 0; int old_bind_scope = bind_scope; access = tagbindbits_(b) & bitoftype_(s_class) ? s_private : s_public; if (LanguageIsCPlusPlus) { if (bind_scope == TOPLEVEL) bind_scope = GLOBALSTG; /* @@@ nasty */ /* the next line is a bit of a hack -- it enables findclassmember */ /* to work while reading members. See cppfe.c.bind("p209"). */ /* See also 'derived_from' below. */ tagbindmems_(b) = bb; } { int scope_level = push_scope(b, Scope_Ord); TagBinder *old_access = set_access_context(b, 0); for (;;) { if (isaccessspec_(curlex.sym)) { access = curlex.sym; nextsym(); checkfor_ket(s_colon); continue; /* class A { public: private: }; is OK. */ } rd_type_name(); if (LanguageIsCPlusPlus && (curlex.sym == s_qualified+s_identifier || curlex.sym == s_qualified+s_pseudoid) && (peepsym()==s_semicolon || peepsym()==s_comma || peepsym()==s_rbrace)) { rd_access_adjuster(b, access); } else if (isdeclstarter2_(curlex) /* Additional C++ (odd!) ways for a member declaration to start... */ /* ... since the 'type' info is optional (sigh): */ || (curlex.sym & ~s_qualified) == s_identifier || (curlex.sym & ~s_qualified) == s_pseudoid || curlex.sym == s_lpar || curlex.sym == s_bitnot || (curlex.sym & ~s_qualified) == s_times || curlex.sym == s_and || curlex.sym == s_colon /* e.g. class A{:32}; */ || curlex.sym == s_semicolon || curlex.sym == s_template) { TopDecl *td; DeclRhsList *d; if (curlex.sym == s_typestartsym) nextsym(); td = rd_decl(MEMBER, stgaccof_(access)); /* using the DeclRhsList from rd_decl is now deprecated (we should */ /* really look in tagbindmems_(b) to make nameseen). */ if (td == 0 || !(h0_(td) == s_decl || h0_(td) == s_memfndef)) syserr(syserr_rd_decl2, td, (long)(td==0 ? 0 : h0_(td))); for (d = td->v_f.var; d != 0; d = d->declcdr) nameseen |= d->declname != NULL ? 2 : 1; if (curlex.sym == s_nothing) nextsym(); /* Optional semicolon after member function definition: */ if (h0_(td) == s_memfndef && curlex.sym == s_semicolon) nextsym(); } else break; } if (LanguageIsCPlusPlus) cpp_end_strdecl(b); pop_scope(scope_level); (void)set_access_context(old_access, 0); if (LanguageIsCPlusPlus) bind_scope = old_bind_scope; switch (nameseen) { case 1: cc_warn(syn_warn_no_named_member, b); break; case 0: if (!LanguageIsCPlusPlus) cc_rerr(syn_rerr_no_members, b); break; } } } static void rd_classdecl_(TagBinder *b) { if (LanguageIsCPlusPlus) { TagBinder *class_scope = syn_class_scope; syn_class_scope = b; rd_classdecl(b); syn_class_scope = class_scope; } else { nextsym(); rd_strdecl(b, NULL); } } /* rd_enumdecl() works very much like rd_decllist() or rd_strdecl() but the different surface syntax leads me to implement it separately. Syntax is taken from Harbison&Steele. ANSI draft means 'int' implementation of 'enum's. This doesn't yet handle C++ enums that need to be long or unsigned long (only happens when sizeof_int < sizeof_long). */ static void rd_enumdecl(TagBinder *tb) { TypeExpr *t = tagbindtype_(tb); BindList *p = 0, *q = 0; int32 nextenumval = 0; int32 minval = 0, maxval = 0; bool has_neg = NO, needs_unsigned = NO, is_non_neg = YES; nextsym(); if (curlex.sym == s_comma && (feature & FEATURE_CFRONT)) { cc_warn(syn_warn_extra_comma); nextsym(); } if (!LanguageIsCPlusPlus || /* Can't have empty enumerations in C */ curlex.sym != s_rbrace) /* """""""""""""""""""""""" */ for (;;) { if (curlex.sym == s_identifier) { Symstr *sv = curlex.a1.sv; Expr *e = 0; Binder *b; DeclRhsList *temp = mkDeclRhsList(sv, t, b_enumconst); nextsym(); if (curlex.sym == s_assign) { nextsym(); e = optimise0(coerceunary(rd_expr(UPTOCOMMA))); } /* @@@ AM: fixup 16 bit ints here too. */ if (e != 0) { bool ok = NO; if (h0_(e) == s_int64con) { uint32 u; if (!(int64map_(e) & bitoftype_(s_unsigned))) { int32 n; if (I64_SToI(&n, &int64val_(e).i) == i64_ok) { nextenumval = n; ok = YES; is_non_neg = n >= 0; } } if (!ok && I64_UToI(&u, &int64val_(e).u) == i64_ok) { nextenumval = u; ok = YES; is_non_neg = YES; } } if (!ok) { nextenumval = evaluate(e); is_non_neg = (h0_(e) == s_integer && typespecmap_(princtype(type_(e))) & bitoftype_(s_unsigned) || nextenumval >= 0); } } /* bind_scope is set so that all enum consts are globalized except in fns */ /* The following instate_declaration can behave like instate_member?! */ /* In case of an instantiation, make it global (better still at the same scope as the primary). */ b = instate_declaration(temp, (tagparent_(tb) != NULL && tagprimary_(tagparent_(tb)) != NULL) ? bind_scope|GLOBALSTG : bind_scope); binduses_(b) |= u_referenced; bindparent_(b) = tagparent_(tb); attributes_(b) |= bitofaccess_(access); if (nextenumval < 0) { if (is_non_neg) { if (LanguageIsCPlusPlus) { needs_unsigned = YES; /* we need to set the container type right away in case */ /* of 'enum { k1 = ~0u, k2 = k1 | 1 };' */ tagbindbits_(tb) = (tagbindbits_(tb) & ~TB_CONTAINER) | TB_CONTAINER_UINT; } else { is_non_neg = NO; /* only one error. */ cc_rerr(sem_rerr_monad_overflow(s_enum,0,0)); } } else has_neg = YES; } if (p == 0) minval = maxval = nextenumval; else { if (nextenumval < minval) minval = nextenumval; if (nextenumval > maxval) maxval = nextenumval; } bindaddr_(b) = nextenumval++; /* BEWARE: reuse of DeclRhsList to hold ClassMember... */ /* @@@ this code is most odd and probably should be discouraged. */ /* It forges a ClassMember list of enum consts. */ /* Maybe we should just return a list of binders for them. */ /* (or discourage the debugger from needing this info in this form). */ { BindList *bl = bind_scope & (TOPLEVEL|GLOBALSTG) ? (BindList *)global_cons2(SU_Type, NULL, b) : mkBindList(NULL, b); if (p == 0) p = q = bl; else q->bindlistcdr = bl, q = bl; } } else { cc_err(syn_err_enumdef); while (curlex.sym != s_rbrace && curlex.sym != s_eof) nextsym(); } if (curlex.sym != s_comma) break; nextsym(); if (curlex.sym == s_rbrace) { if (feature & FEATURE_CFRONT_OR_PCC) cc_warn(syn_warn_extra_comma); else cc_rerr(syn_warn_extra_comma); break; } } if (has_neg && needs_unsigned) cc_rerr(syn_rerr_neg_unsigned_enum, tb); tagbindbits_(tb) = (tagbindbits_(tb) & ~TB_BEINGDEFD) | TB_DEFD; tagbindenums_(tb) = p; { SET_BITMAP container; if (needs_unsigned) container = TB_CONTAINER_UINT; else if (feature & FEATURE_ENUMS_ALWAYS_INT) container = TB_CONTAINER_INT; else if (minval >= 0) container = maxval < (1 << 8) ? TB_CONTAINER_UCHAR : /* @@@ using TB_CONTAINER_USHORT here seems worse than TB_CONTAINER_SHORT -- signed shorts are sometimes cheaper to extract */ maxval < (1 << (8 * sizeof_short)) ? TB_CONTAINER_USHORT : /* it doesn't seem like the choice between TB_CONTAINER_UINT and TB_CONTAINER_INT makes any real difference for C */ LanguageIsCPlusPlus ? TB_CONTAINER_INT : TB_CONTAINER_UINT; else { if (-minval-1 > maxval) maxval = -minval-1; container = maxval < (1 << (8-1)) ? TB_CONTAINER_CHAR : maxval < (1 << (8 * sizeof_short - 1)) ? TB_CONTAINER_SHORT : TB_CONTAINER_INT; } tagbindbits_(tb) = (tagbindbits_(tb) & ~TB_CONTAINER) | container; } } static bool eof_done; /* Exported: ONLY syn_init() and rd_topdecl(). Calling conventions: call lex_init() first. Then call rd_topdecl() until it returns { s_eof }. */ TopDecl *rd_topdecl(bool returneof) { TopDecl *d; TagBinder *old_access_context = set_access_context(NULL, NULL); #ifndef NO_MLS_XDEVT_1823 /* * move the progress from cfe/pp/pp_fillbuf() to reduce overhead */ UpdateProgress(); #endif if (LanguageIsCPlusPlus) { if (syn_reftemps != 0) syserr("syn_reftemps confused"); } implicit_return_ok = 0; /* for junky old C programs */ #ifdef EXTENSION_VALOF inside_valof_block = 0; valof_block_result_type = (TypeExpr *) DUFF_ADDR; cur_restype = 0; /* check for valof out of body */ #endif if (LanguageIsCPlusPlus && syn_generatedfns) { TopDecl *fd = syn_generatedfns->d; Mark* mark = syn_generatedfns->mark; if (usrdbg(DBG_PROC+DBG_VAR)) { Cmd *body = fd->v_f.fn.body; Binder *b = fd->v_f.fn.name; body->fileline.p = dbg_notefileline(body->fileline); #ifndef NEW_DBG_PROC_INTERFACE dbg_proc(bindsym_(b), bindtype_(b), 0, body->fileline); #else dbg_proc(b, NULL, 0, body->fileline); #endif } /* There is NEVER a struct result from a generated function... */ /* Generated fns include: ctors, dtors, operator=()s and the compiler- */ /* portions of user-defined constructors/destructors. */ currentfunction.structresult = 0; syn_generatedfns = cdr_(syn_generatedfns); alloc_unmark(mark); if (debugging(DEBUG_FNAMES+DEBUG_CG+DEBUG_CSE+DEBUG_REGS+DEBUG_SR)) cc_msg("Generated function $b\n", fd->v_f.fn.name); return fd; } if (LanguageIsCPlusPlus && syn_pendingfns) { TopDecl *fd; TagBinder *memscope = syn_pendingfns->pfscope; ScopeSaver formaltags = syn_pendingfns->pf_formaltags, tformals = syn_pendingfns->pf_templateformals; DeclRhsList *d; int instantiatescope = 0, varlevel = 0; int h = syn_pendingfns->pf_toklist_handle; /* Template fn: memscope pf_templateforamls cg -------- ------------------ -- template class memfn YES && NO NO TB_TEMPLATE non-template class template memfn YES YES NO template class template memfn YES YES NO Instantiate: top-level NO YES YES (non-)template class memfn YES YES YES */ bool parse_only = (memscope && (tagbindbits_(memscope) & TB_TEMPLATE)) || has_template_parameter(syn_pendingfns->pf_templateformals); if (memscope) { if (tagbindbits_(memscope) & TB_TEMPLATE) varlevel = push_var_scope(tagformals_(memscope), Scope_TemplateArgs); else if (tagactuals_(memscope)) { /*if (!tagscope_(memscope)) syserr("weird template $c", memscope);*/ instantiatescope = push_var_scope(tagscope_(memscope), Scope_TemplateDef); (void) push_var_scope(tagactuals_(memscope), Scope_TemplateArgs); } } d = reinvent_fn_DeclRhsList( syn_pendingfns->pfname, syn_pendingfns->pfrealname, syn_pendingfns->pftype, syn_pendingfns->pfstg); if (syn_pendingfns->pfstg & b_memfna) memfn_typefix(d, memscope); /* @@@ re-read [ES] to see if pfscope should include outermore scopes! */ /* Perhaps we should setup access in push_multi_scope()? */ /* The next line is OK for within-class friend DEFNS: it sets no access */ /* context, but friends are listed separately for access control. */ (void)set_access_context(memscope, NULL); lex_openbody(h, syn_pendingfns->pf_tfn, NO, NULL, NULL); syn_pendingfns = syn_pendingfns->pfcdr; fd = rd_fndef(d, (parse_only) ? TEMPLATE : TOPLEVEL, memscope, formaltags, tformals); if (memscope) { if (tagbindbits_(memscope) & TB_TEMPLATE) pop_scope_no_check(varlevel); else if (tagactuals_(memscope)) pop_scope_no_check(instantiatescope); if (parse_only) { if (h0_(fd) != s_decl || (fd->v_f.var)->declbind == NULL) syserr("Top level template member fn $r lost", (fd->v_f.var)->declname); bindtext_((fd->v_f.var)->declbind) = h; } } lex_closebody(); (void)set_access_context(old_access_context, NULL); return fd; } /* No pending functions, so read from input file... */ if (curlex.sym == s_nothing) nextsym(); for (;;) { while (curlex.sym == s_toplevel) nextsym(); if (LanguageIsCPlusPlus && syn_linkage != 0) switch (curlex.sym) { case s_eof: cc_err(syn_err_linkage_spec); /* drop through to effect insertion... */ case s_rbrace: syn_pop_linkage(); nextsym(); continue; } break; } if (curlex.sym == s_eof) { static TopDecl eofdecl = { s_eof }; if (LanguageIsCPlusPlus) { if (!returneof) { (void)set_access_context(old_access_context, NULL); if (!eof_done) eof_done = YES, dbg_final_src_codeaddr(codebase, codep); if ((d = vg_dynamic_init()) != NULL) { if (debugging(DEBUG_FNAMES+DEBUG_CG+DEBUG_CSE+DEBUG_REGS+DEBUG_SR)) cc_msg("Function $b\n", d->v_f.fn.name); return d; } } } else dbg_final_src_codeaddr(codebase, codep); return &eofdecl; } if (curlex.sym == s_lbrace) /* temp for ACN - rethink general case */ /* @@@ and especially for C++ linkage! */ { cc_err(syn_err_misplaced_brace); (void)push_scope(0, Scope_Ord); /* helps recovery */ (void)rd_body(te_int, NULL, NO, NO);/* this will also skip initialisers */ label_resolve(); /* tidy up in case declarations */ pop_scope(0); if (LanguageIsCPlusPlus) (void)set_access_context(old_access_context, NULL); return (TopDecl *)errornode; } d = rd_decl(TOPLEVEL, 0); (void)set_access_context(old_access_context, NULL); curlex.fl.p = dbg_notefileline(curlex.fl); return d; } void syn_init(void) { bind_scope = TOPLEVEL; synscope = 0; initpriovec(); expr_dtors = 0; extra_flags = 0; if (LanguageIsCPlusPlus) { syn_reftemps = NULL; syn_pendingfns = 0; syn_generatedfns = 0; syn_linkage = syn_linkage_free = 0; (void)set_access_context(NULL, NULL); /* no access context yet... */ syn_class_scope = 0; cur_template_formals = 0; cur_template_actuals = 0; eof_done = NO; } curlex_member = NULL; xsyn_init(); } /* End of cfe/syn.c */
stardot/ncc
mip/codebuf.h
/* * codebuf.h : target-independent part of object code generation, version 23 * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Codemist Ltd, 1988-1992. * Copyright (C) Advanced Risc Machines Ltd., 1991-1992. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _codebuf_LOADED #define _codebuf_LOADED 1 #ifndef _defs_LOADED # include "defs.h" #endif #include "xrefs.h" typedef struct DataDesc { DataInit *head, *tail; int32 size; DataXref *xrefs; int xrarea; union { int32 w32[1]; int16 w16[2]; int8 w8[4]; } wbuff; uint8 wpos; uint8 wtype; } DataDesc; typedef enum { DS_None , DS_ReadWrite #ifdef CONST_DATA_IN_CODE , DS_Const #endif } DataAreaSort; #if defined(CALLABLE_COMPILER) #define get_datadesc_ht(head) ((DataInit *)0) #define set_datadesc_ht(head,val) ((void)0) #define get_datadesc_size() ((int32) 0) #define set_datadesc_size(val) ((void)0) #define get_datadesc_xrefs() ((DataXref *)0) #define set_datadesc_xrefs(val) ((void)0) #define get_datadesc_xrarea() ((int)0) #define set_datadesc_xrarea(val) ((void)0) #define get_datadesc() ((DataDesc *)0) #define copy_datadesc(dest) ((void)0) #define restore_datadesc(src) ((void)0) #define data_size() ((int32)0) #define data_head() ((DataInit *)0) #define data_xrefs() ((DataXref *)0) #define constdata_size() ((int32)0) #define constdata_head() ((DataInit *)0) #define constdata_xrefs() ((DataXref *)0) #define is_constdata() ((bool)0) #define SetDataArea(x) DS_ReadWrite #else extern DataInit *get_datadesc_ht(bool head); extern void set_datadesc_ht(bool head, DataInit *val); extern int32 get_datadesc_size(void); extern void set_datadesc_size(int32 val); extern DataXref *get_datadesc_xrefs(void); extern void set_datadesc_xrefs(DataXref *val); extern int get_datadesc_xrarea(void); extern void set_datadesc_xrarea(int val); extern DataDesc *get_datadesc(void); extern void copy_datadesc(DataDesc *dest); extern void restore_datadesc(DataDesc *src); extern int32 data_size(void); extern DataInit *data_head(void); extern DataXref *data_xrefs(void); extern DataInit *get_extable_ht(bool head); extern void set_extable_ht(bool head, DataInit *val); extern void set_extable_size(int32 val); extern int32 extable_size(void); extern DataInit *extable_head(void); extern DataXref *extable_xrefs(void); extern bool is_extable(void); extern DataInit *get_exhandler_ht(bool head); extern void set_exhandler_ht(bool head, DataInit *val); extern void set_exhandler_size(int32 val); extern int32 exhandler_size(void); extern DataInit *exhandler_head(void); extern DataXref *exhandler_xrefs(void); extern bool is_exhandler(void); # ifdef CONST_DATA_IN_CODE extern int32 constdata_size(void); extern DataInit *constdata_head(void); extern DataXref *constdata_xrefs(void); extern bool is_constdata(void); # else #define dataloc (get_datadesc_size()) /* compatibility with other back ends. */ #define datainitp (get_datadesc_ht(YES)) #define dataxrefs (get_datadesc_xrefs()) # endif extern DataAreaSort SetDataArea(DataAreaSort); #endif extern int32 code_area_idx; /* for armcc -S -ZO ... */ extern int32 codebase; extern struct LabelNumber *litlab; extern int32 litpoolp; extern int32 codep; #ifdef TARGET_HAS_BSS extern int32 bss_size; #endif /* xxx/gen.c obj.c and asm.c should now only access 'codeandflagvec' */ /* via the macros code_xxx_() below. */ /* ECN: Modified to allow non-aligned words if TARGET_HAS_HALFWORD_INSTRUCTIONS * Unfortunately there are large scale assumptions elsewhere that * codeandflagvec addresses an array of 32 bit words. */ #ifdef TARGET_HAS_HALFWORD_INSTRUCTIONS # define CodeFlag_t unsigned char extern struct CodeAndFlag { unsigned16 code[CODEVECSEGSIZE*2]; CodeFlag_t flag[CODEVECSEGSIZE*2]; } *codeandflagvec[CODEVECSEGMAX]; #define code_byte_(q) ((unsigned8 *)(codeandflagvec[(q) >> CODEVECSEGBITS+2]->code)) \ [(q) & (CODEVECSEGSIZE*4-1)] #define code_hword_(q) (codeandflagvec[(q) >> (CODEVECSEGBITS+2)])-> \ code[((q) >> 1) & (CODEVECSEGSIZE*2-1)] #define code_flag_(q) (codeandflagvec[(q) >> (CODEVECSEGBITS+2)])-> \ flag[((q) >> 1) & (CODEVECSEGSIZE*2-1)] #define code_inst_(q) (host_lsbytefirst ? \ (code_hword_(q) | (code_hword_(q+2) << 16)) : \ ((code_hword_(q) << 16) | code_hword_(q+2))) #define set_code_inst_(q,v) (host_lsbytefirst ? \ ((code_hword_(q) = (unsigned16)(v)), (code_hword_((q)+2) = (v) >> 16)) : \ ((code_hword_(q) = (v) >> 16), (code_hword_((q)+2) = (unsigned16)(v)))) #else #ifdef TARGET_HAS_BYTE_INSTRUCTIONS # define CodeFlag_t int32 /* dying? */ #else # define CodeFlag_t unsigned char #endif extern struct CodeAndFlag { int32 code[CODEVECSEGSIZE]; CodeFlag_t flag[CODEVECSEGSIZE]; } *codeandflagvec[CODEVECSEGMAX]; #define code_inst_(q) (codeandflagvec[(q) >> CODEVECSEGBITS+2])-> \ code[(q)>>2 & CODEVECSEGSIZE-1] #define set_code_inst_(q,v) (code_inst_(q)=v) #define code_flag_(q) (codeandflagvec[(q)>>CODEVECSEGBITS+2])-> \ flag[(q)>>2 & CODEVECSEGSIZE-1] #endif #ifndef NO_ASSEMBLER_OUTPUT /* i.e. lay off otherwise */ extern VoidStar (*(codeasmauxvec[CODEVECSEGMAX]))[CODEVECSEGSIZE]; # define code_aux_(q) (*codeasmauxvec[(q) >> CODEVECSEGBITS+2]) \ [(q)>>2 & CODEVECSEGSIZE-1] #endif /* The following macros provide easy access to blocks for xxx/obj.c */ #define code_instvec_(i) (&(codeandflagvec[i]->code)[0]) #define code_flagvec_(i) (&(codeandflagvec[i]->flag)[0]) #ifdef TARGET_HAS_BYTE_INSTRUCTIONS #define code_byte_(q) \ ((unsigned char *)(codeandflagvec[(q) >> CODEVECSEGBITS+2]->code)) \ [(q) & 4*CODEVECSEGSIZE-1] /* miserable macro to interpret int32 flags as 4 byte flags. Hmm. */ #define flag_byte_(q) \ ((unsigned char *)(codeandflagvec[(q) >> CODEVECSEGBITS+2]->flag)) \ [(q) & 4*CODEVECSEGSIZE-1] #endif extern struct LabList *asm_lablist; /* exported to xxxgen.c */ extern struct LabelNumber *nextlabel(void); extern void labeldata(Symstr *b); extern int32 trydeletezerodata(DataInit *previous, int32 minsize); extern void gendcAX(Symstr *sv, int32 offset, int xrflavour); /* (possibly external) name + offset, flavour is xr_data or xr_code */ #ifdef CALLABLE_COMPILER #define gendc0(n) ((void)0) #else extern void gendc0(int32 nbytes); #endif extern void gendcI_a(int32 len, int32 val, bool aligned); #define gendcI(len, val) gendcI_a(len, val, YES) extern void gendcE(int32 len, FloatCon *val); #ifdef TARGET_CALL_USES_DESCRIPTOR extern void gendcF(Symstr *sv, int32 offset); extern int32 genfncon(Symstr* sv); #else /* TARGET_CALL_USES_DESCRIPTOR */ # define gendcF(sym, off, strength) gendcAX(sym, off, xr_code|(strength)) #endif /* TARGET_CALL_USES_DESCRIPTOR */ #define gendcA(sym, off, strength) gendcAX(sym, off, xr_data|(strength)) extern void vg_genstring(StringSegList *s, int32 size, int pad); extern void padstatic(int32 align); #ifdef TARGET_HAS_BSS extern void padbss(int32 align); #endif int32 totargetsex(int32 w, int flag); extern void codeseg_stringsegs(StringSegList *x, bool incode); extern void codeseg_flush(Symstr *strlitname); extern int32 codeseg_function_name(Symstr *name, int32 argn); extern void show_entry(Symstr *name, int flags); extern void show_code(Symstr *name); extern void outcodeword(int32 w, int32 f); extern void outcodewordaux(int32 w, int32 f, VoidStar aux); extern void outlitword(int32 w, int32 flavour, Symstr *sym, VoidStar aux, int32 flag); extern int32 codeloc(void); extern int32 lit_findadcon(Symstr *name, int32 offset, int32 wherefrom); extern void dumplits2(bool needsjump); extern int lit_of_count_name(char *s); extern void dump_count_names(void); extern int32 lit_findword(int32 w, int32 flavour, Symstr *sym, int32 flag); extern int32 lit_findwordaux(int32 w, int32 flavour, VoidStar aux, int32 flag); extern int32 lit_findwordsincurpool(int32 w[], int32 count, int32 flavour); extern int32 lit_findwordsinprevpools(int32 w[], int32 count, int32 flavour, int32 earliest); extern int32 lit_findstringincurpool(StringSegList *s); extern int32 lit_findstringinprevpools(StringSegList *s, int32 earliest); extern int32 stringlength(StringSegList *s); extern int32 addbsssym(Symstr *sym, int32 size, int32 align, bool statik, bool local); extern void codebuf_init(void); extern void codebuf_reinit(void); extern void codebuf_reinit1(char * codeseg_name); /* for C++ dynamic inits */ extern void codebuf_reinit2(void); extern void codebuf_tidy(void); #ifdef TARGET_IS_ACW extern void outbytef(int32 w, int f); #endif #endif /* end of codebuf.h */
stardot/ncc
mip/cse.c
<gh_stars>0 /* * cse.c: Common sub-expression elimination * Copyright (C) Acorn Computers Ltd., 1988. * Copyright 1991-1997 Advanced Risc Machines Limited. All rights reserved * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 133 * Checkin $Date$ * Revising $Author$ */ #ifdef __STDC__ # include <string.h> # include <time.h> # include <stddef.h> #else # include <strings.h> # include "time.h" # include "stddef.h" #endif #include "globals.h" #include "cse.h" #include "jopcode.h" #include "store.h" #include "regalloc.h" #include "cg.h" #include "flowgraf.h" #include "mcdep.h" /* usrdbg, DBG_xxx */ #include "builtin.h" /* for te_xxx */ #include "errors.h" #include "aeops.h" #include "cseguts.h" typedef struct CSE CSE; typedef struct CSERef CSERef; struct CSERef { CSERef *cdr; union { BlockHead *b; ExprnUse *ex; } ref; }; #define refuse_(p) ((p)->ref.ex) #define refblock_(p) ((p)->ref.b) #define mk_CSERef(a,b) ((CSERef *)CSEList2((a), (b))) #define CSERef_DiscardOne(p) ((CSERef *)discard2((List *)(p))) struct CSEDef { CSEDef *cdr; BlockHead *block; Exprn *exprn; CSERef *refs; Icode *icode; VRegSetP uses; CSEDef *subdefs, *nextsub; CSEDef *super; Binder *binders[1]; int32 mask; /* only for compares */ }; #define defbinder_(x,n) ((x)->binders[n]) #define defmask_(x) ((x)->mask) #define defblock_(x) ((x)->block) #define defex_(x) ((x)->exprn) #define defrefs_(x) ((x)->refs) #define defic_(x) ((x)->icode) #define defuses_(x) ((x)->uses) #define defsub_(x) ((x)->subdefs) #define defsuper_(x) ((x)->super) #define defnextsub_(x) ((x)->nextsub) #define CSEDef_New(n) ((CSEDef *)CSEAlloc(offsetof(CSEDef, binders)+(n)*sizeof(Binder *))) struct CSE { CSE *cdr; Exprn *exprn; CSEDef *def; }; #define cseex_(x) ((x)->exprn) #define csedef_(x) ((x)->def) static CSE *cselist; static CSEDef *localcsedefs; static BindList *csespillbinders; typedef struct LoopList LoopList; struct LoopList { LoopList *cdr; BlockList *members; /* list of basic blocks inside */ BlockHead *preheader; /* where to put found invariants */ BlockHead *header; BlockHead *tail; }; #define ll_mem_(p) ((p)->members) #define ll_prehdr_(p) ((p)->preheader) #define ll_hdr_(p) ((p)->header) #define ll_tail_(p) ((p)->tail) static LoopList *all_loops; static VRegSetP loopmembers; #define mk_CSEBlockList(a, b) ((BlockList *)CSEList2((BlockList *)a, (BlockHead *)b)) struct CSEUseList { CSEUseList *cdr; CSEDef *def; ExprnUse *use; }; #define ul_def_(p) ((p)->def) #define ul_use_(p) ((p)->use) #define mk_CSEUseList(a,b,c) ((CSEUseList *)CSEList3((a),(b),(c))) static unsigned32 nsets, newsets, setbytes; static unsigned32 maxsets, maxbytes; static unsigned32 cse_count, cse_refs; VRegSetAllocRec cseallocrec; /* = {CSEAllocType, &nsets, &newsets, &setbytes};*/ SetSPList *setsplist; static bool BlockList_Member(BlockHead *b, BlockList *list) { return generic_member((IPtr)b, (List *)list); } #ifdef ENABLE_CSE #define printset(s) cseset_map(s, ps, NULL) static void ps(int32 n, VoidStar arg) { IGNORE(arg); cc_msg(" %ld", (long)n); } void cse_printset(VRegSetP s) { cseset_map(s, ps, NULL); } #else #define cse_printset(s) /* nothing */ #endif static J_OPCODE CSEaccessOp(VRegnum r, J_OPCODE model) { /* 'model' is either J_LDRV or J_STRV. */ /* @@@ This routine needs to exploit J_ALIGN4V in cg.c... */ J_OPCODE op; switch (vregsort(r)) { case FLTREG: op = J_LDRFV|J_ALIGN4; break; /* See jopcode.h comment about J_ALIGN8 with alignof_double=4. */ case DBLREG: op = J_LDRDV|J_ALIGN8; break; #ifdef never missing: op = J_LDRLV|J_ALIGN8; break; #endif default: op = J_LDRV|J_ALIGN4; break; } return model == J_LDRV ? op : J_LDtoST(op); } static RegSort DestRegSort(J_OPCODE op) { /* Given 'op' return the 'regsort' suitable for the 'r1' */ /* field of 'op'. If 'op' is a j_ischeck() (or J_CMP?) then */ /* 'GAP' is returned. */ /* This routine is the only user of deprecated 'floatiness_()'. */ /* It suggests that a new 'J_destregsort() could be in jopcode.h */ if (j_is_check(op) || is_compare(op)) return GAP; else { J_OPCODE x = op & J_TABLE_BITS; switch (floatiness_(op)) { case _J_FLOATING: return x==J_FIXFR ? INTREG:FLTREG; case _J_DOUBLE: return x==J_FIXDR ? INTREG:DBLREG; default: return INTREG; } } } static void ReplaceWithLoad(Icode *target, VRegnum r1, Binder *binder) { #ifdef RANGECHECK_SUPPORTED if (binder == NULL) target->op = J_NOOP; else #endif { target->op = CSEaccessOp(r1, J_LDRV); target->r2.r = GAP; target->r3.b = binder; } } static CSEUseList *ReplaceIcode(CSEUseList *deferred, ExprnUse *ref, CSEDef *def) { BlockHead *b = ref->block; if (!IsRealIcode(ref)) blk_defs2_(b) = def; else { Icode *target = &useicode_(ref); J_OPCODE op = target->op; VRegnum r1 = target->r1.r; if (debugging(DEBUG_CSE)) { print_jopcode_1(target); cc_msg(" %ld/%ld\n", (long)blklabname_(b), (long)icoden_(ref)); } if (def != NULL) { Exprn *ex = defex_(def); #ifdef TARGET_ALLOWS_COMPARE_CSES if (is_compare(exop_(ex))) { defmask_(def) = (defmask_(def) & Q_UBIT) | Q_UKN; target->op = J_NOOP; } else #endif if (pseudo_reads_r2(exop_(ex))) { VRegnum r = bindxx_(defbinder_(def, 0)); if (pseudo_reads_r1(op)) target->r1.r = r; else { target->op = exop_(ex); target->r2.r = r; note_slave(target->r1.r, r); } target->r3.i = e1k_(ex); } else if (nvals_(ref) == 0) ReplaceWithLoad(target, r1, defbinder_(def, valno_(ref))); else deferred = mk_CSEUseList(deferred, def, ref); } } cse_refs++; return deferred; } static Binder *AddCSEBinder(J_OPCODE op, BindList **bl, VRegnum r) { Binder *bnew; /* /* The following line is a hack to fix things up now that vregsort() */ /* faults r == GAP. Fix properly soon. */ /* It is manifested by f(n) { if (n>1023) g(); if (n>1023) h(); } */ bnew = gentempvarofsort(r == GAP ? INTREG : vregsort(r)); /* Two lists of binders introduced by CSE are required: one for computing stack frame offsets (to add to lists present before CSE in block heads and SETSPENVs), and one to determine binder spill order. These are not the same: binders introduced for ADCONs and the like need to be in the second list but not the first (since they are simply discarded if they spill: if they were in the first list, they would consume stack to no purpose). */ csespillbinders = mkBindList(csespillbinders, bnew); if (!pseudo_reads_r2(op) && !is_compare(op)) { *bl = mkBindList(*bl, bnew); bindbl_(bnew) = *bl; } else bindbl_(bnew) = NULL; bindstg_(bnew) |= b_bindaddrlist; return bnew; } static CSEDef *mk_CSEDef(Exprn *ex, BlockHead *b) { CSEDef *def; if (is_calln(ex)) def = CSEDef_New(exnres_(ex)); #ifdef TARGET_ALLOWS_COMPARE_CSES else if (is_compare(exop_(ex))) def = CSENew(CSEDef); #endif else def = CSEDef_New(1); defblock_(def) = b; defic_(def) = NULL; defex_(def) = ex; defrefs_(def) = NULL; defuses_(def) = NULL; defbinder_(def, 0) = NULL; defsub_(def) = defnextsub_(def) = defsuper_(def) = NULL; return def; } static CSEDef *AddToCSEList(Exprn *ex, BlockHead *b, bool mustbenew) { CSE *cse; CSEDef *def; for (cse = cselist ; cse != NULL ; cse = cdr_(cse)) if (ex == cseex_(cse)) break; if (cse == NULL) cse = cselist = (CSE *)CSEList3(cselist, ex, NULL); if (!mustbenew) for (def = csedef_(cse); def != NULL; def = cdr_(def)) if (defblock_(def) == b) return def; def = mk_CSEDef(ex, b); cdr_(def) = csedef_(cse); csedef_(cse) = def; return def; } static bool KillExprRef_i(CSEDef *def, Icode *ic) { ptrdiff_t icoden = ic - blkcode_(cse_currentblock); CSERef **refp; for ( ; def != NULL; def = cdr_(def)) if (defblock_(def) == cse_currentblock) for (refp = &defrefs_(def); *refp != NULL; refp = &cdr_(*refp)) { ExprnUse *use = refuse_(*refp); if (use->block == cse_currentblock && icoden_(use) == icoden) { *refp = cdr_(*refp); return YES; } } return NO; } bool cse_KillExprRef(ExSet *s, Icode *ic) { /* remove any local or global CSE references to the instruction ic */ for (; s != NULL; s = cdr_(s)) { Exprn *ex = s->exprn; CSE *cse; if (KillExprRef_i(localcsedefs, ic)) return YES; for (cse = cselist; cse != NULL; cse = cdr_(cse)) if (cseex_(cse) == ex && KillExprRef_i(csedef_(cse), ic)) return YES; } return NO; } static bool WorthReplacement(Exprn *ex) { /* Same rules for what's worth making into a CSE whether for local or */ /* or non-local use. */ /* The following line is really unnecessary (csescan doesn't create */ /* Exprns for these things). */ if (exop_(ex) == J_MOVDIR || exop_(ex) == J_MOVLIR || exop_(ex) == J_MOVFIR) return NO; #ifdef TARGET_HAS_CONST_R_ZERO /* In this case it is SILLY to lift zero as a constant! */ if (exop_(ex) == J_MOVK && e1k_(ex) == 0) return NO; #endif if (extype_(ex) == E_LOAD) { Location *loc = exloc_(ex); if (!ispublic(loc)) return NO; if (loctype_(loc) & LOC_anyVAR) return !(bindstg_(locbind_(loc)) & b_globalregvar); if (exop_(locbase_(loc)) == J_ADCONV) return NO; return YES; } return exop_(ex) != J_STRING && exop_(ex) != J_ADCONV; /* J_ADCONF and J_ADCOND also used to be excluded here. There seems */ /* no good reason - after all, CSEs for them vanish if spilt, and */ /* J_ADCON (which one would have thought analogous) is included. */ /* One might question the inclusion of J_ADCONV, too, but bear in */ /* mind that, for local CSEs, it may be eliminated by transformation*/ /* of opK to opVK. */ } bool cse_AddLocalCSE(Exprn *node, int valno, int nvals, BlockHead *b) { ExprnUse *def = exuses_(node); Icode *deficode; CSEDef *csedef; CSERef *ref; if (!WorthReplacement(node)) return NO; ref = CSENew(CSERef); if (def == NULL) syserr(syserr_addlocalcse, exid_(node)); /* If node is not killed between here and the start of the block, then the local CSE may be later subsumed by a non-local CSE. Otherwise, we must take care to avoid that happening. In the latter case, the CSEDef is attached to the list localcsedefs; in the former, to a CSE in cselist I believe subsuming an ADCON or MOVK is not helpful, thanks to slave_list, and may be harmful if the non-local CSE must be spilt but a register could be allocated for the local one. (Hence the !pseudo_reads_r2() test) */ deficode = &useicode_(def); if (!pseudo_reads_r2(deficode->op) && !cse_KilledInBlock(exid_(node))) { csedef = AddToCSEList(node, b, NO); cseset_insert(blklabname_(b), defuses_(csedef), NULL); if (debugging(DEBUG_CSE) && CSEDebugLevel(1)) cc_msg("(subsumable) "); } else { for (csedef = localcsedefs ; csedef != NULL ; csedef = cdr_(csedef)) if (defic_(csedef) == deficode) break; if (csedef == NULL) { csedef = mk_CSEDef(node, b); setflag_(def, U_LOCALCSE); cdr_(csedef) = localcsedefs; localcsedefs = csedef; } } defic_(csedef) = deficode; cdr_(ref) = defrefs_(csedef); defrefs_(csedef) = ref; refuse_(ref) = ExprnUse_New(NULL, 0, valno); setnvals_(refuse_(ref), nvals); if (debugging(DEBUG_CSE) && CSEDebugLevel(1)) cc_msg("-- local CSE reference [%ld]\n", exid_(node)); return YES; } static VRegSetP ExprnsWantedBy(LabelNumber *q, bool allpaths) { if (is_exit_label(q)) return NULL; else { CSEBlockHead *p = blkcse_(q->block); VRegSetP s = cseset_copy(allpaths ? p->wantedonallpaths : p->wantedlater); if (p->killedinverted) cseset_intersection(s, p->killed); else cseset_difference(s, p->killed); return cseset_union(s, p->wanted); } } static void ExprnsReaching(BlockHead *p) { VRegSetP s1, s2; if (blkflags_(p) & BLKSWITCH) { LabelNumber **v = blktable_(p); int32 i, n = blktabsize_(p); s1 = ExprnsWantedBy(v[0], NO); s2 = ExprnsWantedBy(v[0], YES); for (i = 1 ; i < n ; i++) { VRegSetP s = ExprnsWantedBy(v[i], NO); cseset_union(s1, s); cseset_discard(s); s = ExprnsWantedBy(v[i], YES); cseset_intersection(s2, s); cseset_discard(s); } } else { s1 = ExprnsWantedBy(blknext_(p), NO); s2 = ExprnsWantedBy(blknext_(p), YES); if (blkflags_(p) & BLK2EXIT) { VRegSetP s = ExprnsWantedBy(blknext1_(p), NO); cseset_union(s1, s); cseset_discard(s); s = ExprnsWantedBy(blknext1_(p), YES); cseset_intersection(s2, s); cseset_discard(s); } } blk_wantedlater_(p) = s1; blk_wantedonallpaths_(p) = s2; } static bool ContainsLoadr(Exprn *p) { /* A temporary bodge. Expressions containing a register whose value is * unknown are valid local CSEs, but not valid outside their block (because * before the LOADR was created, earlier loads to the register would have * passed unknown). The earlier treatment of registers (where each was a * Location) got this right, but had undesirable space & time costs. More * thought needed. Here, we simply prevent anything with a leaf which is a * LOADR from becoming a candidate CSE. */ if (p == NULL) return NO; switch (extype_(p)) { case E_LOADR: return YES; case E_TERNARY: if (ContainsLoadr(e3_(p))) return YES; case E_BINARY: if (ContainsLoadr(e2_(p))) return YES; case E_BINARYK: case E_UNARY: return ContainsLoadr(e1_(p)); case E_LOAD: { Location *loc = exloc_(p); if (loctype_(loc) & LOC_anyVAR) return NO; return ContainsLoadr(locbase_(loc)); } case E_CALL: { int32 i; for (i = 0 ; i < exnargs_(p) ; i++) if (ContainsLoadr(exarg_(p, i))) return YES; } return NO; default: return NO; } } static void AddCSE(int32 n, void *arg) { Exprn *ex = exprn_(n); if ( !ContainsLoadr(ex) && WorthReplacement(ex)) AddToCSEList(ex, (BlockHead *)arg, YES); } CSEBlockHead *CSEBlockHead_New(void) { CSEBlockHead *q = CSENew(CSEBlockHead); q->available = NULL; q->wanted = NULL; q->wantedlater = NULL; q->wantedonallpaths = NULL; q->killed = NULL; q->defs = NULL; q->killedinverted = NO; q->reached = NO; q->loopempty = 0; q->scanned = NO; q->locvals = NULL; q->cmp = NULL; q->ternaryr = GAP; q->defs2 = NULL; q->refs = NULL; return q; } #define dominates(p, q) cseset_member(blklabname_(p), blk_dominators_(q)) static bool PruneSuccessors(LabelNumber *lab, VRegSetP s) { if (is_exit_label(lab)) return NO; { BlockHead *p = lab->block; VRegSetP old = blk_dominators_(p); VRegSetP s1 = cseset_copy(s); bool oldreached = blk_reached_(p), same; cseset_intersection(s1, old); cseset_insert(lab_name_(lab), s1, NULL); same = cseset_equal(s1, old); cseset_discard(old); blk_dominators_(p) = s1; blk_reached_(p) = YES; return !same || !oldreached; } } bool cse_AddPredecessor(LabelNumber *lab, BlockHead *p) { if (!is_exit_label(lab) && !BlockList_Member(p, blk_pred_(lab->block))) { blk_pred_(lab->block) = mk_CSEBlockList(blk_pred_(lab->block), p); return YES; } else return NO; } void cse_RemovePredecessor(LabelNumber *lab, BlockHead *b) { if (!is_exit_label(lab)) blk_pred_(lab->block) = (BlockList *)generic_ndelete((IPtr)b, (List *)blk_pred_(lab->block)); } static void PruneDominatorSets(void) { BlockHead *p; bool changed; do { changed = NO; for (p = top_block; p != NULL; p = blkdown_(p)) { VRegSetP s = blk_dominators_(p); if (blk_reached_(p)) { if (blkflags_(p) & BLKSWITCH) { LabelNumber **v = blktable_(p); int32 i, n = blktabsize_(p); for (i=0; i<n; i++) changed = changed | PruneSuccessors(v[i], s); } else { changed = changed | PruneSuccessors(blknext_(p), s); if (blkflags_(p) & BLK2EXIT) changed = changed | PruneSuccessors(blknext1_(p), s); } } } } while (changed); } static void FindDominators(void) { BlockHead *p; { VRegSetP allblocks = NULL; for (p = top_block; p != NULL; p = blkdown_(p)) cseset_insert(blklabname_(p), allblocks, NULL); for (p = blkdown_(top_block); p != NULL; p = blkdown_(p)) blk_dominators_(p) = cseset_copy(allblocks); cseset_discard(allblocks); } blk_reached_(top_block) = YES; cseset_insert(blklabname_(top_block), blk_dominators_(top_block), NULL); PruneDominatorSets(); for (p = top_block; p != NULL; p = blkdown_(p)) { if (!blk_reached_(p)) { cseset_discard(blk_dominators_(p)); blk_dominators_(p) = NULL; } else if (blkflags_(p) & BLKSWITCH) { LabelNumber **v = blktable_(p); int32 i, n = blktabsize_(p); for (i=0; i<n; i++) cse_AddPredecessor(v[i], p); } else { cse_AddPredecessor(blknext_(p), p); if (blkflags_(p) & BLK2EXIT) cse_AddPredecessor(blknext1_(p), p); } } } static void CSEFoundLoop(BlockHead *header, BlockHead *tail, BlockList *members) { if (debugging(DEBUG_CSE) && CSEDebugLevel(2)) { if (header == NULL) cc_msg("fake outer loop:"); else cc_msg("loop %ld<-%ld:", (long)blklabname_(header), (long)blklabname_(tail)); for (; members != NULL; members = cdr_(members)) cc_msg(" %ld", (long)blklabname_(members->blklstcar)); cc_msg("\n"); } } static LoopList *mk_LoopList( LoopList *next, BlockList *members, BlockHead *preheader, BlockHead *header, BlockHead *tail) { LoopList *l = CSENew(LoopList); ll_mem_(l) = members; ll_prehdr_(l) = preheader; ll_hdr_(l) = header; ll_tail_(l) = tail; cdr_(l) = next; return l; } static void ReplaceInBlockList(BlockList *bl, BlockHead *oldb, BlockHead *newb) { for (; bl != NULL; bl = cdr_(bl)) if (bl->blklstcar == oldb) { bl->blklstcar = newb; return; } } static BlockHead *cse_InsertBlockBetween(BlockHead *before, BlockHead *after) { BlockHead *newb = insertblockbetween(before, after, YES); blkcse_(newb) = CSEBlockHead_New(); blk_dominators_(newb) = cseset_copy(blk_dominators_(after)); blkflags_(newb) |= BLKLOOP; blk_pred_(newb) = mk_CSEBlockList(NULL, before); ReplaceInBlockList(blk_pred_(after), before, newb); { /* Must add the new block to dominator sets now, or if it's a preheader we will fail to find a place to insert a preheadeer for another loop with the same header. */ BlockHead *b = top_block; int32 labno = blklabname_(newb); for (; b != NULL; b = blkdown_(b)) if (dominates(after, b)) cseset_insert(labno, blk_dominators_(b), NULL); cseset_delete(blklabname_(after), blk_dominators_(newb), NULL); } return newb; } static BlockHead *MakePreheader(BlockHead *pred, BlockHead *header) { BlockHead *preheader = cse_InsertBlockBetween(pred, header); blkflags_(preheader) |= BLKLOOP; return preheader; } static bool LoopEmptyBlock(BlockHead *b) { /* for loop optimisation's purposes, we may ignore blocks which can't interfere (this means they neither reference nor kill any Exprn, but since loop analysis precedes cse_scanblock the simple !(blk_wanted_(b) == NULL && blk_killed_(b) == NULL) isn't available. Instead, we use a weaker approximation. */ int i; if (blkflags_(b) & BLK2EXIT) return NO; if (blk_loopempty_(b) != LOOP_EMPTY) { for (i = 0; i < blklength_(b); i++) if (blkcode_(b)[i].op != J_SETSPGOTO) return NO; blk_loopempty_(b) = LOOP_EMPTY; } return YES; } typedef struct LLL_Loop { struct LLL_Loop *cdr; BlockList *members; /* list of basic blocks inside */ BlockHead *tail; VRegSetP memberset; } LLL_Loop; typedef struct LoopListList { struct LoopListList *cdr; BlockHead *header; LLL_Loop *loops; } LoopListList; static LoopListList *looplists; static void AddLoop(BlockHead *p, LabelNumber *q) { /* The flowgraph contains an arc from p to q: if q dominates p, this means there is a loop with header q */ if (!is_exit_label(q) && dominates(q->block, p)) { BlockHead *header = q->block; BlockList *bl, *members; LoopListList *l = looplists; for (; l != NULL; l = cdr_(l)) if (l->header == header) { LLL_Loop *ll = l->loops; for (; ll != NULL; ll = cdr_(ll)) if (ll->tail == p) return; /* already got this one */ break; } bl = mk_CSEBlockList(NULL, p); members = mk_CSEBlockList(NULL, header); while (bl != NULL) { BlockHead *b = bl->blklstcar; bl = cdr_(bl); if (!BlockList_Member(b, members)) { BlockList *pred = blk_pred_(b); members = mk_CSEBlockList(members, b); for (; pred != NULL; pred = cdr_(pred)) bl = mk_CSEBlockList(bl, pred->blklstcar); } } /* allow for possible compilation of while(a) b; as if (a) do b; while (a); (Move the loop header before the if) */ if (blk_cmp_(header) != NULL) { BlockList *pred = blk_pred_(header); BlockHead *b = NULL; for (; pred != NULL; pred = cdr_(pred)) if (!BlockList_Member(pred->blklstcar, members)) { if (b != NULL) { b = NULL; break; } b = pred->blklstcar; } if (b != NULL && dominates(b, header) && ExSetsOverlap(blk_cmp_(b), blk_cmp_(header)) && Q_issame(blkflags_(b) & Q_MASK, Q_NEGATE(blkflags_(p) & Q_MASK)) && blknext1_(b) == blknext_(p)) { LabelNumber *l1 = blknext_(b), *l2 = blknext1_(b); BlockHead *newb = cse_InsertBlockBetween(b, header); blknext_(newb) = l1; blknext1_(newb) = l2; blklength_(b)--; blkcode_(newb) = &blkcode_(b)[blklength_(b)]; blklength_(newb) = 1; blkflags_(newb) |= (blkflags_(b) & Q_MASK) | BLK2EXIT; blkflags_(b) = (blkflags_(b) & ~(BLK2EXIT | Q_MASK)) | BLKREXPORTED | BLKREXPORTED2; ExSet_TransferExprnsInSet(&blk_available_(b), &blk_available_(newb), blk_cmp_(b)); blk_cmp_(b) = NULL; members = mk_CSEBlockList(members, newb); if (l1 == blklab_(header)) l1 = l2; if (!is_exit_label(l1)) ReplaceInBlockList(blk_pred_(l1->block), b, newb); header = newb; { LoopListList *ll = looplists; LLL_Loop *l; for (; ll != NULL; ll = cdr_(ll)) for (l = ll->loops; l != NULL; l = cdr_(l)) if (l->tail == b) { BlockList *bl = l->members; for (; bl != NULL; bl = cdr_(bl)) if (bl->blklstcar == b) { bl->blklstcar = newb; break; } l->tail = newb; } else if (BlockList_Member(b, l->members)) l->members = mk_CSEBlockList(l->members, newb); } } } { LoopListList **ll = &looplists; for (ll = &looplists; (l = *ll) != NULL; ll = &cdr_(l)) if (l->header == header) break; CSEFoundLoop(header, p, members); if (l == NULL) *ll = l = (LoopListList *) CSEList3(NULL, header, NULL); { LLL_Loop *newl = CSENew(LLL_Loop); cdr_(newl) = l->loops; newl-> members = members; newl->tail = p; newl->memberset = NULL; l->loops = newl; } } } } static BlockHead *AddBlockBeforeHeader(BlockHead *header, char *s) { BlockHead *b = NULL; BlockList *bl, *prev = NULL; LabelNumber *blab = NULL; for (bl = blk_pred_(header); bl != NULL; prev = bl, bl = cdr_(bl)) if (!dominates(header, bl->blklstcar)) { BlockHead *pred = bl->blklstcar; if (debugging(DEBUG_CSE) && CSEDebugLevel(2)) { cc_msg("insert %s between %ld and %ld: ", s, (long)lab_name_(blklab_(pred)), (long)lab_name_(blklab_(header))); } if (b == NULL) { b = MakePreheader(pred, header); bl->blklstcar = b; blab = blklab_(b); if (debugging(DEBUG_CSE) && CSEDebugLevel(2)) cc_msg("%s = %ld\n", s, (long)blklabname_(b)); } else { changesuccessors(pred, blab, blklab_(header)); cdr_(prev) = cdr_(bl); bl = prev; } cse_AddPredecessor(blab, pred); } return b; } static void AddBlockToLoopsContaining(BlockHead *b, BlockHead *newbh) { /* Add newbh to the members of any loop containing b (except those for which it is the header) */ LoopListList *x; LLL_Loop *l; for (x = looplists; x != NULL; x = cdr_(x)) if (x->header != b) for (l = x->loops; l != NULL; l = cdr_(l)) { BlockList *members = l->members; for (; members != NULL; members = cdr_(members)) if (members->blklstcar == b) cdr_(members) = mk_CSEBlockList(cdr_(members), newbh); } } typedef struct LoopSet { struct LoopSet *cdr; LLL_Loop *loops; VRegSetP xn, un; } LoopSet; static void InsertPreheaders(void) { LoopListList *ll; LLL_Loop *l, *nextl; for (ll = looplists; ll != NULL; ll = cdr_(ll)) if (cdr_(ll->loops) != NULL) { /* If there is more than one loop with the same header, convert the member blocklist for each loop into a VRegSet in which blocks which are empty as far as loop analysis is concerned are ignored. (We do this to make comparison easier). */ LoopSet *loopsets = NULL; for (l = ll->loops; l != NULL; l = cdr_(l)) { BlockList *m = l->members; for (; m != NULL; m = cdr_(m)) { BlockHead *b = m->blklstcar; if (blk_loopempty_(b) != LOOP_NONEMPTY) { if (LoopEmptyBlock(b)) continue; blk_loopempty_(b) = LOOP_NONEMPTY; } l->memberset = cseset_insert(blklabname_(b), l->memberset, NULL); } } /* Now allocate the loops to sets ordered by inclusion of loop member sets. */ for (l = ll->loops; l != NULL; l = nextl) { LoopSet *ls, **lsp = &loopsets; nextl = cdr_(l); for (; (ls = *lsp) != NULL; lsp = &cdr_(ls)) { int order = cseset_compare(l->memberset, ls->xn); if (order == VR_SUBSET) break; order = cseset_compare(l->memberset, ls->un); if (order != VR_SUPERSET) { cdr_(l) = ls->loops; ls->loops = l; ls->un = cseset_union(ls->un, l->memberset); ls->xn = cseset_intersection(ls->xn, l->memberset); while (order == VR_UNORDERED) { LoopSet *nexts = cdr_(ls); if (nexts == NULL || cseset_compare(l->memberset, nexts->xn) == VR_SUBSET) goto nextloop; cdr_(ls) = cdr_(nexts); ls->un = cseset_union(ls->un, nexts->un); { LLL_Loop *nxl, *xl = nexts->loops; for (; xl != NULL; xl = nxl) { nxl = cdr_(xl); cdr_(xl) = ls->loops; ls->loops = xl; } } order = cseset_compare(l->memberset, nexts->un); } goto nextloop; } } ls = CSENew(LoopSet); cdr_(ls) = *lsp; ls->loops = l; cdr_(l) = NULL; ls->un = cseset_copy(l->memberset); ls->xn = cseset_copy(l->memberset); *lsp = ls; nextloop:; } /* for each set of loops but the first, invent a new header and insert it between the original header and its predecessor */ if (debugging(DEBUG_CSE) && CSEDebugLevel(2)) { LoopSet *ls; cc_msg("loop sets (header %ld): ", (long)blklabname_(ll->header)); for (ls = loopsets; ls != NULL; ls = cdr_(ls)) { int c = '{'; LLL_Loop *l = ls->loops; for (; l != NULL; l = cdr_(l)) { cc_msg("%c%ld", c, (long)blklabname_(l->tail)); c = ' '; } if (cdr_(ls) == NULL) cc_msg("}\n"); else cc_msg("}, "); } } if (cdr_(loopsets) != NULL) { BlockHead *header = ll->header; /* we want to deal with the loops largest first */ LoopSet *ls = (LoopSet *)dreverse((List *)cdr_(loopsets)); ll->loops = loopsets->loops; for (; ls != NULL; ls = cdr_(ls)) { BlockHead *newheader = AddBlockBeforeHeader(header, "new header"); LLL_Loop *l; LoopListList *n; blkflags_(newheader) &= ~BLKLOOP; for (l = ls->loops; l != NULL; l = cdr_(l)) changesuccessors(l->tail, blklab_(newheader), blklab_(header)); n = CSENew(LoopListList); cdr_(n) = cdr_(ll); n->header = newheader; n->loops = ls->loops; cdr_(ll) = n; AddBlockToLoopsContaining(header, newheader); ll = n; } } } for (ll = looplists; ll != NULL; ll = cdr_(ll)) { BlockHead *header = ll->header; BlockHead *preheader = AddBlockBeforeHeader(header, "preheader"); AddBlockToLoopsContaining(header, preheader); for (l = ll->loops; l != NULL; l = cdr_(l)) all_loops = mk_LoopList(all_loops, l->members, preheader, header, l->tail); } } static void FindLoops(void) { BlockHead *p; BlockList *allbuttop = NULL; looplists = NULL; for (p=top_block; p != NULL; p = blkdown_(p)) if (blkflags_(p) & BLKSWITCH) { LabelNumber **v = blktable_(p); int32 i, n = blktabsize_(p); for (i=0; i<n; i++) AddLoop(p, v[i]); } else { AddLoop(p, blknext_(p)); if (blkflags_(p) & BLK2EXIT) AddLoop(p, blknext1_(p)); } InsertPreheaders(); for (p = blkdown_(top_block); p != NULL; p = blkdown_(p)) allbuttop = mk_CSEBlockList(allbuttop, p); { /* Since we no longer necessarily lift expressions from the fake outer loop into its preheader, we need to know which blocks are inside real loops (to avoid lifting into such blocks). */ LoopList *lp; loopmembers = NULL; for (lp = all_loops; lp != NULL; lp = cdr_(lp)) { BlockList *m = ll_mem_(lp); for (; m != NULL; m = cdr_(m)) { cseset_insert(blklabname_(m->blklstcar), loopmembers, NULL); } } /* @@@ This implies that the loop preheader for a loop is not included in the members of a containing loop (or it's pointless) : I believe this no longer to be the case. */ for (lp = all_loops; lp != NULL; lp = cdr_(lp)) if (cseset_member(blklabname_(blkup_(ll_prehdr_(lp))), loopmembers)) cseset_insert(blklabname_(ll_prehdr_(lp)), loopmembers, NULL); } /* Add a spurious whole function loop */ { BlockHead *h = MakePreheader(top_block, blknext_(top_block)->block); CSEFoundLoop(NULL, NULL, allbuttop); all_loops = mk_LoopList(all_loops, allbuttop, h, NULL, NULL); blkflags_(h) |= BLKOUTER; } } static bool PruneReached(BlockHead *defblock, LabelNumber *lab) { if (is_exit_label(lab)) return NO; { BlockHead *b = lab->block; if (!blk_reached_(b)) return NO; if (defblock == b) return NO; blk_reached_(b) = NO; return YES; } } static void FindRefIcodes(CSEDef *def, ExprnUse *uses) { BlockHead *defblock = defblock_(def); ExprnUse *defuse; CSERef *l, **prevp; /* There may be many occurrences of this expression in the block * defining it (because it is killed between them): we want the last, * which since the list is reversed we come to first */ for (defuse = uses ; defuse != NULL ; defuse = cdr_(defuse)) if (defuse->block == defblock) break; if (defuse == NULL) if (blklength_(defblock) != 0) syserr(syserr_cse_lost_def); else /* must be an extracted loop invariant */ defic_(def) = NULL; else if (!IsRealIcode(defuse)) defic_(def) = blkcode_(defblock)-1; else defic_(def) = &useicode_(defuse); for (l = defrefs_(def), prevp = &defrefs_(def) ; l != NULL ; l = cdr_(l)) { /* Again, there may be many references: we want the first in the block * (which we come to last): for all the others, the expression will * have a different value. */ ExprnUse *first = NULL; ExprnUse *use; for (use = uses ; use != NULL ; use = cdr_(use)) if (use->block == refblock_(l)) first = use; if (first == NULL) syserr(syserr_cse_lost_use); if (flags_(first) & U_NOTREF) { *prevp = cdr_(l); if (debugging(DEBUG_CSE)) cc_msg(" (%ld notref)", (long)blklabname_(refblock_(l))); } else { refuse_(l) = first; prevp = &cdr_(l); } } } static void DiscardDef(CSEDef *discard, CSEDef *keep) { cseset_discard(defuses_(discard)); defuses_(discard) = NULL; while (defrefs_(discard) != NULL) { CSERef *p; ExprnUse *use = refuse_(defrefs_(discard)); for (p = defrefs_(keep); p != NULL; p = cdr_(p)) if (refuse_(p) == use) break; if (p == NULL) defrefs_(keep) = mk_CSERef(defrefs_(keep), use); defrefs_(discard) = CSERef_DiscardOne(defrefs_(discard)); } } static void RemoveSubRefs(CSEDef *sub, CSEDef *super) { CSERef *subref; for (subref = defrefs_(sub); subref != NULL; subref = cdr_(subref)) { CSERef *p, **pp; ExprnUse *use = refuse_(subref); for (pp = &defrefs_(super); (p = *pp) != NULL; pp = &cdr_(p)) if (refuse_(p) == use) { *pp = CSERef_DiscardOne(p); break; } } } static void MakeSubdef(CSEDef *sub, CSEDef *super) { /* Add sub to the loopinv chain of super. Remove the refs to super which are also refs to sub. Do not alter super->uses, or its use in ordering defs will be defeated (it has no other use). */ if (defsuper_(sub) != NULL) { CSEDef *p, **pp = &defsub_(defsuper_(sub)); for (; (p = *pp) != sub; pp = &defnextsub_(p)) if (p == NULL) syserr(syserr_cse_makesubdef); *pp = defnextsub_(sub); } defsuper_(sub) = super; defnextsub_(sub) = defsub_(super); defsub_(super) = sub; RemoveSubRefs(sub, super); } static void LinkRefs(CSE *cse, CSEDef *def) { /* For the definition def of cse, find the uses of it (blocks for which * it is wanted) which the definition must reach. */ BlockHead *defblock = defblock_(def); bool local; if (defuses_(def) != NULL) { /* Non-null defuses here means a local CSE which may be subsumed */ if (debugging(DEBUG_CSE)) cc_msg(" %ld local", (long)blklabname_(defblock)); local = YES; } else { int32 exid = exid_(cseex_(cse)); int32 defnest = blknest_(defblock); BlockHead *p; bool changed; if (debugging(DEBUG_CSE)) cc_msg(" %ld r", (long)blklabname_(defblock)); for (p = top_block; p != NULL; p = blkdown_(p)) blk_reached_(p) = dominates(defblock, p); if (extype_(cseex_(cse)) != E_UNARYK) { /* Constants can't be killed, so they'll reach everything dominated by the block containing their definition. */ do { changed = NO; for (p=top_block; p!=NULL; p = blkdown_(p)) { if ( (!blk_reached_(p) && blk_dominators_(p) != NULL) || /* (that is, not unreachable) */ (p != defblock && blockkills(exid, p)) ) { if (blkflags_(p) & BLKSWITCH) { LabelNumber **v = blktable_(p); int32 i, n = blktabsize_(p); for (i=0; i<n; i++) changed = changed | PruneReached(defblock, v[i]); } else { changed = changed | PruneReached(defblock, blknext_(p)); if (blkflags_(p) & BLK2EXIT) changed = changed | PruneReached(defblock, blknext1_(p)); } } } } while (changed); } for (p = top_block; p != NULL; p = blkdown_(p)) { if (blk_reached_(p) && p != defblock) { cseset_insert(blklabname_(p), def->uses, NULL); if ( cseset_member(exid, blk_wanted_(p)) && blknest_(p) >= defnest /* this isn't exactly right; it should test that p is inside all loops which defblock is */ ) { defrefs_(def) = mk_CSERef(defrefs_(def), p); if (debugging(DEBUG_CSE)) cc_msg(" %ld", (long)blklabname_(p)); } } } local = NO; } if (defrefs_(def) != NULL) { /* if this isn't a local def, defrefs is a list of blocks; change it now to a list of ExprnUse. (which it already is for local defs) */ if (!local) FindRefIcodes(def, exuses_(cseex_(cse))); if ( (blkflags_(defblock) & BLKOUTER) && ( defrefs_(def) == NULL || /* findreficodes may have discarded some */ cdr_(defrefs_(def)) == NULL) ) { if (debugging(DEBUG_CSE)) cc_msg(": unwanted outer loop inv"); } else if (defrefs_(def) != NULL) { CSEDef **pp, *p; bool discard = NO; for (pp = &csedef_(cse) ; (p = *pp) != NULL ; pp = &cdr_(p)) { int cf = cseset_compare(defuses_(def), defuses_(p)); /* Equality can only happen here if one def is local */ if (cf == VR_SUBSET || (cf == VR_EQUAL && local)) { if (pseudo_reads_r2(exop_(cseex_(cse)))) { MakeSubdef(def, p); if (debugging(DEBUG_CSE)) cc_msg(": subdef of %ld", (long)blklabname_(defblock_(p))); } else { DiscardDef(def, p); if (debugging(DEBUG_CSE)) cc_msg(": killed (%ld)", (long)blklabname_(defblock_(p))); discard = YES; } break; } else if (cf == VR_SUPERSET || cf == VR_EQUAL) { if (pseudo_reads_r2(exop_(cseex_(cse)))) { if ( defsuper_(p) != NULL && cseset_compare(defuses_(def), defuses_(defsuper_(p))) == VR_SUPERSET) RemoveSubRefs(p, def); else { MakeSubdef(p, def); if (debugging(DEBUG_CSE)) cc_msg(": has subdef %ld", (long)blklabname_(defblock_(p))); } } else { DiscardDef(p, def); if (debugging(DEBUG_CSE)) cc_msg(": kills %ld", (long)blklabname_(defblock_(p))); } } } if (!discard) { cdr_(def) = p; *pp = def; } } } if (debugging(DEBUG_CSE)) cc_msg("\n"); } static void LinkRefsToDefs(void) { CSE *cse; for ( cse = cselist ; cse != NULL ; cse = cdr_(cse) ) { CSEDef *def = csedef_(cse), *next; csedef_(cse) = NULL; if (debugging(DEBUG_CSE)) cse_print_node(cseex_(cse)); for (; def != NULL ; def = next) { /* There used to be code here to discard this def if it was a ref of one previously encountered, (to save work, since LinkRefs() would anyway discard it). Now we want to do something more complicated, the check has been retired. We remove def from the list, linkrefs will add it in the appropriate place (sorted subdefs first) */ next = cdr_(def); LinkRefs(cse, def); } if (debugging(DEBUG_CSE)) { cc_msg(" sorted:\n"); for (def = csedef_(cse); def != NULL ; def = cdr_(def)) { CSERef *ref = defrefs_(def); cc_msg(" %ld:", blklabname_(defblock_(def))); for (; ref != NULL; ref = cdr_(ref)) cc_msg(" %ld", blklabname_(refuse_(ref)->block)); if (defsub_(def) != NULL) { CSEDef *sub = defsub_(def); char *s = " <"; for (; sub != NULL; sub = defnextsub_(sub)) { cc_msg("%s%ld", s, blklabname_(defblock_(sub))); s = " "; } cc_msg(">"); } cc_msg("\n"); } } } } static bool SafeToLift(Exprn *ex) { J_OPCODE op = exop_(ex) & J_TABLE_BITS; switch (extype_(ex)) { case E_UNARYK: return YES; case E_BINARY: switch (op) { case J_CHKUR: case J_CHKLR: case J_CHKNEFR: case J_CHKNEDR: case J_DIVR: case J_REMR: case J_DIVFR: case J_DIVDR: return NO; default: /* what about other floating pt ops ? */ return (SafeToLift(e2_(ex)) && SafeToLift(e1_(ex))); } case E_TERNARY: return (SafeToLift(e3_(ex)) && SafeToLift(e2_(ex)) && SafeToLift(e1_(ex))); case E_BINARYK: switch (op) { case J_CHKUK: case J_CHKLK: case J_CHKNEK: return NO; case J_DIVK: case J_REMK: if (e2k_(ex) == 0) return NO; } /* drop through - what about floating pt ? */ case E_UNARY: return SafeToLift(e1_(ex)); default: case E_MISC: syserr(syserr_cse_safetolift); case E_CALL: case E_LOADR: return NO; case E_LOAD: { Location *loc = exloc_(ex); if (loctype_(loc) & LOC_anyVAR) return YES; return (cse_AdconBase(locbase_(loc), NO) != NULL); } } } static void AddIfSafe(int32 n, void *arg) { if (SafeToLift(exprn_(n))) AddCSE(n, arg); } static void FindLoopInvariants(void) { LoopList *p; for (p = all_loops ; p != NULL ; p = cdr_(p)) { BlockHead *b = ll_prehdr_(p); BlockList *bl; VRegSetP w = cseset_copy(blk_wantedlater_(b)); VRegSetP we = cseset_copy(blk_wantedonallpaths_(b)); VRegSetP u = NULL; for (bl = p->members ; bl != NULL ; bl = cdr_(bl)) { BlockHead *c = bl->blklstcar; cseset_union(u, blk_wanted_(c)); if (blk_killedinverted_(c)) { cseset_intersection(w, blk_killed_(c)); cseset_intersection(we, blk_killed_(c)); } else { cseset_difference(w, blk_killed_(c)); cseset_difference(we, blk_killed_(c)); } } cseset_difference(w, we); cseset_intersection(w, u); cseset_intersection(we, u); cseset_discard(u); if (debugging(DEBUG_CSE)) { cc_msg("Loop L%ld:", (long)blklabname_(b)); for (bl = p->members ; bl != NULL ; bl = cdr_(bl)) cc_msg(" %ld", (long)blklabname_(bl->blklstcar)); cc_msg(": safe"); cse_printset(we); cc_msg("; unsafe"); cse_printset(w); cc_msg("\n"); } cseset_map(we, AddCSE, (VoidStar)b); cseset_map(w, AddIfSafe, (VoidStar)b); } } static BindList *nconcbl(BindList *l, BindList *bl) { /* Returns its first argument, adjusted to have as its tail the BindList bl if it didn't on entry (Bindlists in the places being adjusted share tails, so after the first has been adjusted many others will already be right). */ BindList *p = l; BindList *prev = NULL; for ( ; p != NULL ; prev = p, p = cdr_(p) ) if (p == bl) return l; if (prev == NULL) return bl; cdr_(prev) = bl; return l; } static Icode *StoreCSE2(Icode *newic, VRegnum r1, Binder *binder) { newic = newic+1; INIT_IC(*newic, CSEaccessOp(r1, J_STRV)); newic->r1.r = r1; newic->r3.b = binder; return newic; } static Icode *StoreCSE(Icode *newic, CSEDef *def) { /* ADCONs etc get treated specially here, in that rather than store into the CSE binder, we use an ADCON with the register for the CSE binder as r1. This is so that, if the binder gets spilled, the ADCON is voided. (The load of the CSE register is inserted before the original instruction, so that can be turned into a use of the CSE in case it isn't spilled). */ VRegnum r1 = newic->r1.r; if (is_calln(defex_(def))) { int32 i, nres = exnres_(defex_(def)); r1 = R_A1; /* Local CSE def which is a non-local ref */ /* @@@ presumably, this should never happen now */ /* r2 = call->r1.r;*/ for (i = 1; i < nres; i++) newic = StoreCSE2(newic, r1+i, defbinder_(def, i)); } #ifdef TARGET_ALLOWS_COMPARE_CSES if (is_compare(exop_(defex_(def)))) { newic->op = (newic->op & ~Q_MASK) | defmask_(def); blkflags_(defblock_(def)) |= BLKCCEXPORTED; return newic; } #endif if (j_is_check(exop_(defex_(def)))) return newic; if (defbinder_(def, 0) == NULL) syserr(syserr_storecse, (long)blklabname_(defblock_(def)), (long)exid_(defex_(def))); if (pseudo_reads_r2(newic->op)) { VRegnum b = bindxx_(defbinder_(def, 0)); Icode *ic = newic+1; *ic = *newic; ic->r2.r = newic->r1.r = b; if (newic->r2.r != GAP) { forget_slave(ic->r1.r, newic->r2.r); note_slave(b, newic->r2.r); } note_slave(ic->r1.r, b); return ic; } else if (pseudo_reads_r1(newic->op)) { VRegnum b = bindxx_(defbinder_(def, 0)); Icode *ic = newic+1; *ic = *newic; newic->op = exop_(defex_(def)); newic->r2.r = ic->r1.r; if (ic->r1.r != GAP) note_slave(b, ic->r1.r); ic->r1.r = newic->r1.r = b; return ic; } else return StoreCSE2(newic, r1, defbinder_(def, 0)); } static int32 DefsSize(CSEDef *defs) { int32 ndefs = 0; for (; defs != NULL; defs = cdr_(defs)) if (is_calln(defex_(defs))) ndefs += exnres_(defex_(defs)); else if (!is_compare(exop_(defex_(defs))) && !j_is_check(exop_(defex_(defs)))) ndefs++; cse_count += ndefs; return ndefs; } typedef struct CopyList CopyList; typedef struct CopyCSE CopyCSE; typedef struct CopyListList CopyListList; struct CopyList { CopyList *cdr; Icode icode; CopyCSE *cse; Exprn *exprn; int level; }; #define cl_ic_(p) ((p)->icode) #define cl_cse_(p) ((p)->cse) #define cl_exprn_(p) ((p)->exprn) #define cl_level_(p) ((p)->level) struct CopyListList { CopyListList *cdr; CopyList *p; int resno; }; #define cl_(q) ((q)->p) #define cll_resno_(q) ((q)->resno) #define mk_CopyListList(a,b,c) ((CopyListList*)CSEList3((a),(b),(c))) typedef struct CSEDefList CSEDefList; struct CSEDefList { CSEDefList *cdr; CSEDef *def; }; #define dl_def_(p) ((p)->def) #define mk_CSEDefList(a,b) ((CSEDefList *)CSEList2((a),(b))) struct CopyCSE { CopyCSE *cdr; CopyList *def; CopyListList *refs; CSEDefList *csedefs; }; static CopyCSE *addeddefs; static CopyList *mk_CopyList( CopyList *cl, Exprn *exprn, const Icode *const ic, int level) { CopyList *q = CSENew(CopyList); cdr_(q) = cl; cl_cse_(q) = NULL; cl_exprn_(q) = exprn; cl_level_(q) = level; cl_ic_(q) = *ic; return q; } typedef struct LiftedTernaryList LiftedTernaryList; struct LiftedTernaryList { LiftedTernaryList *cdr; Exprn *ex; union { CopyList *cl; Icode *ic; BlockHead *b; } e1, e2, e3; }; #define lt_ex_(p) ((p)->ex) #define lt_mask_(p) (exmask_(lt_ex_(p))) #define lt_ic1_(p) ((p)->e1.ic) #define lt_ic2_(p) ((p)->e2.ic) #define lt_ic3_(p) ((p)->e3.ic) #define lt_cl1_(p) ((p)->e1.cl) #define lt_cl2_(p) ((p)->e2.cl) #define lt_cl3_(p) ((p)->e3.cl) #define lt_b1_(p) ((p)->e1.b) #define lt_b2_(p) ((p)->e2.b) #define lt_b3_(p) ((p)->e3.b) typedef struct { LiftedTernaryList *ternaries; int32 callcount; } AEB_Res; static CopyList *AddExprnsBelow( CopyList *cl, Exprn *exprn, int level, VRegnum targetr, CopyList **clp, AEB_Res *resp); static VRegnum aeb_argumentreg( CopyList **cl, Exprn *e, AEB_Res *resp, int resno, int level, VRegnum targetr) { CopyList *arg; *cl = AddExprnsBelow(*cl, e, level+1, targetr, &arg, resp); if (cl_cse_(arg) == NULL) return cl_ic_(arg).r1.r; else { Icode ic; VRegnum oldr = cl_ic_(arg).r1.r, newr = targetr == GAP ? vregister(vregsort(oldr)) : targetr; if (pseudo_reads_r2(exop_(e))) { INIT_IC(ic, cl_ic_(arg).op); ic.r1.r = newr; ic.r3 = cl_ic_(arg).r3; *cl = mk_CopyList(*cl, NULL, &ic, level); } else { INIT_IC(ic, CSEaccessOp(oldr, J_LDRV)); ic.r1.r = newr; ic.r3.i = 0; *cl = mk_CopyList(*cl, NULL, &ic, level); } cl_cse_(arg)->refs = mk_CopyListList(cl_cse_(arg)->refs, *cl, resno); return newr; } } static CopyCSE *mk_CopyCSE(CopyList *p) { CopyCSE *q = CSENew(CopyCSE); cdr_(q) = addeddefs; q->def = p; q->refs = NULL; q->csedefs = NULL; addeddefs = q; return q; } static CopyList *AddExprnsBelow( CopyList *cl, Exprn *exprn, int level, VRegnum targetr, CopyList **clp, AEB_Res *resp) { CopyList *p; if (is_compare(exop_(exprn))) p = NULL; else for (p = cl ; p != NULL ; p = cdr_(p)) if (cl_exprn_(p) == exprn) { if (cl_cse_(p) == NULL) cl_cse_(p) = mk_CopyCSE(p); break; } if (p == NULL) { Icode ic; RegSort r1sort; INIT_IC(ic, exop_(exprn)); r1sort = DestRegSort(ic.op); ic.r1.r = targetr != GAP ? targetr : r1sort == GAP ? GAP : vregister(r1sort); switch (extype_(exprn)) { case E_UNARYK: ic.r3.i = e1k_(exprn); break; case E_UNARY: { int resno = 0; if (ic.op == J_RESULT2) resno = 1, ic.op = J_MOVR; ic.r3.r = aeb_argumentreg(&cl, e1_(exprn), resp, resno, level+1, GAP); } break; case E_BINARYK: ic.r2.r = aeb_argumentreg(&cl, e1_(exprn), resp, 0, level+1, GAP); ic.r3.i = e2k_(exprn); break; case E_BINARY: ic.r2.r = aeb_argumentreg(&cl, e1_(exprn), resp, 0, level+1, GAP); ic.r3.r = aeb_argumentreg(&cl, e2_(exprn), resp, 0, level+1, GAP); break; case E_TERNARY: { LiftedTernaryList *p = CSENew(LiftedTernaryList); ic.op = J_NOOP | exmask_(exprn); aeb_argumentreg(&cl, e1_(exprn), resp, 0, level+1, GAP); cdr_(p) = resp->ternaries; resp->ternaries = p; lt_cl1_(p) = cl; ic.r1.r = aeb_argumentreg(&cl, e2_(exprn), resp, 0, level+1, GAP); lt_cl2_(p) = cl; aeb_argumentreg(&cl, e3_(exprn), resp, 0, level+1, ic.r1.r); lt_cl3_(p) = cl; lt_ex_(p) = exprn; break; } case E_LOAD: { /* Loads need greater care, because they have been transformed into compute address; ldrk but transforming back is subject to constraints I'd rather not know about. (eg on ARM ldrr<<2 r1, r2, r3 but addr<<2 r1, r2, r3; ldrfk f1, r1, 0) To sidestep this problem, transformed loads have been marked as such and must be transformed back here. */ Location *loc = exloc_(exprn); if (loctype_(loc) & LOC_anyVAR) { ic.r3.b = locbind_(loc); ic.op = J_KtoV(ic.op); } else { Exprn *base = locbase_(loc); if (locrealbase_(loc)) { /* an untransformed load: must be copied as it stands */ ic.r2.r = aeb_argumentreg(&cl, base, resp, 0, level+1, GAP); ic.r3.i = locoff_(loc); } else { /* base must be one of ADDR, SUBR or ADCONV */ J_OPCODE baseop = exop_(base); switch (UnshiftedOp(baseop)) { case J_SUBR: #ifdef TARGET_HAS_SCALED_ADDRESSING ic.op |= J_NEGINDEX; /* and fall through to treat as ADDR */ case J_ADDR: ic.op |= (baseop & J_SHIFTMASK); #else case J_ADDR: #endif ic.op = J_KTOR(ic.op); ic.r2.r = aeb_argumentreg(&cl, e1_(base), resp, 0, level+1, GAP); ic.r3.r = aeb_argumentreg(&cl, e2_(base), resp, 0, level+1, GAP); break; case J_ADCONV: ic.r3.b = e1b_(base); ic.r2.r = locoff_(loc); ic.op = J_addvk(ic.op); break; default: syserr(syserr_baseop, (long)baseop); } } } } break; case E_CALL: { int32 nargs = exnargs_(exprn), i; CopyList *arglist = NULL; ++resp->callcount; for (i = 0 ; i < nargs ; i++) { Icode ic1; bool isfp = exargisfp_(exprn, i); Exprn *thisarg = exarg_(exprn, i); Exprn *nextarg; VRegnum argreg = isfp ? R_FA1+i : R_A1+i-k_fltregs_(exargdesc_(exprn)); /* CSE_WORD1/2 only used if !TARGET_FP_ARGS_CALLSTD2 */ if ( exop_(thisarg) == CSE_WORD1 && (i+1) < nargs && !k_argisfp_(exargdesc_(exprn), i+1) && exop_(nextarg = exarg_(exprn, i+1)) == CSE_WORD2 && e1_(thisarg) == e1_(nextarg) ) { CopyList *arg; cl = AddExprnsBelow(cl, e1_(thisarg), level+1, GAP, &arg, resp); INIT_IC(ic1, J_MOVDIR); ic1.r1.r = argreg; ic1.r2.r = argreg + 1; ic1.r3 = cl_ic_(arg).r1; arglist = mk_CopyList(arglist, NULL, &ic1, level+1); i++; } else if (exop_(thisarg) == CSE_WORD1 || exop_(thisarg) == CSE_WORD2) syserr(syserr_cse_wordn); else { INIT_IC(ic1, isfp ? J_MOVDR : J_MOVR); ic1.r1.r = argreg; ic1.r3.r = aeb_argumentreg(&cl, exarg_(exprn, i), resp, 0, level+1, GAP); arglist = mk_CopyList(arglist, NULL, &ic1, level+1); } } cl = (CopyList *)nconc(dreverse((List *)arglist), (List *)cl); { RegSort restype = exfntype_(exprn); ic.r2.i = exargdesc_(exprn) | K_PURE; ic.r1.r = V_resultreg(restype); ic.r3.b = exfn_(exprn); cl = mk_CopyList(cl, exprn, &ic, level); cl_cse_(cl) = mk_CopyCSE(cl); *clp = cl; return cl; } } } cl = p = mk_CopyList(cl, exprn, &ic, level); } *clp = p; return cl; } typedef struct { CopyList *cl; int32 ndefs; LiftedTernaryList *ternaries; } IcodeToCopyRes; static CopyList *IcodeToCopy_i(CSEDef *defs, AEB_Res *resp) { CopyList *res = NULL, *p; addeddefs = NULL; for ( ; defs != NULL ; defs = cdr_(defs)) if (defic_(defs) == NULL) { res = AddExprnsBelow(res, defex_(defs), 0, GAP, &p, resp); if (cl_cse_(p) == NULL) { cl_cse_(p) = mk_CopyCSE(p); } cl_cse_(p)->csedefs = mk_CSEDefList(cl_cse_(p)->csedefs, defs); } return (CopyList *)dreverse((List *)res); } static IcodeToCopyRes IcodeToCopy(BlockHead *b, CSEDef *defs, BindList *bl) { IcodeToCopyRes res; AEB_Res aeb; aeb.callcount = 0; aeb.ternaries = NULL; { CopyList *c = IcodeToCopy_i(defs, &aeb); int32 n = length((List *) c); BindList **bp = &cdr_(bl); for (; addeddefs != NULL; addeddefs = cdr_(addeddefs)) if (addeddefs->csedefs == NULL) { /* Observe that if we're doing this, bl must be non-null - so * adding new binders generated here after the first element of * bl is safe (and saves trouble with the code for modifying * SETSPENVs). */ VRegnum r1 = addeddefs->def->icode.r1.r; CSEDef *csedef = mk_CSEDef(addeddefs->def->exprn, b); J_OPCODE op = addeddefs->def->icode.op; if (is_calln(addeddefs->def->exprn)) { int32 i, nres = exnres_(addeddefs->def->exprn); for (i = 1; i < nres; i++) { defbinder_(csedef, i) = AddCSEBinder(op, bp, r1); n++; } } defic_(csedef) = &addeddefs->def->icode; if (!j_is_check(defic_(csedef)->op)) { defbinder_(csedef, 0) = AddCSEBinder(op, bp, r1); n++; } addeddefs->csedefs = mk_CSEDefList(NULL, csedef); } if (aeb.callcount == 1 && !(blkflags_(b) & BLKCALL)) blkflags_(b) |= BLKCALL; else if (aeb.callcount >= 1) blkflags_(b) |= BLKCALL | BLK2CALL; res.cl = c; res.ndefs = n; res.ternaries = (LiftedTernaryList *)dreverse((List *)aeb.ternaries); return res; } } static Icode *CopyIcode(Icode *newic, CopyList *c, LiftedTernaryList *tl) { for ( ; c != NULL ; c = cdr_(c)) { *newic = cl_ic_(c); if (cl_cse_(c) != NULL) { CopyListList *refs = cl_cse_(c)->refs; CSEDefList *defs = cl_cse_(c)->csedefs; J_OPCODE op = newic->op; for (; defs != NULL; defs = cdr_(defs)) { CSEDef *def = dl_def_(defs); Binder *b = defbinder_(def, 0); if (def->super != NULL && defs == cl_cse_(c)->csedefs) { /* Only do this when the superdef is in some other block. * (i.e. only for the first in a sequence of defs for the * same cse). */ VRegnum r = bindxx_(defbinder_(defsuper_(def), 0)); newic->r2.r = r; note_slave(newic->r1.r, r); } if (b != NULL) { if (pseudo_reads_r2(op) && defrefs_(def) == NULL && cl_level_(c) == 0) { VRegnum r = bindxx_(defbinder_(def, 0)); if (newic->r2.r != GAP) { forget_slave(newic->r1.r, newic->r2.r); note_slave(r, newic->r2.r); } *(newic+1) = *newic; newic->op = J_NOOP; newic++; newic->r1.r = r; } else newic = StoreCSE(newic, def); } for (; refs != NULL; refs = cdr_(refs)) { Icode *ic = &cl_ic_(cl_(refs)); #ifdef RANGECHECK_SUPPORTED if (b == NULL) ic->op = J_NOOP; else #endif if (pseudo_reads_r2(cl_ic_(c).op)) { ic->r2.r = bindxx_(b); note_slave(ic->r1.r, bindxx_(b)); } else if (cll_resno_(refs) == 1) ic->r3.b = defbinder_(def, 1); else ic->r3.b = b; } } } newic++; { LiftedTernaryList *p; for (p = tl; p != NULL; p = cdr_(p)) { if (lt_cl1_(p) == c) lt_ic1_(p) = newic; if (lt_cl2_(p) == c) lt_ic2_(p) = newic; if (lt_cl3_(p) == c) lt_ic3_(p) = newic; } } } return newic; } static CSERef *FindRealRef(CSEDef *d) { for (; d != NULL; d = defnextsub_(d)) { if (defrefs_(d) != NULL) return defrefs_(d); if (d->subdefs != NULL) { CSERef *ref = FindRealRef(defsub_(d)); if (ref != NULL) return ref; } } return NULL; } static BindList *ReferenceCSEDefs(BindList *bl, CSEDef *def, CSEUseList **deferredp) { CSEUseList *deferred = NULL; for ( ; def != NULL ; def = cdr_(def)) { CSERef *ref = defrefs_(def); #ifdef TARGET_ALLOWS_COMPARE_CSES if (is_compare(exop_(defex_(def)))) defmask_(def) = defic_(def)->op & Q_MASK; #endif if (ref != NULL || defsub_(def) != NULL) { bool defer = NO; if ( #ifdef TARGET_ALLOWS_COMPARE_CSES is_compare(exop_(defex_(def))) || #endif j_is_check(exop_(defex_(def)))) { defbinder_(def, 0) = NULL; if (debugging(DEBUG_CSE)) cc_msg("\n: "); } else { J_OPCODE op = exop_(defex_(def)); VRegnum r1; CSERef *realref = FindRealRef(def); if (realref == NULL) syserr(syserr_referencecsedefs); r1 = (op == CSE_COND) ? blk_ternaryr_(refuse_(realref)->block) : useicode_(refuse_(realref)).r1.r; defbinder_(def, 0) = AddCSEBinder(op, &bl, r1); if (debugging(DEBUG_CSE)) cc_msg("\n$b [%ld]: ", defbinder_(def, 0), (long)bindxx_(defbinder_(def, 0))); if (is_calln(defex_(def))) { int32 i, nres = exnres_(defex_(def)); for (i = 1; i < nres; i++) { Binder *b = defbinder_(def, i) = AddCSEBinder(op, &bl, r1); if (debugging(DEBUG_CSE)) cc_msg("$b [%ld]: ", b, (long)bindxx_(b)); } } } if (debugging(DEBUG_CSE)) { cc_msg("%ld/", (long)blklabname_(defblock_(def))); if (blklength_(defblock_(def)) == 0) cc_msg("loop inv: "); else cc_msg("%ld: ", (long)(defic_(def)-blkcode_(defblock_(def)))); cse_print_node(defex_(def)); } for ( ; ref != NULL ; ref = cdr_(ref)) deferred = ReplaceIcode(deferred, refuse_(ref), def); } } *deferredp = deferred; return bl; } static CSERef *FindAnyRef(CSEDef *sub) { CSEDef *p; for (p = sub; p != NULL; p = defnextsub_(p)) if (defrefs_(p) != NULL) return defrefs_(p); for (p = sub; p != NULL; p = defnextsub_(p)) if (defsub_(p) != NULL) { CSERef *ref = FindAnyRef(defsub_(p)); if (ref != NULL) return ref; } return NULL; /* should never happen */ } static void AddCSEDefsToBlock(CSEDef *def) { CSEDef *next; for (; def != NULL; def = next) { next = cdr_(def); if (defrefs_(def) != NULL || defsub_(def) != NULL) { BlockHead *b = defblock_(def); if (blkflags_(b) & BLKOUTER) { /* for expressions lifted out of the fake outer "loop", we wish to lift them not to the loop preheader, but to the nearest block which dominates all references. */ CSERef *ref = defrefs_(def), *anyref = ref; CSEDef *sub = defsub_(def); VRegSetP d; bool discard = NO; if (ref != NULL) b = refuse_(ref)->block, ref = cdr_(ref); else b = defblock_(sub), sub = defnextsub_(sub); d = cseset_copy(blk_dominators_(b)); cseset_difference(d, loopmembers); for (; ref != NULL; ref = cdr_(ref)) cseset_intersection(d, blk_dominators_(refuse_(ref)->block)); for (; sub != NULL; sub = sub->nextsub) { cseset_intersection(d, blk_dominators_(defblock_(sub))); if (anyref == NULL) anyref = defrefs_(sub); } if (anyref == NULL) anyref = FindAnyRef(defsub_(def)); for (;;) { bool dummy; for (b = top_block; b != NULL; b = blkdown_(b)) if (cseset_member(blklabname_(b), d) && cseset_compare(d, blk_dominators_(b)) <= VR_EQUAL) /* (equal or subset) */ break; if (b == NULL) syserr(syserr_addcsedefs); /* Don't lift code which alters condition codes into a block which relies on their setting on entry. */ if (!(blkflags_(b) & BLKCCLIVE) || (IsRealIcode(refuse_(anyref)) && !alterscc(&useicode_(refuse_(anyref))))) break; cseset_delete(blklabname_(b), d, &dummy); } { /* if the block to which we've decided to lift the expression contains a reference, it's not a lifted CSE. There may be many references in the block, thanks to an amalgamated local CSE. */ CSEDef **subp = &defsub_(def); /* First check for a lifted reference */ for (; (sub = *subp) != NULL; subp = &defnextsub_(sub)) if (defblock_(sub) == b) { defsuper_(sub) = NULL; *subp = defnextsub_(sub); { CSEDef *p, *oldsubdefs = defsub_(sub); defsub_(sub) = defsub_(def); subp = &defsub_(sub); for (; (p = *subp) != NULL; subp = &defnextsub_(p)) defsuper_(p) = sub; *subp = oldsubdefs; } discard = YES; break; } if (!discard) { CSERef **prev = &defrefs_(def); CSERef **defpref = NULL; Icode *deficode = NULL; for (; (ref = *prev) != NULL; prev = &cdr_(ref)) if (b == refuse_(ref)->block) { if (pseudo_reads_r2(exop_(defex_(def)))) { discard = YES; break; } else { Icode *reficode; if (IsRealIcode(refuse_(ref))) reficode = &useicode_(refuse_(ref)); else reficode = blkcode_(b)-1; if (deficode != NULL && deficode < reficode) continue; defpref = prev; deficode = reficode; } } if (deficode != NULL) { defic_(def) = deficode; *defpref = cdr_(*defpref); } } } if (debugging(DEBUG_CSE)) if (!(blkflags_(b) & BLKOUTER)) cc_msg("%ld %s : %ld\n", (long)exid_(defex_(def)), (discard ? "discarded" : defic_(def) == NULL ? "(lifted)" : "(not lifted)"), (long)blklabname_(b)); if (discard) continue; defblock_(def) = b; } { CSEDef **prevp = &blk_defs_(b); CSEDef *p = blk_defs_(b); /* CSEDefs are ordered by the position of their definition within the block, with those corresponding to lifted expressions (where there is no definition in the block) coming last. */ for (; p != NULL; p = cdr_(p)) { if ( defic_(def) != 0 && (defic_(p) == 0 || defic_(p) > defic_(def))) break; prevp = &cdr_(p); } *prevp = def; cdr_(def) = p; } } } } #ifdef TARGET_ALLOWS_COMPARE_CSES static bool CantMarkCCLive(LabelNumber *from, BlockHead *to) { BlockHead *p; LabelNumber *lab; VRegSetP visited = NULL; for (lab = from; ; lab = blknext_(p)) { bool already; if (is_exit_label(lab)) return YES; cseset_insert(lab_name_(lab), visited, &already); if (already) return YES; p = lab->block; if (p == to) break; if (blkflags_(p) & (BLKSWITCH+BLK2EXIT)) return YES; } for (p = from->block; ; p = blknext_(p)->block) { blkflags_(p) |= BLKCCLIVE; if (p == to) break; } cseset_discard(visited); return NO; } #endif static int CompPtr(void const *a, void const *b) { IPtr d = (IPtr)a - (IPtr)b; if (d == 0) return 0; else if (d < 0) return -1; else return 1; } static int32 LookUpIC(Icode const *p, Icode * const *ic, int32 n) { int32 i; for (i = 0; i < n; i++) if (p == ic[i]) return i; syserr("LookUpIc"); return n; } static BindList *ModifyCode(void) { CSE *cse; BindList *bl = NULL; CSEUseList *deferred = NULL; /* Hang CSE definitions off the heads of the blocks containing them * (sorted by the order of their occurrence in the block). */ #ifdef TARGET_ALLOWS_COMPARE_CSES /* compares as CSEs must inhibit lifting of expressions which affect the * condition codes into any block between the successor of the defining * block and the referencing block (inclusive). * (observe that a block can contain at most one compare, so it would be * foolish to process localcsedefs here). */ for (cse = cselist ; cse != NULL ; cse = cdr_(cse)) if (is_compare(exop_(cse->exprn))) { CSEDef *def = cse->def; for (; def != NULL; def = cdr_(def)) { BlockHead *defblock = defblock_(def); CSERef *ref = defrefs_(def); for (; ref != NULL; ref = cdr_(ref)) { /* the blocks between the defining and referencing ones must * all be single-exit (other types would destroy the condition * codes). */ BlockHead *refblock = refuse_(ref)->block; /* nb MarkCCLive applied to both paths from the defining block */ if (CantMarkCCLive(blknext_(defblock), refblock) & CantMarkCCLive(blknext1_(defblock), refblock)) syserr(syserr_cse_modifycode_2, (long)blklabname_(refblock), (long)blklabname_(defblock)); } } } #endif for (cse = cselist ; cse != NULL ; cse = cdr_(cse)) AddCSEDefsToBlock(cse->def); AddCSEDefsToBlock(localcsedefs); /* Allocate binders for referenced CSE defs, and also replace the */ /* references by loads from the binders. We can't do the latter */ /* yet for references using more than one result of a CSE (pure */ /* functions calls returning a structure) because to do so would */ /* require lengthening the block containing the reference, so */ /* add these to the deferred list. */ { BlockHead *b; for (b = top_block; b != NULL; b = blkdown_(b)) bl = ReferenceCSEDefs(bl, blk_defs_(b), &deferred); } /* Allocate members of the deferred list to the blocks containing */ /* the references (sorting them by position within the block) */ { CSEUseList *next; for (; deferred != NULL; deferred = next) { CSEUseList **pp, *p; BlockHead *b = u_block_(ul_use_(deferred)); ptrdiff_t icn = icoden_(ul_use_(deferred)); next = cdr_(deferred); for (pp = &blk_refs_(b); (p = *pp) != NULL; pp = &cdr_(p)) if (icoden_(ul_use_(p)) > icn) break; cdr_(deferred) = p; *pp = deferred; } } /* Now add stores into the binders created for eliminated expressions. * This means lengthening the code in existing blocks: we could be clever * about doing this (largest first, allowing the space for most of the rest * to be reused). Later, perhaps. * While I'm doing this, destructively alter all non-null binder chains in * block heads to end in the cse list, and all null ones to be the cse list. * (Except for the first block - the binders don't exist on function entry. * We're going to create a SETSPENV to introduce them at the end of the * first block). The intent is to cause the extent of cse binders to be * the whole function. Later, we can be more precise. * Do chains in J_SETSPxx first. These need care to avoid changing the * new binder chain for a SETSPENV immediately before a return from null. * (Otherwise, return from a function which stores things on the stack but * doesn't create a frame will be compromised). * There can't be returns without a preceding SETSPENV: cg has been fixed * to ensure it. See cg_return. */ { SetSPList *p; for ( p = setsplist ; p != NULL ; p = cdr_(p) ) { BlockHead *b = p->block; Icode *ic = p->icode; ic->r2.bl = nconcbl(ic->r2.bl, bl); if ( ic->op == J_SETSPENV && ( (ic+1) - blkcode_(b) != blklength_(b) || !is_exit_label(blknext_(b)))) ic->r3.bl = nconcbl(ic->r3.bl, bl); /* J_SETSPGOTO is done */ } } { BlockHead *b; for ( b = blkdown_(top_block) ; b != NULL ; b = blkdown_(b) ) { /* AM thinks that the code consider the possible presence of */ /* double_pad_binder and integer_binder (see cg.c) means that this */ /* insertion (which I take to be adding to bindlists at the start of */ /* blocks) needs to be rather more careful. */ CSEDef *defs = blk_defs_(b); CSEDef *defs2 = blk_defs2_(b); CSEUseList *refs = blk_refs_(b); blkstack_(b) = nconcbl(blkstack_(b), bl); if (defs != NULL || defs2 != NULL || refs != NULL) { /* Now we can have a block containing both real CSE defs and lifted ones */ IcodeToCopyRes icr = IcodeToCopy(b, defs, bl); int32 oldlength; Icode *newic; Icode *old; int32 i; int32 ndefs = DefsSize(defs) + icr.ndefs; if (defs2 != NULL) ndefs++; { CSEUseList *up = refs; for (; up != NULL; up = cdr_(up)) ndefs += nvals_(ul_use_(up)); } oldlength = blklength_(b); newic = newicodeblock(oldlength+ndefs); old = blkcode_(b); blkcode_(b) = newic; /* CSEs for ternary expressions must be handled */ /* specially, because there's no jopcode to define the */ /* CSE or to be replaced by its reference. There can be */ /* at most one in a block (and the def if present is at */ /* the front of the list of defs for the block) */ /* We must take care not to treat lifted ternaries as */ /* ordinary defs: they are handled later. */ if (defs2 != NULL) { VRegnum r1 = blk_ternaryr_(b); INIT_IC(*newic, CSEaccessOp(r1, J_LDRV)); newic->r1.r = r1; newic->r3.b = defbinder_(defs2, 0); newic++; } if (defs != NULL && exop_(defex_(defs)) == CSE_COND && defic_(defs) != NULL) { VRegnum r1 = blk_ternaryr_(b); INIT_IC(*newic, CSEaccessOp(r1, J_STRV)); newic->r1.r = r1; newic->r3.b = defbinder_(defs, 0); newic++; defs = cdr_(defs); } for ( i = 0 ; i != blklength_(b) ; i++ ) { *newic = old[i]; while (refs != NULL && i == icoden_(ul_use_(refs))) { ExprnUse *use = ul_use_(refs); int32 i, base = valno_(use), nres = nvals_(use); VRegnum r1 = newic->r1.r; --newic; for (i = 0; i <= nres; i++) { ++newic; INIT_IC(*newic, J_NOOP); ReplaceWithLoad(newic, r1, defbinder_(ul_def_(refs), base+i)); newic->r1.r = base+i; } refs = cdr_(refs); } while (defs != NULL && &old[i] == defic_(defs)) { /* At the moment, there may be both a non-local and a local def for the same icode (if the exprn was killed earlier in the block) */ newic = StoreCSE(newic, defs); defs = cdr_(defs); } newic++; } if (defs != NULL) { if ( oldlength != 0 && (blkflags_(b) & (BLKSWITCH | BLK2EXIT))) { /* J_CASEBRANCH or J_CMP must be the last op in the block. Copy from newic rather than old, because J_CMPK may have had its r1 field changed from GAP. */ Icode ic; ic = *--newic; newic = CopyIcode(newic, icr.cl, icr.ternaries); *newic++ = ic; } else newic = CopyIcode(newic, icr.cl, icr.ternaries); } if (oldlength != 0) freeicodeblock(old, oldlength); blklength_(b) += ndefs; if ((newic - blkcode_(b)) != blklength_(b)) { Icode *ic = blkcode_(b); for (; ic != newic; ic++) print_jopcode(ic); syserr(syserr_cse_modifycode, (long)blklabname_(b), (long)(newic - blkcode_(b)), (long)blklength_(b)); } /* The call to CopyIcode above copied the icodes making */ /* up a ternary expression, but into a single block. We */ /* must now break up the single block into several, and */ /* generate the conditional branches, to recreate the */ /* real expressions. */ if (icr.ternaries != NULL) { int32 i, n = 3 * length((List *)icr.ternaries); Icode **ic = CSENewN(Icode *, n); BlockHead **bv = CSENewN(BlockHead *, n); LiftedTernaryList *p, *lastternary; BlockHead *prev = b, *nextb = blkdown_(b); Icode *icstart = blkcode_(b); LabelNumber *next = blknext_(b), *next1 = blknext1_(b); int32 bflags = blkflags_(b); blkflags_(b) &= ~(BLK2EXIT | BLKSWITCH | Q_MASK); for (i = 0, p = icr.ternaries; p != NULL; p = cdr_(p), i += 3) { ic[i] = lt_ic1_(p); ic[i+1] = lt_ic2_(p); ic[i+2] = lt_ic3_(p); } qsort(ic, n, sizeof(Icode const *), CompPtr); for (i = 0; i < n; i++) { BlockHead *p = insertblockbetween(prev, nextb, NO); blkcse_(p) = CSEBlockHead_New(); blk_dominators_(p) = cseset_copy(blk_dominators_(nextb)); blklength_(prev) = ic[i] - icstart; blkcode_(p) = ic[i]; bv[i] = p; prev = p; icstart = ic[i]; } blklength_(prev) = newic - icstart; for (p = icr.ternaries; p != NULL; p = cdr_(p)) { int32 i1 = LookUpIC(lt_ic1_(p), ic, n), i2 = LookUpIC(lt_ic2_(p), ic, n), i3 = LookUpIC(lt_ic3_(p), ic, n); BlockHead *next = lt_b1_(p) = bv[i1], *next1 = lt_b2_(p) = bv[i2], *after = lt_b3_(p) = bv[i3]; if (i1 == 0) prev = b; else prev = bv[i1-1]; if (i3 == n-1) lastternary = p; blkflags_(prev) |= BLK2EXIT; blkflags_(prev) |= lt_mask_(p); blknext_(prev) = blklab_(next1); blknext1_(prev) = blklab_(next); blknext_(next) = blklab_(after); blknext_(next1) = blklab_(after); blk_pred_(next) = mk_CSEBlockList(NULL, prev); blk_pred_(next1) = mk_CSEBlockList(NULL, prev); blk_pred_(after) = mk_CSEBlockList(mk_CSEBlockList(NULL, next), next1); } #ifdef TARGET_ALLOWS_COMPARE_CSES prev = bv[n-1]; /* If the expression setting the condition for the */ /* last lifted ternary is also the expression */ /* setting the condition for the block it's being */ /* lifted to, kill the latter */ if (bflags & BLK2EXIT) { if (blk_cmp_(b) != NULL && ExSet_Member(e1_(lt_ex_(lastternary)), blk_cmp_(b)) && !CantMarkCCLive(blklab_(lt_b1_(lastternary)), prev) && !CantMarkCCLive(blklab_(lt_b2_(lastternary)), prev)) { blkcode_(prev)[blklength_(prev)-1].op = J_NOOP; } else blk_cmp_(prev) = blk_cmp_(b); blk_cmp_(b) = NULL; } #endif if (bflags & BLKSWITCH) { LabelNumber **table = (LabelNumber **)next; int32 i, n = (int32)next1; blkflags_(prev) |= BLKSWITCH; blktable_(prev) = table; blktabsize_(prev) = n; for (i = 0; i < n; i++) ReplaceInBlockList(blk_pred_(lab_block_(table[i])), b, prev); } else { if (bflags & BLK2EXIT) { blkflags_(prev) |= bflags & (BLK2EXIT | Q_MASK); blknext1_(prev) = next1; ReplaceInBlockList(blk_pred_(lab_block_(next1)), b, prev); } blknext_(prev) = next; ReplaceInBlockList(blk_pred_(lab_block_(next)), b, prev); } } } } } { int32 i = blklength_(top_block); Icode *newic = newicodeblock(i+1); Icode *old = blkcode_(top_block); blkcode_(top_block) = newic; if (i != 0) memcpy(newic, old, (int) i*sizeof(Icode)); freeicodeblock(old, i); INIT_IC(newic[i], J_SETSPENV); newic[i].r2.bl = NULL; newic[i].r3.bl = bl; blklength_(top_block) = i+1; } greatest_stackdepth += sizeofbinders(bl, YES); return csespillbinders; } static clock_t csetime; static void cse_setup(void) { csespillbinders = NULL; setsplist = NULL; vregset_init(); cselist = NULL; localcsedefs = NULL; } static BindList *cse_eliminate_i(void) { BlockHead *p; BindList *bl = NULL; clock_t t0 = clock(); clock_t ts = t0; int32 refs = cse_refs, count = cse_count; nsets = 0; newsets = 0; setbytes = 0; end_emit(); cse_setup(); for (p = top_block; p != NULL; p = blkdown_(p)) blkcse_(p) = CSEBlockHead_New(); FindDominators(); if (cse_enabled && (!usrdbg(DBG_LINE) || usrdbg(DBG_OPT_CSE))) { phasename = "CSE_Available"; cse_scanblocks(top_block); /* which can alter arcs in the flowgraf, so now we recompute the dominator sets */ phasename = "CSELoops"; { VRegSetP allblocks = NULL; for (p = top_block; p != NULL; p = blkdown_(p)) cseset_insert(blklabname_(p), allblocks, NULL); for (p = blkdown_(top_block); p != NULL; p = blkdown_(p)) { cseset_union(blk_dominators_(p), allblocks); blk_reached_(p) = NO; } cseset_discard(allblocks); PruneDominatorSets(); for (p = top_block; p != NULL; p = blkdown_(p)) if (!blk_reached_(p)) { cseset_discard(blk_dominators_(p)); blk_dominators_(p) = NULL; } FindLoops(); { LoopList *lp; for (lp = all_loops; lp != NULL; lp = cdr_(lp)) { BlockList *bp = ll_mem_(lp); for (; bp != NULL; bp = cdr_(bp)) blknest_(bp->blklstcar)++; } } if (debugging(DEBUG_CSE | DEBUG_STORE)) { cc_msg("dominators found - %d csecs\n", clock()-t0); } if (debugging(DEBUG_CSE) && CSEDebugLevel(2)) { for (p=top_block; p!=NULL; p = blkdown_(p)) { cc_msg("Block %ld dominated by ", blklabname_(p)); cse_printset(blk_dominators_(p)); cc_msg("\n"); } cc_msg("loop members "); cse_printset(loopmembers); cc_msg("\n"); } } phasename = "CSEdataflow"; t0 = clock(); { bool changed; do { if (debugging(DEBUG_CSE | DEBUG_STORE)) cc_msg("CSE dataflow iteration\n"); changed = NO; for (p=bottom_block; p!=NULL; p = blkup_(p)) { VRegSetP oldwantedlater = blk_wantedlater_(p); VRegSetP oldwantedonallpaths = blk_wantedonallpaths_(p); ExprnsReaching(p); if (!cseset_equal(oldwantedlater, blk_wantedlater_(p)) || !cseset_equal(oldwantedonallpaths, blk_wantedonallpaths_(p))) changed = YES; cseset_discard(oldwantedlater); cseset_discard(oldwantedonallpaths); } } while (changed); } if (debugging(DEBUG_CSE | DEBUG_STORE)) { clock_t now = clock(); cc_msg("CSE dataflow complete - %d csecs\n", now-t0); t0 = now; } phasename = "CSEfind"; /* Now things have converged, and for each block we have * available as before * wantedlater the set of expressions evaluated by some subsequent block * and not killed on any path from here to the evaluating * block. * wantedonallpaths the set of expressions evaluated by some block on each * path from the block, and not killed between here and there. * An expression is a candidate for elimination if it is in both available * and wantedlater. * For loop headers, wantedonallpaths is the set of loop-constant * expressions which can be pulled out of the loop with complete safety. */ for (p = bottom_block; p != NULL; p = blkup_(p)) { /* This loop goes from the bottom upwards so that, in the list of * definitions for a given CSE, ones in earlier blocks come first, * so we have a good chance of rejecting definitions which are * subsumed without doing any work. */ VRegSetP cses = cseset_copy(blk_wantedlater_(p)); cseset_intersection(cses, blk_available_(p)); cseset_map(cses, AddCSE, (VoidStar) p); cseset_discard(cses); if (debugging(DEBUG_CSE) && CSEDebugLevel(3)) { cc_msg("L%li:", (long)blklabname_(p)); if (blkflags_(p) & BLKLOOP) cc_msg("*"); cc_msg(" w"); cse_printset(blk_wanted_(p)); cc_msg(" wl"); cse_printset(blk_wantedlater_(p)); cc_msg(" we"); cse_printset(blk_wantedonallpaths_(p)); cc_msg(" k"); if (blk_killedinverted_(p)) cc_msg("~"); cse_printset(blk_killed_(p)); cc_msg(" a"); cse_printset(blk_available_(p)); cc_msg("\n"); } } if (debugging(DEBUG_CSE | DEBUG_STORE)) cc_msg("candidate cses found - "); FindLoopInvariants(); if (debugging(DEBUG_CSE | DEBUG_STORE)) { clock_t now = clock(); cc_msg("candidate loop invariants found - %d csecs\n", now-t0); t0 = now; } LinkRefsToDefs(); if (debugging(DEBUG_CSE | DEBUG_STORE)) { clock_t now = clock(); cc_msg("cse references linked - %d csecs\n", now-t0); t0 = now; } phasename = "CSEeliminate"; bl = ModifyCode(); if (debugging(DEBUG_CSE | DEBUG_STORE)) { clock_t now = clock(); cc_msg("%ld CSEs, %ld references - %d csecs, CSE total %d\n", (long)(cse_count-count), (long)(cse_refs-refs), now-t0, now-ts); csetime += (now - ts); } if (nsets > maxsets) maxsets = nsets; if (setbytes > maxbytes) maxbytes = setbytes; } for (p = top_block; p != NULL; p = blkdown_(p)) { /* from syntax to binder store to survive imminent drop_local_store() */ BlockList *b = NULL, *oldb = blk_pred_(p); for (; oldb != NULL; oldb = cdr_(oldb)) b = mkBlockList(b, oldb->blklstcar); blk_pred_(p) = b; cseallocrec.alloctype = AT_Bind; blk_dominators_(p) = cseset_copy(blk_dominators_(p)); } return bl; } extern BindList *cse_eliminate(void) { BindList *bl = cse_eliminate_i(); if (debugging(DEBUG_CG) || (debugging(DEBUG_CSE) && CSEDebugLevel(1))) flowgraf_print("CSE transforms to:", NO); return bl; } extern void cse_reinit(void) { all_loops = NULL; cseallocrec.alloctype = CSEAllocType; } extern void cse_init(void) { csetime = 0; maxsets = 0; maxbytes = 0; cse_count = 0; cse_refs = 0; /* * The next few are done this way so that the object file for the compiler * will not contain any initialised statics initialised to relocatable * values. Doing so may (on some systems) make it easier to build a * relocatable version of the compiler (e.g. as an Archimedes/RISC-OS * relocatable module). */ cseallocrec.alloctype = CSEAllocType; cseallocrec.statsloc = &nsets; cseallocrec.statsloc1 = &newsets; cseallocrec.statsbytes = &setbytes; } extern void cse_tidy(void) { if (!debugging(DEBUG_STORE | DEBUG_CSE)) return; cc_msg("CSE max sets: %ld (%ld bytes): time %d cs\n", (long)maxsets, (long)maxbytes, csetime); cc_msg("%ld cses, %ld references\n", (long)cse_count, (long)cse_refs); } /* end of mip/cse.c */
stardot/ncc
util/timelim.c
<filename>util/timelim.c /* * Copyright (C) Advanced Risc Machines Ltd., 1991 * SPDX-Licence-Identifier: Apache-2.0 */ #include <stdio.h> #include <time.h> int main() { time_t now = time(0); struct tm tms = *localtime(&now); fprintf(stderr, "Today is %s", ctime(&now)); /* >>>>>>>> EXPIRE at 23:59 on 01 Apr 1994 <<<<<<<< */ tms.tm_sec = 1; tms.tm_min = 0; tms.tm_hour = 0; tms.tm_mday = 1; tms.tm_mon = 9; tms.tm_year = 94; now = mktime(&tms); printf("#define TIME_LIMIT %d\n", now); fprintf(stderr, "The software expires at %s", ctime(&now)); return 0; }
stardot/ncc
cfe/vargen.c
<reponame>stardot/ncc<filename>cfe/vargen.c /* * vargen.c: static initialised variable generator for C compiler * Copyright (C) Codemist Ltd, 1988-1992. * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Advanced RISC Machines Limited, 1991-1992. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 46 * Checkin $Date$ * Revising $Author$ */ /* AM memo: for C++ soon suppress static const's until first &taken. */ /* AM memo: I do not see how genpointer gets called with a string arg */ /* for WR_STR_LITS since it s_string is filtered off by initsubstatic(). */ /* Bug in WR_STR_LITS in ANSI mode? */ /* I think the two calls to genpointer need merging -- read ANSI carefully.*/ /* AM memo: see obj_symref @@@ below for more general use? */ /* Warning: the vg_copyobj/zeroobj probably depend on structs/arrays being */ /* aligned as the compiler currently does to 4 word boundaries. */ /* AM memo: void values/vars need faulting earlier -- see initsubstatic() */ /* WGD 28-9-87 ACW support added, 27-3-88 updated */ /* 30-Nov-86: vargen now assembles bytes/halfword data initialisations */ /* into bytes and adds LIT_XXX flags for xxxasm.c, xxxobj.c */ /* Discussion: Observe that generating code in full generality for arbitrary open arrays requires two passes - consider (e.g.) "char [][] = { "a", "bc",... }". Moreover ANSI forbid such possibly useful initialisations. So do we, but for reasons of producing (type and size) error messages as soon as possible rather than after a reading phase. Accordingly we adopt a coroutine-like linkage to syn.c. */ #ifndef _VARGEN_H #include "globals.h" #include "vargen.h" #include "lex.h" /* for curlex */ #include "syn.h" #include "sem.h" #include "simplify.h" #include "bind.h" #include "builtin.h" #include "aetree.h" #include "codebuf.h" #ifndef NON_CODEMIST_MIDDLE_END #include "regalloc.h" /* to handle global register variables */ #endif #include "mcdep.h" /* for dbg_xxx */ #include "store.h" #include "aeops.h" #include "util.h" /* for padsize */ #include "xrefs.h" #include "inline.h" #include "errors.h" #include "dump.h" /* and for C-only compiler... */ #define vg_note_topdtor(b, topflag) (void)0 #define vg_get_dyninit(topflag) 0 #define dynamic_init(init, fl) (void)0 #define Vargen_cpp_LoadState(f) (void)0 #define Vargen_cpp_DumpState(f) (void)0 #endif /*_VARGEN_H */ static FileLine init_fl; /* @@@ not always set just before use! */ static TypeExpr *inittype; static bool complain_non_aggregate; static int32 initbsize, initboffset, initwoffset; static Binder *cur_initlhs; #define orig_(p) arg1_(p) #define compl_(p) arg2_(p) /* It is now clear that vg_acton_globreg() should be part of syn.c */ /* and/or bind.c (see bind_err_conflicting_globalreg below). */ static void vg_acton_globreg(DeclRhsList *d, Binder *b) { VRegnum reg = GAP; TypeExpr *t = princtype(bindtype_(b)); int32 rno = declstgval_(d) >> 1; #ifndef TARGET_SHARES_INTEGER_AND_FP_REGISTERS if (declstgval_(d) & 1) { if (rno <= 0 || rno > MAXGLOBFLTREG) cc_err(vargen_err_overlarge_reg); else { if ( h0_(t) == s_typespec && ( typespecmap_(t) & bitoftype_(s_double) ) ) reg = R_FV1+rno-1; else cc_err(vargen_err_not_float); } } else #endif { { if (0 < rno && rno <= MAXGLOBINTREG) reg = R_V1+rno-1; #ifdef TARGET_IS_AIH324 /* Prefered form, also prepares for use of a0...d31 etc. */ else if (160 <= rno && rno < 160+32) reg = R_V1 + rno - 160; #endif else cc_err(vargen_err_overlarge_reg); if (reg != GAP) switch (h0_(t)) { case t_content: break; case s_typespec: #ifdef TARGET_SHARES_INTEGER_AND_FP_REGISTERS if (typespecmap_(t) & bitoftype_(s_double)) break; #endif if (typespecmap_(t) & ( bitoftype_(s_char) | bitoftype_(s_int) | bitoftype_(s_enum) )) break; /* no one_word structs, unions - cg isn't up to the notion that they might be in registers (?) */ /* @@@AM: it ought to be! */ default: cc_err(vargen_err_not_int); reg = GAP; } } } if (reg != GAP) { /* We have arranged that this binder has room to record a * register (though normally only auto binders have). */ if (bindxx_(b) != GAP && bindxx_(b) != reg) cc_rerr(bind_err_conflicting_globalreg, b); bindxx_(b) = reg; globalregistervariable(reg); asm_setregname(reg, symname_(bindsym_(b))); } } static Expr *reduce(Expr *e, Binder *whole) { /* a reduced optimise0: expose s_floatcon/s_integer */ if (whole && (h0_(e) == s_assign || h0_(e) == s_init) && arg1_(e) == (Expr *)whole) e = arg2_(e); if (h0_(e) == s_invisible && h0_(compl_(e)) == s_floatcon) return compl_(e); return e; } static Expr *rdinit(TypeExpr *t, Binder *whole, int32 flag) { Expr *e; if (LanguageIsCPlusPlus) { /* We can't do optimise0() since it removes the cast to break toplevel */ /* int x = (int)"abc"; Make C code share this soon. */ /* Maybe the right thing to do is optimise0(x = e) for some var 'x'. */ e = syn_rdinit(t, whole, flag); if (e) e = reduce(e, whole); } else { /* The code for C and C++ has diverged -- share the above code soon. */ e = syn_rdinit(t, whole, flag|8); if (e) e = optimise0(e); } if (e && h0_(e) == s_error) e = 0; return e; } /* @@@ check this routine takes care with padding for wide strings. */ static int32 genstring(String *s, int32 size) { /* the efficiency of this is abysmal. */ StringSegList *p = s->strseg; AEop sort = h0_(s); int32 length = stringlength(p)/(sort == s_wstring ? 4 : 1); if (size == 0xffffff) size = length + 1; else if (length > size) cc_rerr(vargen_err_long_string, sort==s_wstring ? "wchar_t":"char", (long)size); else if (length == size) cc_warn(vargen_warn_nonull, sort==s_wstring ? "wchar_t":"char", (long)size); vg_genstring(p, size*(sort == s_wstring ? 4:1), 0); return size; } static int32 int_of_init0(Expr *init, bool *ok) { int32 ival = 0; if (init != 0 && *ok) { int32 op = h0_(init); if (op == s_integer) ival = intval_(init); else { #ifndef PROPER_CODE_TO_SUPPORT_OFFSETOF_IN_STATIC_INITIALISERS /* AM: It isn't just a case of being sensibly centralised, an attempt */ /* was made to encourage sem.c only to reduce 'honest' constant exprs, */ /* like 3.4*2, but not to do algebraic re-arrangement (which simplify.c */ /* or cg.c are responsible for). This is partly to enable that correct */ /* diagnostics are produced (e.g. we do not want (x+0)=3 to become x=3). */ /* The offsetof rules changed and so I believe that sem.c should NOW */ /* do a little more about these things. Note the requirement to */ /* diagnose "static int x = 1 || f();" comes in here! */ /* @@@ LDS 27-Mar-90. The following makes offsetof() work in */ /* static initializer contexts. Oh woe, expression reduction */ /* isn't sensibly centralised. This must be regarded as an */ /* interim bodge of the worst sort, but I don't have time to */ /* rstructure the tree-reduction part of the compiler. */ if (op == s_cast || op == s_plus || op == s_minus) { Expr *a1, *a2; if (op == s_cast) a1 = init, a2 = arg1_(init); else a1 = arg1_(init), a2 = arg2_(init); if ((mcrepofexpr(a1) & ~0x01000000) == sizeof_int && (mcrepofexpr(a2) & ~0x01000000) == sizeof_int) { ival = int_of_init0(a2, ok); if (op == s_plus) ival = int_of_init0(a1, ok) + ival; if (op == s_minus) ival = int_of_init0(a1, ok) - ival; return ival; } } #endif *ok = 0; } } return ival; } static int32 int_of_init(Expr *init) { bool ok = YES; int32 ival = int_of_init0(init, &ok); if (!ok) { if (LanguageIsCPlusPlus) dynamic_init(init, 0); else moan_nonconst(init, moan_static_int_type_nonconst, moan_static_int_type_nonconst1, moan_static_int_type_nonconst2); } return ival; } static Int64Con *int64_of_init(Expr *init) { static Int64Con zero = { s_int64con, bitoftype_(s_short)|bitoftype_(s_long)|bitoftype_(s_int), { 0, 0} }; Int64Con *fval = &zero; if (init != 0) { if (h0_(init) == s_int64con) fval = (Int64Con *)init; else if (LanguageIsCPlusPlus) dynamic_init(init, 0); else moan_nonconst(init, moan_static_int_type_nonconst, moan_static_int_type_nonconst1, moan_static_int_type_nonconst2); } return fval; } static FloatCon *float_of_init(Expr *init) { FloatCon *fval = fc_zero.d; if (init != 0) { if (h0_(init) == s_floatcon) fval = (FloatCon *)init; else if (LanguageIsCPlusPlus) dynamic_init(init, 0); else moan_nonconst(init, moan_floating_type_nonconst, moan_floating_type_nonconst1, moan_floating_type_nonconst2); } return fval; } static String *string_of_init(Expr *init, bool wide) { if (init != 0 && h0_(init) == s_invisible) init = orig_(init); /* can only happen in CPLUSPLUS */ if (init != 0 && isstring_(h0_(init))) { if (wide == (h0_(init) == s_wstring)) return (String *)init; } return 0; } static int32 rd_bitinit(TypeExpr *t, int32 size) { t = unbitfield_type(t); /* Apr 92: for type-safe enums, now use 't' instead of prev. te_int */ /* The current version of unbitbields returns te_int/enum type. */ { int32 i = int_of_init(rdinit(t, 0, 0)); if (size < 32) i &= ((unsigned32)1 << size)-1; return i; } /* One day it might be nice to compare the value read with size... */ } /************************************************************************** oo oo Problem: This code is tailored to putting string o\\ ____ //o literals in the read only code area, thus it handles \\/ \// initialised char *s without additional buffering and | O O | can generate the address constants on the fly. In : oo : order to put the literals in the data area, we have \__/ to postpone generating them until after we've made //\\ the adcons pointing to them. Clever use of existing o// \\o data structures makes this almost painless... but oo oo BEWARE if you aspire to grok the code... **************************************************************************/ struct StrLit { struct StrLit *next; DataInit *d; String *s; }; static struct StrLit *str_lits; static void genpointer(Expr *einit) { int32 offset = 0; AEop op; Expr *x; if (LanguageIsCPlusPlus) { x = optimise0(einit); /* @@@ dubious -- see rdinit(). */ if (x == 0 || h0_(x) == s_integer) syserr("genpointer new code"); } else x = einit; for (;;) switch (op = h0_(x)) { case s_addrof: { Expr *y = arg1_(x); Binder *b; if (h0_(y) != s_binder) syserr(syserr_genpointer, (long)h0_(y)); b = (Binder *)y; if (bindstg_(b) & b_fnconst) Inline_RealUse(b); if ((bindstg_(b) & (bitofstg_(s_static) | u_loctype)) == bitofstg_(s_static)) { /* now statics may be local (and hence use datasegment * offsets -- see initstaticvar()) or functions (possibly * not yet defined -- "static f(), (*g)() = f;". */ if (bindstg_(b) & b_fnconst) gendcF(bindsym_(b), offset, 0); else { gendcA(bindsym_(datasegment), bindaddr_(b)+offset, 0); } } #ifdef TARGET_HAS_BSS else if ((bindstg_(b) & bitofstg_(s_static)) && bindaddr_(b) != BINDADDR_UNSET) #ifdef CONST_DATA_IN_CODE gendcA( (bindstg_(b) & u_constdata) ? bindsym_(constdatasegment) : bindsym_(bsssegment), bindaddr_(b)+offset, 0); #else gendcA(bindsym_(bsssegment), bindaddr_(b)+offset, 0); #endif #endif else if (bindstg_(b) & (bitofstg_(s_extern) | u_loctype)) { int xr = (bindstg_(b) & bitofstg_(s_weak)) ? xr_weak : 0; if (bindstg_(b) & b_fnconst) gendcF(bindsym_(b), offset, xr); else gendcA(bindsym_(b), offset, xr); } else { cc_err(vargen_err_nonstatic_addr, b); if (sizeof_ptr == 8 && target_lsbytefirst) gendcI(sizeof_ptr-4, TARGET_NULL_BITPATTERN); else gendcI(sizeof_ptr, TARGET_NULL_BITPATTERN); } /* * The next line is because (at present?) gendcA does not put out the * high-order part of an 8-byte address... to allow me to fudge string * addresses.... */ if (sizeof_ptr == 8 && target_lsbytefirst) gendcI(4, 0); /* ! */ return; } case_s_any_string if ((feature & FEATURE_WR_STR_LITS) || (config & CONFIG_REENTRANT_CODE)) { /* * Standard pcc mode: first dump a reference to the * literal then record that the literal must be generated * and the reference updated when the recursion terminates. * I.e. the offset value stashed away in the next value * will be sought out again and updated. */ gendcA(bindsym_(datasegment), offset, 0); /* dataseg relative */ str_lits = (struct StrLit *) syn_list3(str_lits, get_datadesc_ht(NO), x); /* * Here is the reason that (as a temporary hack?) I make gendcA only generate * 4 bytes if sizeof_ptr == 8 and target_lsbytefirst. It is because the fudge * here needs to have a handle on the LOW word of the address to relocate it * to talk about the offset of the string being mentioned. */ if (sizeof_ptr == 8 && target_lsbytefirst) gendcI(4, 0); } else { /* * Standard ANSI mode: put the strings in code space, * nonmodifiable. Rely on the fact that CG thinks it is * between routines (even for local static inits). * codeloc() is a routine temporarily for forward ref */ gendcF(bindsym_(codesegment),codeloc()+offset, 0); if (sizeof_ptr == 8 && target_lsbytefirst) gendcI(4, 0); codeseg_stringsegs(((String *)x)->strseg, NO); } return; case s_integer: /* * A New case to deal with things like '(&(struct tag*)0)->field' * Such expressions turn into '(int) + (int)' in the AE tree. * So here I calculate the value and assign it to the pointer. */ /* @@@AM: new pointer reduction code in sem.c (for offsetof) */ /* *probably* means can never happen. Review. */ gendcI(sizeof_ptr, evaluate(x) + offset); return; case s_monplus: case s_cast: x = arg1_(x); break; case s_plus: if (h0_(arg1_(x)) == s_integer) { offset += evaluate(arg1_(x)); x = arg2_(x); break; } /* drop through */ case s_minus: if (h0_(arg2_(x)) == s_integer) { offset += (op == s_plus ? evaluate(arg2_(x)) : -evaluate(arg2_(x))); x = arg1_(x); break; } /* drop through */ default: /* I wonder if the type system allows the next error to occur! */ /* ',' operator probably does */ if (LanguageIsCPlusPlus) /* we must use 'einit': (1) to avoid optimise0() */ /* and (2) to keep 'offset'. */ dynamic_init(einit, 0); else cc_err(vargen_err_bad_ptr, op); gendcI(sizeof_ptr, TARGET_NULL_BITPATTERN); return; } } static void initbitfield(unsigned32 bfval, int32 bfsize, bool pad_to_int) { int32 j; /* Bitfield initialisers may start on any container boundary, so */ /* (except in strict ANSI mode) they aren't necessarily int-aligned */ /* nor int-sized */ bfsize = (bfsize + 7) & ~7; if (debugging(DEBUG_DATA)) cc_msg("initbitfield(%.8lx, %lu, %i)\n", bfval, bfsize, pad_to_int); for (j = 0; j < bfsize; j += 8) if (target_lsbytefirst) gendcI(1, bfval & 255), bfval >>= 8; else gendcI(1, bfval >> 24), bfval <<= 8; if (pad_to_int) padstatic(alignof_int); } /* NB. this MUST be kept in step with sizeoftype and findfield (q.v.) */ static void initsubstatic(TypeExpr *t, Binder *whole, bool aligned, Expr *einit) { SET_BITMAP m; inittype = t; /* for possible dynamic initialization */ switch (h0_(t)) { case s_typespec: m = typespecmap_(t); switch (m & -m) /* LSB - unsigned/long etc. are higher */ { case bitoftype_(s_void): /* * This Guy is trying to initalise a 'void' !!! * @@@ Can this happen any more? */ cc_err(vargen_err_init_void); (void)int_of_init(rdinit(te_int,whole,0)); break; case bitoftype_(s_char): case bitoftype_(s_enum): /* maybe do something more later */ case bitoftype_(s_bool): case bitoftype_(s_int): if (m & BITFIELD) syserr(syserr_initsubstatic); /* these are all supposedly done as part of the * enclosing struct or union. */ if (int_islonglong_(m)) { if (einit == 0 && syn_canrdinit()) einit = rdinit(t,whole,0); { Int64Con *ic = int64_of_init(einit); gendcI_a(sizeof_long, ((int32 *)&ic->bin.i)[0], aligned); gendcI_a(sizeof_long, ((int32 *)&ic->bin.i)[1], aligned); } break; } #ifndef REVIEW_AND_REMOVE /* in by default */ /* This code to be reviewed now that the front end reduces some such expressions to integers. AM and ??? to discuss. Do we need support for: int x = (int)"abc";? Check the exact wording of last ANSI draft. If nothing else review the cc_err() message in genpointer. */ /* * Okay, I confess, I have used the pointer initialisation * code here to initialise 'int' values in PCC mode, * But I can explain !!!. Well, it goes like this, some * PCC code contains expressions like : * 'int x = (int) (&(struct tag*)0)->field;' * Well, this is really a pointer initialisation so why * not use the code. (See simple, isn't it). **** AM cringes at this. Tidy soon. *@@@ LDS too - BUT DON'T BREAK IT; * Unix won't compile if you do. * AM dec90: this code probably is redundant since * changes elsewhere means it works in ansi mode. * but it does allow: int x = (int)"abc"; */ if ((feature & FEATURE_PCC) && (sizeoftype(t) == 4)) { Expr *init = rdinit(t,whole,0); if (init == 0) gendcI_a(4, 0, aligned); else if (h0_(init) == s_integer) gendcI_a(4, intval_(init), aligned); else genpointer(init); } else #endif /* REVIEW_AND_REMOVE */ { if (einit == 0 && syn_canrdinit()) einit = rdinit(t,whole,0); gendcI_a(sizeoftype(t), int_of_init(einit), aligned); } break; case bitoftype_(s_double): if (einit == 0 && syn_canrdinit()) einit = rdinit(t,whole,0); gendcE(sizeoftype(t), float_of_init(einit)); break; case bitoftype_(s_struct): case bitoftype_(s_class): case bitoftype_(s_union): /* ANSI 3rd public review draft says that */ /* union { int a[2][2] a, ... } x = {{1,2}} initialises like */ /* int a[2][2] = {1,2} ( = {{1,0},{2,0}}). */ { int32 note = syn_begin_agg(); /* skips and notes if '{' */ TagBinder *b = typespectagbind_(t); ClassMember *l; int32 bfsize, bfval, k, woffset; bool is_union = ((m & -m) == bitoftype_(s_union)); (void)sizeofclass(b, NULL); if (!(tagbindbits_(b) & TB_DEFD)) cc_err(vargen_err_undefined_struct, b); bfsize = bfval = woffset = 0; for (l = tagbindmems_(b); l != 0; l = memcdr_(l)) if (is_datamember_(l)) { inittype = memtype_(l); initbsize = membits_(l); initboffset = memboff_(l); initwoffset = memwoff_(l); if (isbitfield_type(memtype_(l))) { if (is_union && memsv_(l) == NULL) continue; k = membits_(l); if (bfsize == 0) { while (woffset < memwoff_(l)) { gendcI(1, 0); ++woffset; } } if (woffset < memwoff_(l)) { initbitfield(bfval, bfsize, 0); bfsize = bfval = 0; woffset = memwoff_(l); } /* accumulate bitfield in bfval */ { int32 leftshift = memboff_(l); if (woffset != memwoff_(l)) leftshift -= (woffset-memwoff_(l))*8; if ((leftshift + k) > bfsize) bfsize = leftshift + k; if (!target_lsbitfirst) leftshift = MAXBITSIZE - k - leftshift; /* ANSI 3rd draft says unnamed bitfields */ /* never consume initialisers. */ /* (even for unions) */ if (memsv_(l) != NULL) bfval |= rd_bitinit(memtype_(l), k) << leftshift; } } else { if (bfsize != 0) { int32 align = memwoff_(l) & -memwoff_(l); initbitfield(bfval, bfsize, 0); padstatic(align > alignof_int ? alignof_int : align); bfsize = bfval = 0; } if (!(tagbindbits_(b) & TB_UNALIGNED)) { padstatic(alignof_member); padstatic(alignoftype(memtype_(l))); } if (attributes_(l) & CB_MASK && complain_non_aggregate) { cc_warn(vargen_warn_init_non_aggregate); complain_non_aggregate = 0; } if (!(attributes_(l) & CB_BASE) || tagbindmems_(typespectagbind_(princtype(memtype_(l)))) != NULL) initsubstatic(memtype_(l), 0, !(tagbindbits_(b) & TB_UNALIGNED), 0); woffset = memwoff_(l) + sizeoftype(memtype_(l)); } /* only the 1st field of a union can be initialised */ if (is_union) break; } if (bfsize) initbitfield(bfval, bfsize, is_union); if (is_union) gendc0(sizeoftype(t) - (l==0 ? 0 : /* empty union!! */ bfsize ? sizeof_int : sizeoftype(memtype_(l)))); /* See sem.c(sizeoftype) -- check this agrees */ else if (bfsize == 0 && woffset == 0) gendc0(1); /* empty C++ struct. */ syn_end_agg(note); padstatic(alignoftype(t)); /* often, alignof_struct */ break; } case bitoftype_(s_typedefname): initsubstatic(bindtype_(typespecbind_(t)), whole, aligned, einit); break; default: syserr(syserr_initstatic, (long)h0_(t), (long)m); break; } break; case t_unknown: /* stash it away */ { Expr *e = (einit == 0 && syn_canrdinit()) ? rdinit(t, whole, 0) : einit; if (whole) bindconst_(whole) = e; break; } case t_fnap: /* spotted earlier */ default: syserr(syserr_initstatic1, (long)h0_(t)); case t_subscript: { int32 note = syn_begin_agg(); /* skips and notes if '{' */ int32 i, m = (typesubsize_(t) && h0_(typesubsize_(t)) != s_binder) ? evaluate(typesubsize_(t)):0xffffff; TypeExpr *t2; if (m == 0) { syn_end_agg(note); /* Be careful with struct { char x; int y[0]; char y; } even if ANSI illegal */ break; } /* N.B. the code here updates the size of an initialised [] array */ /* with the size of its initialiser. initstaticvar() */ /* ensures (by copying types if necessary) that this does not clobber */ /* a typedef in things like: typedef int a[]; a b = {1,2}; */ if (!syn_canrdinit()) { if (typesubsize_(t) == 0 || h0_(typesubsize_(t)) == s_binder) cc_err(vargen_err_open_array); } else if (t2 = princtype(typearg_(t)), isprimtype_(t2,s_char)) { String *s = string_of_init(rdinit(0,0,1), 0); if (s) { int32 k = genstring(s, m); if (s != string_of_init(rdinit(0,0,0), 0)) syserr("vargen(string-peep)"); if (typesubsize_(t) == 0 || h0_(typesubsize_(t)) == s_binder ) typesubsize_(t) = globalize_int(k); syn_end_agg(note); break; } /* ANSI say m > 0 so rdinit(peek) is re-read. */ } /* t2 is maybe const/volatile 'signed T' or 'T', where T is the type of */ /* wchar_t. This needs to be improved if wchar_t can be some sort of */ /* char. */ else if (h0_(t2) == s_typespec && (typespecmap_(t2) & (bitoftype_(s_int)|bitoftype_(s_long)| bitoftype_(s_short)|bitoftype_(s_unsigned))) == typespecmap_(te_wchar)) { String *s = string_of_init(rdinit(0,0,1), 1); if (s) { int32 k = genstring(s, m); if (s != string_of_init(rdinit(0,0,0), 1)) syserr("vargen(string-peep)"); if (typesubsize_(t) == 0 || h0_(typesubsize_(t)) == s_binder) typesubsize_(t) = globalize_int(k); syn_end_agg(note); break; } /* ANSI say m > 0 so rdinit(peek) is re-read. */ } /* Maybe generalise this one day: */ #define vg_init_to_null(t) (TARGET_NULL_BITPATTERN == 0) for (i = 0; i < m; i++) { if (!syn_canrdinit()) { if (typesubsize_(t) == 0 || h0_(typesubsize_(t)) == s_binder) { typesubsize_(t) = globalize_int(i); break; /* set size to number of elements read. */ } if (vg_init_to_null(typearg_(t))) { gendc0((m-i)*sizeoftype(typearg_(t))); break; /* optimise multi-zero initialisation. */ } } initsubstatic(typearg_(t), 0, aligned, 0); } syn_end_agg(note); break; } case t_content: case t_ref: { Expr *init = rdinit(t,whole,0); if (init == 0) gendcI(sizeof_ptr, TARGET_NULL_BITPATTERN); else if (h0_(init) == s_integer) gendcI(sizeof_ptr, intval_(init)); /* casted int to pointer */ else genpointer(init); break; } } } static void initstaticvar_1( Binder *b, bool topflag, TentativeDefn *tentative, Expr *einit) { TypeExpr *btype = bindtype_(b); bool changingtoconst = LanguageIsCPlusPlus && !is_constdata() && (qualifiersoftype(btype) & bitoftype_(s_const)); DataInit *oldtail; int32 oldsize; DataXref *oldxrefs; if (tentative != NULL) { if (changingtoconst) { DataAreaSort da = SetDataArea(DS_Const); save_vargen_state(tentative); SetDataArea(da); } else save_vargen_state(tentative); } if (debugging(DEBUG_DATA)) cc_msg("%.6lx: %s%s (%s)\n", (long)get_datadesc_size(), topflag ? "" : "; ", symname_(bindsym_(b)), #ifdef CONST_DATA_IN_CODE (is_constdata()) ? "constdata" : #endif "data"); if (b != datasegment) padstatic(alignoftype(btype)); /* ECN: Defer setting of oldtail & oldsize until after we have done padstatic * because padstatic applies to the original datap so if we switch to * datap = &constdata we will need to apply padstatic again and not simply * reuse the old padding as this may be wrong for constdata. */ if (changingtoconst) { labeldata(NULL); oldtail = get_datadesc_ht(NO); oldsize = get_datadesc_size(); oldxrefs = get_datadesc_xrefs(); } bindaddr_(b) = get_datadesc_size(); if (topflag) /* note: names of local statics may clash but cannot be forward refs (except for fns which don't come here) */ { labeldata(bindsym_(b)); (void)obj_symref(bindsym_(b), bindstg_(b) & bitofstg_(s_extern) ? get_datadesc_xrarea()+xr_defext : get_datadesc_xrarea()+xr_defloc, get_datadesc_size()); } if (b == datasegment) return; /* not really tidy */ { /* * A decl such as 'typedef char MSG[];' gets side effected by * 'MSG name = "A name";'. Therefore copy type before initialiser * is read ... Here we go ... */ if (isprimtype_(btype, s_typedefname)) { TypeExpr *t = prunetype(btype); if (h0_(t)==t_subscript && (typesubsize_(t) == 0 || h0_(typesubsize_(t)) == s_binder)) /* the next line is idle, since case is rare... */ /* (We must alloc. glob store since b maybe top level */ /* and hence its type will already be globalised, but */ /* prunetype() may alloc. local store -- globalise all.) */ /* Note that the next line relies on globalize_typeexpr */ /* NOT caching empty arrays, hence we get a fresh copy. */ btype = bindtype_(b) = globalize_typeexpr(t); } { #ifdef TARGET_IS_ACW /* The following (hackish) lines force FEATURE_WR_STR_LITS (which puts */ /* strings in data segment) for the Acorn 32000 machine) which, due to */ /* TARGET_CALL_USES_DESCRIPTOR, are unhappy abount code segment adcons */ /* (as opposed to descriptors) in a data segment. */ int32 f = feature; feature |= FEATURE_WR_STR_LITS; #endif initsubstatic(btype, b, YES, einit); /* Note that the following padstatic(alignof_toplevel) helps alignment */ /* of (e.g.) strings (which often speeds memcpy etc.). However it is */ /* also assumed to happen by the code for initialising auto arrays. */ /* See the call to trydeletezerodata(). */ padstatic(alignof_toplevel_static); #ifdef TARGET_IS_ACW feature = f; #endif } } #ifdef CONST_DATA_IN_CODE if (changingtoconst && vg_currentdecl_inits == NULL) { DataInit *newtail, *newinits; labeldata(NULL); newtail = get_datadesc_ht(NO); if (oldtail != NULL) { newinits = oldtail->datacdr; oldtail->datacdr = NULL; set_datadesc_ht(NO, oldtail); } else { newinits = get_datadesc_ht(YES); set_datadesc_ht(YES, NULL); set_datadesc_ht(NO, NULL); } SetDataArea(DS_Const); padstatic(alignoftype(btype)); labeldata(NULL); bindaddr_(b) = get_datadesc_size(); /* constdata.size */ /* the following lines are a hack but reused store allocated and fewer things to unhook */ if (topflag) { symext_(bindsym_(b))->extflags = 0; (void)obj_symref(bindsym_(b), bindstg_(b) & bitofstg_(s_extern) ? get_datadesc_xrarea()+xr_defext : get_datadesc_xrarea()+xr_defloc, get_datadesc_size()); } if (newinits != NULL) { if (get_datadesc_ht(YES) == NULL) set_datadesc_ht(YES, newinits); else get_datadesc_ht(NO)->datacdr = newinits; set_datadesc_ht(NO, newtail); } /* Assert: (data.xrefs == NULL) -> (data.xrefs == oldxrefs) */ if (data_xrefs() != oldxrefs) { DataXref *xref = data_xrefs(); int32 roffdelta = constdata_size() - oldsize; while (xref != NULL) { xref->dataxroff += roffdelta; if (xref->dataxrcdr == oldxrefs) break; xref = xref->dataxrcdr; } if (xref == NULL) syserr("can't find oldxref"); xref->dataxrcdr = constdata_xrefs(); set_datadesc_xrefs(data_xrefs()); SetDataArea(DS_ReadWrite); set_datadesc_xrefs(oldxrefs); SetDataArea(DS_Const); } if (debugging(DEBUG_DATA)) cc_msg(" moved to const data %.6lx\n", (long)constdata_size()); set_datadesc_size(constdata_size() + data_size() - oldsize); SetDataArea(DS_ReadWrite); set_datadesc_size(oldsize); SetDataArea(DS_Const); bindstg_(b) |= u_constdata; bindstg_(b) |= b_generated; } #endif codeseg_flush(0/*no strlitname*/); } /* Should be static except for initstaticvar(datasegment) in compiler.c */ void initstaticvar(Binder *b, bool topflag) { initstaticvar_1(b, topflag, NULL, 0); } static Expr *quietaddrof(Binder *b) /* This function exists only to keep PCC mode happy. ensurelvalue() in */ /* sem is what's really needed, but it isn't exported and whinges in */ /* pcc mode about &<array>. In the long-term, something like this is */ /* needed for export from simplify (a quiet force-address-of-tree opn */ /* for trusted callers) so until then LDS leves this bodge here. */ { bindstg_(b) |= b_addrof; return mk_expr1(s_addrof, ptrtotype_(bindtype_(b)), (Expr *)b); } /* Auxiliary routine for initialising auto array/struct/unions */ static Expr *vg_copyobj(Binder *sb, Binder *b, int32 size) { /* Note that the same code suffices for array and structs as it is */ /* quite legal to take the address of an array, implicitly or */ /* explicitly. Note that b/sb both have array/struct/union type. */ return mk_expr2(s_fnap, primtype_(bitoftype_(s_void)), sim.memcpyfn, (Expr *)mkExprList( mkExprList( mkExprList(0, mkintconst(te_int, size, 0)), quietaddrof(sb)), quietaddrof(b))); } static Expr *vg_zeroobj(Binder *b, int32 offset, int32 zeros) { Expr *addrb = quietaddrof(b); return mk_expr2(s_fnap, primtype_(bitoftype_(s_void)), sim.memsetfn, (Expr *)mkExprList( mkExprList( mkExprList(0, mkintconst(te_int,zeros,0)), lit_zero), mk_expr2(s_plus, typeofexpr(addrb), addrb, mkintconst(te_int, offset, 0)))); } static DeclRhsList *defergenerating(DeclRhsList *const d, Expr *dyninit) { DeclRhsList *dd = (DeclRhsList *)GlobAlloc(SU_Const, sizeof(DeclRhsList)); *dd = *d; dd->decltype = globalize_typeexpr(d->decltype); declinit_(dd) = globalize_expr(dyninit); return dd; } /* The following routine removes generated statics, which MUST have been instated with instate_declaration(). Dynamic initialistions are turned into assignments for rd_block(), by return'ing. 0 means no init. Ensure type errors are noticed here (for line numbers etc.) */ /* AM: the 'const's below are to police the unchanging nature of 'd' */ /* (and its subfields stg,b). Note that 't' can be changed. */ Expr *genstaticparts(DeclRhsList *const d, bool topflag, bool dummy_call, Expr *dyninit) { const SET_BITMAP stg = d->declstg; /* also note stg below has 2/3 defns bindstg/declstg. */ Binder *const b = d->declbind; TypeExpr *t = prunetype(d->decltype); int hackflag; /* only while transforming code. */ int32 loc = 0; str_lits = NULL; /* no static string inits seen yet. */ init_fl = d->fileline; complain_non_aggregate = !dummy_call; /* Apr 92: this case was recently lifted out -- maybe it shows a */ /* bug(?) whereby s_typedef and b_fnconst can both be set? */ if (stg & bitofstg_(s_typedef)) { if (usrdbg(DBG_PROC) && topflag) dbg_type(bindsym_(b), bindtype_(b), d->fileline); } else if (!(stg & b_fnconst)) switch (stg & PRINCSTGBITS) { case bitofstg_(s_auto): /* includes register vars too */ /* * Deal with arrays, structs and unions here * Treat auto a[5] = 2; consistently with static a[5] = 2; * by always trying to read an initialiser for an array. * @@@ maybe forbid above for C++ */ if ( syn_canrdinit() && ( h0_(t) == t_subscript || ( curlex.sym == s_lbrace && isclasstype_(t)))) { /* For an initialised auto array/struct/union generate */ /* the whole object (ANSI 3rd draft say initialising one */ /* component of an object initialises it all) in static */ /* space and generate a run-time copy. We treat large */ /* terminal zero segments specially. */ /* For consistency this is a source-to-source translation. */ int32 size, zeros; /* NB the use of bindtype_(b) in the next line instead of t avoids */ /* updating a possible open array typedef. */ Binder *sb = mk_binder(gensymval(0), bitofstg_(s_static), bindtype_(b)); DataInit *start; /* It suffices to allocate sb like any other local static. */ #ifdef TARGET_IS_HELIOS /* * A strange option needed with Helios (for building a shared library) can * make this mechanism fall apart (the forged static may not get set up) * so I generate a diagnostic to warn people. Yuk at the break of modularity. */ { extern bool suppress_module; if (suppress_module) cc_err(vg_err_dynamicinit); } #endif #ifdef CONST_DATA_IN_CODE if ( /*!LanguageIsCPlusPlus &&*/ (!(config & CONFIG_REENTRANT_CODE) || pointerfree_type(bindtype_(b)))) { SetDataArea(DS_Const); binduses_(sb) |= u_constdata; cur_initlhs = b; } #endif start = (get_datadesc_ht(YES) == NULL) ? NULL : get_datadesc_ht(NO); /* * Create hidden static for auto initialiser. */ initstaticvar(sb, NO); cur_initlhs = 0; /* Update bindtype_(b) in case it was typedef to open array which */ /* would have been copied (cloned) by initstaticvar(). */ t = bindtype_(b) = bindtype_(sb); size = sizeoftype(t); /* size of auto [] now known. */ /* The following line is helpful for initialising auto char arrays. */ /* We pad the size for initialisation purposes up to a multiple of */ /* alignof_toplevel, safe (in the assumption) that flowgraf.c has padded*/ /* the stack object and that initstaticvar() below has done the same */ /* for the statically allocated template. */ /* The effect is to encourage cg.c to optimised word-oriented copies. */ size = padsize(size, alignof_toplevel_auto); /* If less than 8 words of zeros in array, struct or union then do not */ /* remove trailing zeros. trydeletezerodata() is a multiple of 4. */ zeros = trydeletezerodata(start, 32); if (dyninit) syserr("dyninit"); if (zeros == 0) dyninit = vg_copyobj(sb, b, size); else { /* * Call function to copy trailing zeros to the data * structure. */ dyninit = vg_zeroobj(b, size-zeros, zeros); /* * Copy hidden static to auto array, struct or union * without any trailing zeros. */ if (size>zeros) dyninit = mkbinary(s_comma, vg_copyobj(sb, b, size-zeros), dyninit); } { Expr *e = vg_get_dyninit(topflag); if (e != 0) dyninit = mkbinary(s_comma, dyninit, e); } SetDataArea(DS_ReadWrite); } else { Expr *e = syn_rdinit(d->decltype, b, 0); /* no optimise0 */ if (e) { if (dyninit) syserr("dyninit"); dyninit = e; } } break; #ifndef NON_CODEMIST_MIDDLE_END case b_globalregvar: vg_acton_globreg(d, b); loc = bindxx_(b); break; #endif default: syserr(syserr_rd_decl_init, (long)stg); /* assume static */ case bitofstg_(s_static): case bitofstg_(s_extern): { bool dyninit_is_const = NO; Expr *orig_dyninit = dyninit; if (LanguageIsCPlusPlus) /* @@@ This isn't right for local statics! */ { /* pick up any initialiser expressions passed in... */ if (dyninit) { Expr *rhs; if (issimpletype_(t) && (h0_(rhs = reduce(dyninit, b)) == s_integer || h0_(rhs) == s_floatcon)) { dyninit = rhs; if (stg & bitofstg_(s_static)) dyninit_is_const = YES; else dyninit_is_const = NO; } else dynamic_init(dyninit, 1), dyninit = 0; } } if (!(d->declstg & b_undef)) /* explicit initialisation */ { /* (or small tentative). */ #ifdef CONST_DATA_IN_CODE if ((!LanguageIsCPlusPlus || dyninit) && (qualifiersoftype(d->decltype) & bitoftype_(s_const)) && ( !(config & CONFIG_REENTRANT_CODE) || pointerfree_type(d->decltype)) ) { bindstg_(b) |= u_constdata; } #endif if (LanguageIsCPlusPlus) { /* similar code to auto for "static class A x, y = x;" */ if (isclasstype_(t)) { if (curlex.sym != s_lbrace && syn_canrdinit()) { Expr *e = syn_rdinit(d->decltype, b, 0); /* no optimise0 */ if (e) dynamic_init(e, 1), e = 0; else syserr("genstatic(static-class)"); } } vg_note_topdtor(b, topflag); /* no-op unless t is a class or array-of-class type */ if (var_cc_private_flags & 2L) dyninit_is_const = 0; /* in C++, disable if set */ } if (dyninit_is_const && (bindstg_(b) & u_constdata) && !(bindstg_(b) & b_generated)) { /* an eliminatable const definition... for now... */ bindaddr_(b) = (IPtr)defergenerating(d, orig_dyninit); return 0; } else { #ifdef CONST_DATA_IN_CODE if (bindstg_(b) & u_constdata) { bindstg_(b) |= b_generated; SetDataArea(DS_Const); } #endif initstaticvar_1(b, topflag, d->tentative, dyninit); } /* Put out debug info AFTER initialised array size has */ /* been filled in by initstaticvar(): */ hackflag = 1; } else /* declaration with no explicit initialisation. */ { if (feature & FEATURE_PCC) { TypeExpr *t = princtype(bindtype_(b)); /* * Found a declaration like int foo; with no initialiser. * PCC regards this as common which is encoded as an * undefined external data reference with a non-0 size. * BUT BEWARE: int foo[]; is NOT a common variable - it * is an extern decl. Thus, we have a look for undefined * arrays. (e.g. xxx[1][3][]), possibly via a leading * typedef. If we find one then we exit. * AM: @@@ use is_openarray() soon? I would now, but * am nervous about int a[][]; in pcc mode. */ for (; h0_(t) == t_subscript; t = princtype(typearg_(t))) { if (typesubsize_(t) == 0 || h0_(typesubsize_(t)) == s_binder) { #ifndef TARGET_IS_UNIX /* Add debug info for open arrays (ASD only) */ if (usrdbg(DBG_PROC) && topflag) #ifdef TARGET_HAS_BSS dbg_topvar(bindsym_(b),0,bindtype_(b),DS_EXT+DS_UNDEF,d->fileline); #else /* Not all Codemist clients unix interfaces have BSS yet (e.g. COFF) */ dbg_topvar(bindsym_(b),0,bindtype_(b),1,d->fileline); #endif #endif goto switch_break; } } /* * Generate a special extern reference for PCC style * common variables. */ /* @@@ This is a genuine feature or config which other systems may want. */ /* Provide a switch one day soon. */ if ((stg & bitofstg_(s_extern)) && (stg & b_implicitstg)) (void)obj_symref(bindsym_(b), xr_data+xr_comref, sizeoftype(bindtype_(b))); } /* Add debug information for common and extern variables */ hackflag = 0; } } if (LanguageIsCPlusPlus) /* The next line should be a result of initstaticvar! */ dyninit = vg_get_dyninit(topflag); loc = bindaddr_(b); break; } if (usrdbg(DBG_PROC) && topflag && !(stg & (b_fnconst|bitofstg_(s_typedef)))) { /* Note that local (to a proc) statics are dealt with */ /* in flowgraph.c */ #ifdef TARGET_HAS_BSS /* @@@ <NAME>: do the BSS mods in a more principled way. */ /* The following code (tidied Jul-93 but not changed in effect) does */ /* several silly things: it sets DS_BSS even when the var is later */ /* given a definition. */ SET_BITMAP stg = bindstg_(b); if (curlex_member && realbinder_(curlex_member) == b) bindparent_(b) = bindparent_(curlex_member); dbg_topvar(bindsym_(b), loc, bindtype_(b), stg & b_globalregvar ? DS_REG : ( (stg & bitofstg_(s_extern) ? DS_EXT : 0) | (stg & u_bss ? DS_BSS : stg & u_constdata ? DS_CODE : 0) | (stg & b_undef ? DS_UNDEF : 0)), d->fileline); #else if (hackflag) dbg_topvar(bindsym_(b), bindaddr_(b), bindtype_(b), (bindstg_(b) & bitofstg_(s_extern)) != 0, d->fileline); else dbg_topvar(bindsym_(b), 0, bindtype_(b), 1, d->fileline); #endif bindparent_(b) = 0; } switch_break: /* AM Aug 90: bug fix to stop initialisation of a tentative to be a */ /* string pointer leaving the string pointer in the wrong place in the */ /* data segment in FEATURE_WR_STR_LITS mode. Now that the ANSI std */ /* has appeared, the whole tentative/bss/vargen edifice ought to be */ /* rationally reconstructed. */ /* * The next call is part of a disgusting fix for tentative * static and extern decls. What happens is as follows: * We parse along until we find a decl with no initialiser. * We then set 'b_undef' for this symbol and pass it to * 'instate_declaration()' above. This symbol is then entered * into the symbol table and 'b_undef' is UNSET if it is a * tentative decl so that 'genstaticparts()' WILL allocate it * some store. * Now if sometime later a REAL initialiser is found for * this symbol, this is detected by is_tentative() in mip/bind.c * which removes the zeros from the 'data.head/tail' lists and then call * 'genstaticparts()' to read the initialiser and finally we call * 'reset_vg_after_init_of_...()' below to fix the tables. */ reset_vg_after_init_of_tentative_defn(); SetDataArea(DS_ReadWrite); /* * Now generate the string literals we have delayed generating. * Also, we relocate the references to them by updating the * values in the data-generation templates that will cause those * references to be dumped in the data area... Note that we reverse * the work list so literals are generated in source order. * Note also that the following is a no-op unless FEATURE_WR_STR_LITS. */ { struct StrLit *p = (struct StrLit *) dreverse((List *)str_lits); for (; p != NULL; p = p->next) { p->d->val += data_size(); /* real offset of generated lit */ genstring(p->s, 0xffffff); /* literal dumped in data area */ padstatic(alignof_toplevel_static); } } return dyninit ? optimise0(dyninit) : 0; } void vg_generate_deferred_const(Binder *b) { DeclRhsList *d = (DeclRhsList *)(IPtr)bindaddr_(b); /* see defergenerating() uses */ Expr *dyninit = declinit_(d); bindstg_(b) |= b_generated; /* note reuse of b_generated */ bindaddr_(b) = 0; declinit_(d) = 0; (void) genstaticparts(d, YES, NO, dyninit); } #ifndef NO_DUMP_STATE void Vargen_LoadState(FILE *f) { if (LanguageIsCPlusPlus) Vargen_cpp_LoadState(f); else IGNORE(f); } void Vargen_DumpState(FILE *f) { if (LanguageIsCPlusPlus) Vargen_cpp_DumpState(f); else IGNORE(f); } #endif /* end of vargen.c */
stardot/ncc
ccthumb/options.h
/* * options.h -- compiler configuration options set at compile time * Copyright (C) Acorn Computers Ltd. 1988 * Copyright (C) Codemist Ltd., 1994 * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _options_LOADED #define _options_LOADED /* * The following conditional settings allow the produced compiler (TARGET) * to depend on the HOST (COMPILING_ON) environment. * Note that we choose to treat this independently of the target-machine / * host-machine issue. */ #include "toolver.h" #define NON_RELEASE_VSN TOOLVER_TCC #define DISABLE_ERRORS #define PCS_DEFAULTS (PCS_CALLCHANGESPSR|PCS_NOSTACKCHECK|PCS_NOFP) #ifdef TARGET_IS_NEWTON # define TARGET_MACHINE "Newton" # define TARGET_SYSTEM "Newton OS" # define TARGET_IS_NEWTONOS 1 # ifndef VERSIONSTRING # define VERSIONSTRING "0.11/C5.00" # endif # define TARGET_DEFAULT_BIGENDIAN 1 # define NO_INSTORE_FILES 1 /* no in-store headers for Newton. */ #else #define TARGET_SYSTEM "" #endif #define TARGET_HAS_DIVREM_FUNCTION 1 #define TARGET_HAS_DIV_10_FUNCTION 1 #ifdef COMPILING_ON_UNIX #define DRIVER_ENV { \ 0, (KEY_LINK), 0, \ "/usr/local/lib/arm", "/usr/local/lib/arm", "", "/", "/usr/local/lib/arm", "", "lst", \ "tasm", \ "armlink", NULL, "", \ "", "", "", \ "armlib.o", "hostlib.o", "armlib.o", "", "", "" \ } #else #ifdef COMPILING_ON_MSDOS #define DRIVER_ENV { \ 0, (KEY_LINK), 0, \ "\\arm\\lib", "\\arm\\lib", "", "\\", "\\arm\\lib", "", "lst", \ "tasm", \ "armlink", NULL, "", \ "", "", "", \ "armlib.o", "hostlib.o", "armlib.o", "", "", "" \ } #else #ifdef COMPILING_ON_MACINTOSH #define DRIVER_ENV { \ 0, (KEY_LINK), 0, \ "", "", "", ":", "", "", "lst", \ "tasm", \ "armlink", NULL, "", \ "", "", "", \ "armlib.o", "hostlib.o", "armlib.o", "", "", "" \ } #else #ifdef COMPILING_ON_RISC_OS #define DRIVER_ENV { \ 0, (KEY_LINK), 0, \ "$.clib", "$.clib", "$.plib", ".", "$.clib", "$.plib", "l", \ "tasm", \ "CHAIN:link", NULL, "", \ "", "", "", \ "o.ansilib", "o.hostlib", "o.ansilib", "o.fortlib", "o.fortlib", "o.plib" \ } #else #error Unknown host #endif #endif #endif #endif /* #define DO_NOT_EXPLOIT_REGISTERS_PRESERVED_BY_CALLEE 1 */ /* #define MOVC_KILLS_REGISTER_PRESERVED_BY_CALLEE_EXPLOITATION 1 */ /* to avoid conflict with host compilers */ #define C_INC_VAR "ARMINC" #define C_LIB_VAR "ARMLIB" #ifndef DRIVER_OPTIONS # define DRIVER_OPTIONS {"-D__thumb", NULL} #endif #ifndef RELEASE_VSN # define ENABLE_ALL 1 /* -- to enable all debugging options */ #endif #define HOST_WANTS_NO_BANNER 1 /* mac-specific options - find a better home for these sometime! */ #ifdef macintosh # define NO_STATIC_BANNER 1 pascal void SpinCursor(short increment); /* copied from CursorCtl.h */ # define ExecuteOnSourceBufferFill() SpinCursor(1) #endif #define MSG_TOOL_NAME "armcc" /* used to load correct NLS message file */ #define TARGET_HAS_ASD #define TARGET_HAS_DWARF #define TARGET_HAS_INLINE_ASSEMBLER 1 #define THUMB_INLINE_ASSEMBLER 1 #endif /* end of ccthumb/options.h */
stardot/ncc
mip/inline.h
<filename>mip/inline.h /* * inline.h: inline function expansion * Copyright (C) Advanced Risc Machines Ltd., 1993 * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _inline_h #define _inline_h #ifndef _cgdefs_h # include "cgdefs.h" #endif #ifndef _jopcode_h # include "jopcode.h" #endif typedef struct Inline_ArgBinderList Inline_ArgBinderList; struct Inline_ArgBinderList { Inline_ArgBinderList *cdr; Binder *globarg, *globnarrowarg, *instantiatednarrowarg; /* valid only after Inline_Restore */ TypeExpr *narrowtype; /* (globalised) */ }; typedef struct Inline_SavedFn { struct CurrentFnDetails fndetails; BlockHead *top_block, *bottom_block; BindList *var_binders, *reg_binders; Inline_ArgBinderList *args; /* The next two fields are to handle inlining of functions with narrow * arguments (passed widened, and narrowed on function entry). It doesn't * make much sense to do this when the function is inlined: instead, the * argument value is stored directly into the narrowed binder. * firstblockignore is a bitmap of the instructions in the first real block * of the function which handle the narrowing (and are to be omitted in the * inline copy). ix_narrowspenv is index in this block of the J_SETSPENV * adding the narrow binders (which must be moved before the argument * assignments. * firstblockignore will be null for functions without narrow arguments. */ uint32 firstblockignoresize; uint8 *firstblockignore; int32 ix_narrowspenv; uint32 ix_max; bool firstblockmergeable, lastblockmergeable; } Inline_SavedFn; typedef enum { T_Binder, T_AdconV, T_Adcon, T_Int, T_Plus } Inline_ArgSubstSort; typedef struct Inline_ArgSubstList Inline_ArgSubstList; struct Inline_ArgSubstList { Inline_ArgSubstList *cdr; Binder *arg; union { Binder *b; Expr *ex; } replacement; Expr *rest; Inline_ArgSubstSort sort; int32 size; /* a MEM_xx value (or MEM_NONE) */ bool refsleft; bool notnull; }; #define MEM_NONE 255 typedef struct { LabelNumber *exitlabel; BindList *env; int nresults; VRegnum resultregs[NARGREGS], newresultregs[NARGREGS]; Inline_ArgSubstList *argreplace; } Inline_RestoreControl; Inline_SavedFn *Inline_FindFn(Binder *b); bool Inline_Save(Binder *b, BindList *local_binders, BindList *regvar_binders); #if defined(CALLABLE_COMPILER) #define Inline_RealUse(b) ((void)0) #else void Inline_RealUse(Binder *b); #endif void Inline_Restore(Inline_SavedFn *p, Inline_RestoreControl *rc); void Inline_Init(void); void Inline_Tidy(void); #endif
stardot/ncc
arm/gen.c
/* * C compiler file arm/gen.c. * Copyright (C) Codemist Ltd, 1988. * Copyright (C) Acorn Computers Ltd., 1988 * Copyright (C) Advanced Risc Machines Ltd., 1991 * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 48 * Checkin $Date$ * Revising $Author$ */ /* @@@ AM memo: the uses of bind_global_() are spiritually wrong. */ /* @@@ LDS 30-Oct-92: wrong save when applied to top-level things. */ /* This file contains mainly arm dependent machine coding routines. */ /* Apr 89: xr_refext removed by AM as unused elsewhere. */ /* AM 3-Apr-87: add debugger. Beware that machine *independent* code should *not* go in this file. */ /* AM 10-Mar-87: add peepholer. Beware local_address() (q.v.) */ /* exports: void show_instruction(Icode *ic); RealRegister local_base(Binder *b); int32 local_address(Binder *b); bool immed_cmp(int32); bool fpliteral(FloatCon *val, J_OPCODE op); also (unfortunately for peephole): void setlabel(LabelNumber *); void branch_round_literals(LabelNumber *); */ #ifdef __STDC__ # include <string.h> #else # include <strings.h> #endif #define DEFINE_A_JOPTABLE 1 #include "globals.h" #include "mcdep.h" #include "mcdpriv.h" #include "aeops.h" #include "xrefs.h" #include "armops.h" #include "jopcode.h" #include "store.h" #include "codebuf.h" #include "regalloc.h" #include "builtin.h" /* for te_xxx */ #include "bind.h" /* for sym_insert_id */ #include "flowgraf.h" #include "errors.h" #include "inlnasm.h" #include "arminst.h" #include "ampops.h" #include "ampdis.h" unsigned integer_load_max; unsigned ldm_regs_max; static int32 nargwords, nregargwords, argwordsbelowfp, realargwordsbelowfp, fp_minus_sp; static int32 intsavewordsbelowfp, savewordsabovefp, argstopopabovefp; static uint32 condition_mask; static int32 mustlitby; static int32 literal_pool_start; static bool in_code; static int literal_pool_number; static LabelNumber *returnlab; static Symstr *lib_reloc_sym, *mod_reloc_sym; #ifndef PROFILE_COUNTS_INLINE static Symstr *fn_entry_sym, *fn_exit_sym; #endif static int32 spareregs; static void cmp_integer(RealRegister r,int32 n,RealRegister workreg,int32 mask,int32 flags); static void cmn_integer(RealRegister r,int32 n,RealRegister workreg,int32 mask,int32 flags); static void load_integer(RealRegister r,int32 n,int32 flags); static void add_integer(RealRegister r1,RealRegister r2,int32 n,int32 flags); static void sub_integer(RealRegister r1,RealRegister r2,int32 n,int32 flags); static void adc_integer(RealRegister r1,RealRegister r2,int32 n,int32 flags); static void sbc_integer(RealRegister r1,RealRegister r2,int32 n,int32 flags); static void rsb_integer(RealRegister r1,RealRegister r2,int32 n,int32 flags); static void rsc_integer(RealRegister r1,RealRegister r2,int32 n,int32 flags); static void and_integer(RealRegister r1,RealRegister r2,int32 n,int32 peep, bool dead_r1); static void orr_integer(RealRegister r1,RealRegister r2,int32 n,int32 flags); static void eor_integer(RealRegister r1,RealRegister r2,int32 n,int32 flags); static void tst_integer(RealRegister rt,RealRegister r2,int32 n,int32 flags); static void teq_integer(RealRegister rt,RealRegister r2,int32 n,int32 flags); static void multiply_integer(RealRegister r1,RealRegister r2,int32 n,int32 scc); static void mla_integer(RealRegister r1,RealRegister r2,int32 n,RealRegister acc,int32 scc); static void conditional_branch_to(int32 condition,LabelNumber *destination,bool bxxcase,int32 spadjust); static void routine_entry(int32 m); static void routine_saveregs(int32 m); static void routine_exit(int32 condition,bool to_pc,int32 spadjust); static void killipvalue(RealRegister r); static int32 LSBits(int32 mask, int n); typedef enum { UseFP, UseSP_Adjust, UseSP_NoAdjust } FP_RestoreBase; typedef struct { void (*show)(PendingOp const *p); void (*calleesave)(int32 mask); int32 (*restoresize)(int32 mask); void (*calleerestore)(int32 mask, int32 condition, FP_RestoreBase base, int32 offset); void (*saveargs)(int32); } FP_Gen; static FP_Gen const *fp_gen; static RealRegister local_base_a(int32 p); static int32 local_addr_a(int32 p); #define ROR(x, n) (((x)<<(32-(n))) | ((((uint32)x)>>(n)) & ((1L<<(32-(n)))-1L))) /* The set of registers whose values are potentially destroyed by normal */ /* calls (to finctions whose register usage isn't known) */ #define VolatileRegisters \ (regbit(R_A1) | regbit(R_A2) | regbit(R_A3) | regbit(R_A4) \ | regbit(R_IP) | M_LR) #define AllIntRegs 0xffff #define NoRegister ((RealRegister)-1) struct { bool known; int32 value; } register_values[16]; static struct { bool valid; RealRegister base; int32 offset; } ipvalue; static void KillKnownRegisterValues(uint32 mask) { RealRegister r; for (r = 0; r < 16; r++) if (mask & regbit(r)) register_values[r].known = NO; } static void KillKnownRegisterValue(RealRegister r) { if (r < 16) register_values[r].known = NO; } static void SetKnownRegisterValue(RealRegister r, int32 n) { if (r < 16) { register_values[r].value = n; register_values[r].known = YES; } } #define ValueIsKnown(r) (r < 16 && register_values[r].known) #define KnownValue(r) (register_values[r].value) static bool ValueBuildable(uint32 value, uint32 target, int flags, ValueDesc *vp) { int n; if (value == target) { vp->op3.shift = 0; return YES; } if (flags & V_ASR) for (n = 1; n < 32; n++) if (signed_rightshift_(value, n) == target) { vp->op3.shift = K_ASR(n); return YES; } if (flags & V_LSR) for (n = 1; n < 32; n++) if ((value >> n) == target) { vp->op3.shift = K_LSR(n); return YES; } if (flags & V_LSL) for (n = 1; n < 32; n++) if (value << n == target) { vp->op3.shift = K_LSL(n); return YES; } if (flags & V_ROR) for (n = 1; n < 32; n++) if (ROR(value, n) == target) { vp->op3.shift = K_ROR(n); return YES; } return NO; } static bool ValueBuildableOR(uint32 value, uint32 target, int flags, ValueDesc *vp) { int n; if (value == target) { vp->op3.shift = 0; return YES; } if (flags & V_ASR) for (n = 1; n < 32; n++) if ((value | signed_rightshift_(value, n)) == target) { vp->op3.shift = K_ASR(n); return YES; } if (flags & V_LSR) for (n = 1; n < 32; n++) if ((value | (value >> n)) == target) { vp->op3.shift = K_LSR(n); return YES; } if (flags & V_LSL) for (n = 1; n < 32; n++) if ((value | (value << n)) == target) { vp->op3.shift = K_LSL(n); return YES; } if (flags & V_ROR) for (n = 1; n < 32; n++) if ((value | ROR(value, n)) == target) { vp->op3.shift = K_ROR(n); return YES; } return NO; } static bool ValueBuildable_AnyOp(uint32 target, uint32 n, ValueDesc *vp) { RealRegister r; for (r = 0; r < 16; r++) if (register_values[r].known) { uint32 value = register_values[r].value; if ((value & n) == target) { vp->op3.rpair.op = OP_ANDR; vp->r = r; return YES; } if ((value & ~n) == target) { vp->op3.rpair.op = OP_BICR; vp->r = r; return YES; } if ((value | n) == target) { vp->op3.rpair.op = OP_ORRR; vp->r = r; return YES; } if ((value ^ n) == target) { vp->op3.rpair.op = OP_EORR; vp->r = r; return YES; } if ((value - n) == target) { vp->op3.rpair.op = OP_SUBR; vp->r = r; return YES; } if ((n - value) == target) { vp->op3.rpair.op = OP_RSBR; vp->r = r; return YES; } if ((value + n) == target) { vp->op3.rpair.op = OP_ADDR; vp->r = r; return YES; } } return NO; } static int RegisterContainingValue(uint32 n, int flags, ValueDesc *vp) { RealRegister r; for (r = 0; r < 16; r++) if (register_values[r].known) { uint32 value = register_values[r].value; if (ValueBuildable(value, n, flags, vp)) { vp->r = r; return V_Exact; } if ((flags & V_Negated) && ValueBuildable(value, 0-n, flags, vp)) { vp->r = r; return V_Negated; } if ((flags & V_Inverted) && ValueBuildable(value, ~n, flags, vp)) { vp->r = r; return V_Inverted; } if ((flags & V_Orred) && ValueBuildableOR(value, n, flags, vp)) { vp->r = r; return V_Orred; } if (flags & V_KAdded) { int32 ndiff = Arm_EightBits(n - value); if (ndiff > 0) { vp->r = r; vp->op3.add.k = ndiff; vp->op3.add.op = OP_ADDN; return V_KAdded; } ndiff = Arm_EightBits(value - n); if (ndiff > 0) { vp->r = r; vp->op3.add.k = ndiff; vp->op3.add.op = OP_SUBN; return V_KAdded; } } if (flags & V_RegPair) { int sh; if (ValueBuildable_AnyOp(n, value, vp)) { vp->op3.rpair.rm = r; return V_RegPair; } for (sh = 1; sh < 32; sh++) if (ValueBuildable_AnyOp(n, signed_rightshift_(value, sh), vp)) { vp->op3.rpair.rm = r | K_ASR(sh); return V_RegPair; } for (sh = 1; sh < 32; sh++) if (ValueBuildable_AnyOp(n, value >> sh, vp)) { vp->op3.rpair.rm = r | K_LSR(sh); return V_RegPair; } for (sh = 1; sh < 32; sh++) if (ValueBuildable_AnyOp(n, value << sh, vp)) { vp->op3.rpair.rm = r | K_LSL(sh); return V_RegPair; } for (sh = 1; sh < 32; sh++) if (ValueBuildable_AnyOp(n, ROR(value, sh), vp)) { vp->op3.rpair.rm = r | K_ROR(sh); return V_RegPair; } } } return 0; } static void DestroyIP(void) { ipvalue.valid = NO; spareregs |= regbit(R_IP); regmask |= regbit(R_IP); KillKnownRegisterValue(R_IP); } /* Claim a temporary register. GetTempReg may only be called once * for each JOPCODE. It returns -1 if there are no free registers. * As the spare register will be written to, any knowledge of the * temp reg is killed. */ static int GetTempReg(void) { int reg = spareregs & -spareregs; if (reg == 0) return -1; reg = logbase2(reg); regmask |= regbit(reg); killipvalue(reg); KillKnownRegisterValue(reg); return reg; } #define FreeTempRegs() (spareregs != 0) #ifdef TARGET_HAS_FP_OFFSET_TABLES static struct { ProcFPDesc desc; FPList **tail; int32 offset; } fpd; static void fpdesc_init(void) { fpd.desc.fplist = NULL; fpd.tail = &fpd.desc.fplist; fpd.desc.startaddr = fpd.desc.saveaddr = -1; fpd.desc.codeseg = bindsym_(codesegment); fpd.desc.initoffset = fpd.offset = -4; } static void fpdesc_startproc(void) { fpd.desc.startaddr = codebase+codep; } static void fpdesc_enterproc(void) { fpd.desc.saveaddr = codebase+codep; } static void fpdesc_setinitoffset(int32 n) { fpd.desc.initoffset = fpd.offset = n; } static void fpdesc_endproc(void) { fpd.desc.endaddr = codebase+codep; if (fpd.desc.fplist != NULL) obj_notefpdesc(&fpd.desc); } static void fplist_add(int32 n) { FPList *p; /* Suppress generation of fpdesc tables for compatibility with old armsds */ /* Not a user facility! Only used for testing, etc. */ if (var_cc_private_flags & 0x800000) return; p = (FPList *)SynAlloc(sizeof(FPList)); cdr_(p) = NULL; p->addr = codebase+codep; p->change = n; *fpd.tail = p; fpd.tail = &cdr_(p); fpd.offset += n; } static void fpdesc_notespchange(int32 n) { if (!(procflags & NONLEAF) || (pcs_flags & PCS_NOFP)) fplist_add(n); } static void fpdesc_newsp(int32 n) { if ((!(procflags & NONLEAF) || (pcs_flags & PCS_NOFP)) && fpd.desc.fplist != NULL) { n += 4*(intsavewordsbelowfp + realargwordsbelowfp + 3*bitcount(regmask & M_FVARREGS)); if (n - 4 - fpd.offset != 0) fplist_add(n - fpd.offset - 4); } } #else #define fpdesc_init() 0 #define fpdesc_newsp(n) 0 #define fpdesc_setinitoffset(n) 0 #define fpdesc_startproc() 0 #define fpdesc_enterproc() 0 #define fpdesc_endproc() 0 #define fpdesc_notespchange(n) 0 #endif #define AddCodeXref3(t, n) (codexrefs = (CodeXref *)global_list3(SU_Xref, codexrefs, t, n)) #define AddCodeXref4(t, n, x) (codexrefs = (CodeXref *)global_list4(SU_Xref, codexrefs, t, n, x)) #define AddCodeXref5(t, n, x, y) (codexrefs = (CodeXref *)global_list5(SU_Xref, codexrefs, t, n, x, y)) static void outinstr(int32 w) { if ((unsigned32 )w >= (unsigned32)0xff000000L) syserr(syserr_outinstr, (long)w); outcodeword(w ^ condition_mask, LIT_OPCODE); } static int32 outinstr3t(int32 w, Symstr *name, int xrflags, int32 tailcall) { int32 d; if ((unsigned32)w >= (unsigned32)0xff000000L) syserr(syserr_outinstr, (long)w); /* the next two lines' data structures may be mergeable. */ { d = obj_symref(name, xr_code | xrflags, 0); #ifndef TARGET_WANTS_LINKER_TO_RESOLVE_FUNCTION_REFERENCES if (d == -1 || tailcall) #endif { int32 type = tailcall ? X_TailCall : X_PCreloc; AddCodeXref4(type | (codebase+codep), name, 0); d = 0; } #ifdef AOF_VERSION_150 else #endif w += ((d - (codebase+codep+8)) >> 2) & 0x00ffffff; } outcodewordaux(w ^ condition_mask, LIT_RELADDR, name); return d; } static int32 outinstr3(int32 w, Symstr *name, int xrflags) { return outinstr3t(w, name, xrflags, NO); } static void out_ldm_instr(uint32 w) { /* Convert single register ldm/stm into a load/store - faster on some processors. */ int reg = power_of_two(w & 65535); if (reg >= 0 && !(w & F_PSR)) /* one reg ldm/stm without S-flag */ { w = (w & 0xF1BF0000) | 0x04000004 | F_RD(reg); if (!(w & 0x01000000)) /* post inc */ { if (w & F_WRITEBACK) w &= ~F_WRITEBACK; /* Post, WB -> remove writeback */ else w ^= 0x01000004; /* Post, no WB -> pre inc with 0 */ } } outinstr(w); } /* * Some stuff added by RCC to peephole LDR a, [b, #x]; LDR a, [c, #x+4] * and similar into a single LDMIA, and possibly some shuffling of * registers. This is probably of little use unless you have the hacks * to earlier stages of the code generator to encourage it to put * such things together (LRU-biased regalloc.c, and localopt.c). * * For the moment I am not going to integrate this with the rest of * the peepholing, because I think it is too confusing already. */ typedef enum { PENDING_NONE, PENDING_LD, PENDING_ST } PendingStoreAccess; typedef struct LoadOrStoreMul { int32 offset[16]; /* offset[i] holds the offset from the current value of basereg */ /* at which register i is to be loaded or stored (if bit i set */ /* in regbits). Constant additions to or subtractions from */ /* basereg (including load/store with writeback) do not generate */ /* any code, but alter baseadjust. After partial dumping of */ /* pending loads/stores which has changed the value in basereg, */ /* remaining offset[i]s must be corrected (and of course the */ /* value of baseadjust must also have been altered). */ PendingStoreAccess state; RealRegister basereg; int32 regbits; int32 deadregs; /* The subset of regbits for which the register is dead after its*/ /* (not yet performed) store. (Cannot be added to spareregs until*/ /* the store is actually done). */ /* What about registers not dead in their store, but dead after a /**/ /* later reference? Should be added to deadregs, but probably added */ /* to spareregs instead? Not currently a problem, since spareregs */ /* used only for MOVC and friends, which do an ldm_flush first, but */ /* in that case why bother with deadregs anyway? */ int32 baseadjust; /* Constant value the addition of which to basereg has been */ /* deferred. (See above) */ int32 baseadjusted; /* Use purely internal to ldm_flush, to track modifications to */ /* basereg (store location for Ri is offset[i]-baseadjusted) */ bool isload; /* The same as state == PENDING_LD, except that when flushing */ /* state is set to PENDING_NONE early */ bool basedead; /* TRUE if basereg is dead (so the update implied by baseadjust */ /* need not in fact be done) */ } LoadOrStoreMul; static LoadOrStoreMul ldm_state; static void ldm_reinit(void) { ldm_state.state = PENDING_NONE; } #define LDRMASK #define CONDITION(w) ((w) & 0xf0000000L) #define RN(w) (((w) >> 16) & 0xf) #define RD(w) (((w) >> 12) & 0xf) #define OFFSET(w) (((w)&F_UPDOWN_FIELD)==F_UP?((w)&0xfff):-((w)&0xfff)) #define OP_IS_LDR(w) \ (((w) & (0x0e000000L|F_LDRSTR_FIELD|F_BYTEWORD_FIELD)) ==\ (OP_POSTN|F_LDR|F_WORD)) #define OP_IS_STR(w) \ (((w) & (0x0e000000L|F_LDRSTR_FIELD|F_BYTEWORD_FIELD)) ==\ (OP_POSTN|F_STR|F_WORD)) #define ldm_printf if (localcg_debug(4)) cc_msg typedef struct SavedLDM { struct SavedLDM *cdr; int32 startoff; int32 endoff; int32 regset; RealRegister lastreg; } SavedLDM; /* While flushing pending loads/stores, s->baseadjusted holds the value */ /* by which s->basereg has been altered since the call to flush, and */ /* s->baseadjust always holds the amount still to be added to basereg */ /* (baseadjust and baseadjusted are always changed in step). */ static int32 ldm_type(int32 op, LoadOrStoreMul *s, int32 end) { if (!s->isload) op ^= (OP_LDMIA ^ OP_STMIA); if ((end < 0 && s->baseadjust < 0 && end >= s->baseadjust) || (end > 0 && s->baseadjust > 0 && end <= s->baseadjust)) { s->baseadjusted += end; s->baseadjust -= end; op |= F_WRITEBACK; } return op; } static void ldmstm_generate(SavedLDM *p, LoadOrStoreMul *s) { RealRegister basereg = s->basereg; if (p->startoff != p->endoff) { /* more than one register: ldm or stm likely */ int32 op = 0; RealRegister b = basereg; bool altered = NO; int32 start = p->startoff - s->baseadjusted; int32 end = p->endoff - s->baseadjusted; int32 addon = 0; ldm_printf("-- flushing a %s r%ld, {%lx}, offset %ld\n", (s->isload ? "LDM": "STM"), basereg, p->regset, start); if (start == 0) op = ldm_type(OP_LDMIA, s, end+4); else if (start == 4) op = ldm_type(OP_LDMIB, s, end); else if (end == 0) op = ldm_type(OP_LDMDA, s, start-4); else if (end == -4) op = ldm_type(OP_LDMDB, s, start); else if (start > 0 /* && end > 0 */ && s->baseadjust >= end) { if (s->baseadjust == end) addon = start-4, op = OP_LDMIB; else addon = start, op = OP_LDMIA, end += 4; op = ldm_type(op, s, end); } else if (/* start < 0 && */ end < 0 && s->baseadjust <= end) { if (s->baseadjust == start) addon = end+4, op = OP_LDMDB; else addon = end, op = OP_LDMDA, start -= 4; op = ldm_type(op, s, start); } else { if (s->isload) { b = p->lastreg; op = OP_LDMIA; } else { if (basereg == R_SP || member_RealRegSet(globalregset(), basereg)) { if ((b = GetTempReg()) >= 0) { ldm_printf(" using spare reg %ld as base\n", (long)b); if (regbit(b) & p->regset) syserr(syserr_stm_freeregs, p->regset, spareregs); } else { ldm_printf("No stm - would modify SP or global reg variable\n"); goto dosingly; } } else altered = YES; op = OP_STMIA; } if (Arm_EightBits(start) >= 0) addon = start; else if (Arm_EightBits(start-4) >= 0) { op += OP_LDMIB-OP_LDMIA; addon = start-4; } else if (Arm_EightBits(end) >= 0) { addon = end; op += OP_LDMDA-OP_LDMIA; } else if (Arm_EightBits(end+4) >= 0) { addon = end+4; op += OP_LDMDB-OP_LDMIA; } else addon = start; } if (addon != 0) add_integer(b, basereg, addon, 0); out_ldm_instr(op | F_RN(b) | p->regset); if (b == R_SP && (op & F_WRITEBACK)) { int32 n = 4 * bitcount(p->regset); fpdesc_notespchange((op & F_UPDOWN_FIELD) == F_DOWN ? n : -n); } if (altered) { s->baseadjusted += addon; s->baseadjust -= addon; } return; } dosingly: { /* Note that we don't need to take here to load the base register last (if it's in the set to be loaded), because this code is only executed with regset having more than one member for stores (and base R_SP, moreover) */ int32 rbit; int32 regset = p->regset; for (; (rbit = (regset & -regset)) != 0; p->startoff += 4, regset ^= rbit) { RealRegister r = power_of_two(rbit); int32 offx = p->startoff - s->baseadjusted; int32 op = (s->isload ? OP_LDR : OP_STR); ldm_printf("-- flushing %s r%ld, [r%ld, #%ld]\n", s->isload ? "LDR" : "STR", r, basereg, offx); if (offx == 0 && s->baseadjust != 0) { if (cdr_(p) == NULL) { if (-0xfff <= s->baseadjust && s->baseadjust <= 0xfff) offx = s->baseadjust; } else { int32 nextoff = cdr_(p)->startoff - s->baseadjusted; if ((s->baseadjust > 0 && nextoff > 0 && nextoff <= 0xfff && nextoff <= s->baseadjust) || (s->baseadjust < 0 && nextoff < 0 && nextoff >= -0xfff && nextoff >= s->baseadjust)) offx = nextoff; } if (offx != 0) { op ^= (OP_PREN ^ OP_POSTN); s->baseadjusted += offx; s->baseadjust -= offx; } } else if ((s->baseadjust > 0 && offx > 0 && offx <= s->baseadjust) || (s->baseadjust < 0 && offx < 0 && offx >= s->baseadjust)) { op |= F_WRITEBACK; s->baseadjusted += offx; s->baseadjust -= offx; } if (offx < 0) { op |= F_DOWN | (-offx); } else op |= F_UP | offx; outinstr(op | F_RN(basereg) | F_RD(r)); if (basereg == R_SP && ((op & OP_CLASS) == OP_POSTN || (op & F_WRITEBACK))) fpdesc_notespchange(-offx); } } } static void ldm_flush_r(int32 regbits, bool moreforbase) { struct LoadOrStoreMul *s = &ldm_state; RealRegister r; SavedLDM ldm[16], *ldmp = NULL, *atend = NULL; int ldmix = 0; bool basefree; if (s->state == PENDING_NONE) return; ldm_printf("-- ldm_flush: %lx\n", regbits); /* I assume we can generate max 16 instructions. It's easy to get over 10 generated instructions, so we have to check whether we need to dump the literals. */ if (codep + 16*4 >= mustlitby) dumplits2(YES); /* If there is no writeback, but the base is dead (and not being reloaded) we may produce better code if more than one LDM/STM is to be generated if we pretend there is writeback. */ if (s->baseadjust != 0) regbits = AllIntRegs; else if (s->basedead && !(s->regbits & regbit(s->basereg)) && !usrdbg(DBG_VAR)) { int32 maxoffset = 0; bool fake_wb = YES; for (r = 0; r < 16; r++) if (s->regbits & regbit(r)) { int32 off = s->offset[r]; if (maxoffset == 0 || maxoffset >= 0 && off >= 0 || maxoffset <= 0 && off <= 0) maxoffset = off; else fake_wb = NO; } if (fake_wb) { s->baseadjust = maxoffset; regbits = AllIntRegs; } } s->baseadjusted = 0; basefree = s->basedead && !(regbit(s->basereg) & s->regbits); for (r = 0; r < 16; r++) if (s->regbits & regbits & regbit(r)) { unsigned count = 1; RealRegister lastr; SavedLDM *cur = &ldm[ldmix]; s->regbits ^= regbit(r); cur->regset = regbit(r); cur->endoff = cur->startoff = s->offset[r]; cur->lastreg = r; for (lastr = r-1; lastr >= 0 && count < ldm_regs_max; lastr--, count++) if ((s->regbits & regbit(lastr)) && s->offset[lastr] == cur->startoff-4) { s->regbits ^= regbit(lastr); cur->regset |= regbit(lastr); cur->startoff -= 4; } for (lastr = r+1; lastr < 16 && count < ldm_regs_max; lastr++, count++) if ((s->regbits & regbit(lastr)) && s->offset[lastr] == cur->endoff+4) { s->regbits ^= regbit(lastr); cur->regset |= regbit(lastr); cur->endoff += 4; cur->lastreg = lastr; } { SavedLDM *p, **pp = &ldmp; if (cur->regset & regbit(s->basereg)) { /* if the base register is in the set to be loaded, it must be done last. */ for (; (p = *pp) != NULL; pp = &cdr_(p)) /* nothing */; atend = cur; } else { /* if there is writeback, sort into order of offset (increasing if increment, decreasing if decrement). If not, any order will do. This is all in aid of not pushing stuff on the stack before SP is advanced / popping it after SP retreats (in case base is R_SP). */ for (; (p = *pp) != atend; pp = &cdr_(p)) if ((s->baseadjust > 0 && cur->startoff < p->startoff) || (s->baseadjust < 0 && cur->startoff > p->startoff)) break; } *pp = cur; cdr_(cur) = p; ldmix++; } } if (s->regbits == 0) { s->state = PENDING_NONE; } for (; ldmp != NULL; ldmp = cdr_(ldmp)) { if (s->basedead && cdr_(ldmp) == NULL) s->baseadjust = 0; /* remove writeback of last transfer if base is dead */ ldmstm_generate(ldmp, s); if (s->isload) { KillKnownRegisterValues(ldmp->regset); spareregs &= ~ldmp->regset; } else spareregs |= ldmp->regset & s->deadregs; } s->deadregs &= s->regbits; /* clear deadbits */ if (s->regbits == 0 && basefree) spareregs |= regbit(s->basereg); if (s->baseadjusted != 0) /* basereg updated */ KillKnownRegisterValue(s->basereg); if (s->regbits != 0) { for (r = 0; r < 16; r++) if (s->regbits & regbit(r)) s->offset[r] -= s->baseadjusted; } else if (s->baseadjust != 0 && !s->basedead && !moreforbase) { add_integer(s->basereg, s->basereg, s->baseadjust, 0); s->baseadjust = 0; } } static void ldm_flush(void) { ldm_flush_r(AllIntRegs, NO); } static void ldm_setpending(LoadOrStoreMul *s, int32 w) { if (OP_IS_LDR(w)) { s->state = PENDING_LD; s->isload = YES; } else { s->state = PENDING_ST; s->isload = NO; } } static int ldm_addregoff(LoadOrStoreMul *s, RealRegister reg, int32 w, int32 deadbits) { int32 off; int32 newadjust; if ((w & OP_CLASS) == OP_PREN) { off = s->baseadjust + OFFSET(w); newadjust = (w & F_WRITEBACK) ? off : s->baseadjust; } else { off = s->baseadjust; newadjust = s->baseadjust + OFFSET(w); } if ((reg == s->basereg || (regbit(s->basereg) & s->regbits)) && newadjust != 0) return NO; if (regbit(reg) & s->regbits) { /* already have this reg */ if (s->state == PENDING_ST) { if (s->offset[reg] != off) { /* storing to different place */ return NO; /* handle it yourself! */ } } } else { if (s->state == PENDING_ST) { /* if a store, we must check there isn't already a store to the same place pending. If there is, we may just throw it away - it hasn't been used */ RealRegister r; for (r = 0; r < 16; r++) if ((s->regbits & regbit(r)) && s->offset[r] == off) { ldm_printf("--- ldm discard store %ld : [%ld, %ld]\n", r, s->basereg, off); s->regbits ^= regbit(r); break; } } s->regbits |= regbit(reg); } s->offset[reg] = off; s->baseadjust = newadjust; s->basedead = (deadbits & J_DEAD_R2) != 0; if (deadbits & J_DEAD_R1) s->deadregs |= regbit(reg); if (s->isload && s->basereg != reg) spareregs |= regbit(reg); /* * Now if this LDR has loaded the basereg, must not allow any * more to get peepholed onto it... */ ldm_printf("-- ldm add %s %ld : [%ld, %ld]\n", s->state == PENDING_ST ? "store": "load", reg, s->basereg, off); if (reg == s->basereg) ldm_flush(); return YES; } static void ldm_outinstr(int32 w, int32 deadbits) { struct LoadOrStoreMul *s = &ldm_state; bool mustdonow = var_ldm_enabled==0; RealRegister base = RN(w), rd = RD(w); if ((w & OP_CLASS) == OP_POSTN && (w & F_WRITEBACK)) /* LDRT or STRT special case */ mustdonow = YES; if (s->state != PENDING_NONE) { PendingStoreAccess access = OP_IS_LDR(w) ? PENDING_LD : PENDING_ST; if (mustdonow || s->state != access || base != s->basereg || (rd == base && access == PENDING_ST)) ldm_flush(); else { if (ldm_addregoff(s, rd, w, deadbits)) return; ldm_flush_r(AllIntRegs, YES); ldm_setpending(s, w); s->regbits = 0; s->deadregs = 0; ldm_addregoff(s, rd, w, deadbits); return; } } if (mustdonow || base == R_PC || base == rd) { outinstr(w); killipvalue(rd); KillKnownRegisterValue(rd); killipvalue(base); KillKnownRegisterValue(base); if (base == R_SP && ((w & OP_CLASS) == OP_POSTN || (w & F_WRITEBACK))) { int32 n = w & 0xfffL; fpdesc_notespchange((w & F_UPDOWN_FIELD) == F_DOWN ? n : -n); } return; } /* Now we are starting a fresh LDM/STM. */ ldm_setpending(s, w); s->basereg = base; s->regbits = 0; s->deadregs = 0; s->baseadjust = 0; ldm_addregoff(s, rd, w, deadbits); } static void ldm_c_flush(int32 regbits, int32 setscond) { if (ldm_state.state != PENDING_NONE) { if ((regbits & regbit(ldm_state.basereg)) || (setscond && condition_mask != C_ALWAYS)) ldm_flush(); else if (ldm_state.regbits & regbits) ldm_flush_r(regbits, NO); } } /* * End of the stuff to peephole LDM and STM. */ #define LABREF_BRANCH 0x00000000 /* ARM addressing modes for forw. refs. */ #define LABREF_B4096 0x01000000 #define LABREF_W256 0x02000000 #ifdef TARGET_HAS_DATA_VTABLES #define LABREF_WORD32 0x03000000 #endif struct DispDesc { int32 u_d, m; RealRegister r; }; static void bigdisp(struct DispDesc *x, int32 m, int32 mask, RealRegister r2r) { int32 w, modm; if (m<0) w = F_DOWN, modm = -m; else w = F_UP, modm = m; if (modm & ~mask) /* This can happen via LDRV/STRV with big frames */ { int32 n; ldm_c_flush(regbit(r2r) | regbit(R_IP), 0); if (ipvalue.valid && ipvalue.base == r2r) { int32 xw, offset = m - ipvalue.offset; if (offset < 0) xw = F_DOWN, offset = -offset; else xw = F_UP; if (offset <= mask) { x->u_d = xw; x->m = offset; x->r = R_IP; return; } } n = modm & ~mask; if (!(w & F_UP)) n = -n; add_integer(R_IP, r2r, n, 0); if (condition_mask == C_ALWAYS) { ipvalue.valid = YES; ipvalue.base = r2r; ipvalue.offset = n; spareregs &= ~regbit(R_IP); KillKnownRegisterValue(R_IP); } else DestroyIP(); r2r = R_IP; modm &= mask; } x->u_d = w; x->m = modm; x->r = r2r; } typedef union count_position { struct { unsigned int posn:12, line:16, file:4; } s; int32 i; } count_position; static void arthur_module_relocation(void) { /* * Dump relocation directives to relocate refs to * sl, -#_Lib$Reloc$Off and sl, -#_Mod$Reloc$off. */ Symstr *name; if (arthur_module == 1) { name = mod_reloc_sym; } else if (arthur_module == 2) { name = lib_reloc_sym; } else { syserr(syserr_module_reloc, arthur_module); return; } obj_symref(name, 0, 0); /* really a sort of xr_abs -- not code not data */ AddCodeXref3(X_backaddrlit | (codebase+codep), name); } /* The notion of addressability is common, but w.r.t what varies between machines. */ static void addressability(int32 n) { /* the next line does not hide sloppy programming, but allows us to test * whether we have run out of addressability before we know exactly how * many (less than 5!) arm instructions a JOPCODE will generate. * WD: well, it's actually nearer to 32 instructions. Eg. max 15 instr for * the LDM peepholer followed by a CLRC using 8 registers (15 instr again)... * Therefore the MOVC/CLRC/PUSHC and ldm peepholer now have seperate checks. */ n -= 5; if (litpoolp>=n) dumplits2(YES); if (codep-4*litpoolp+4*n < mustlitby) mustlitby = codep-4*litpoolp+4*n; } #define call_k(name, tail, xrflags, t) outinstr3t((tail) ? OP_B : OP_BL, name, xrflags, t) static void killipvalue(RealRegister r) { if (r == R_IP || r == ipvalue.base) ipvalue.valid = NO; } static void adjustipvalue(RealRegister r1, RealRegister r2, int32 k) { if (ipvalue.valid && r1 == r2) { if (r1 == R_IP) { if (condition_mask == C_ALWAYS) ipvalue.offset += k; else ipvalue.valid = NO, spareregs |= regbit(R_IP); } else if (r1 == ipvalue.base) { if (condition_mask == C_ALWAYS) ipvalue.offset -= k; else ipvalue.valid = NO, spareregs |= regbit(R_IP); } } else killipvalue(r1); KillKnownRegisterValue(r1); } static int32 C_FROMQ(int32 q) { switch (q) { /* We could exploit Q_NOT to simplify this code... */ case Q_EQ: case Q_UEQ: return C_EQ; case Q_NE: case Q_UNE: return C_NE; case Q_HS: return C_HS; case Q_LO: return C_LO; case Q_PL: return C_PL; case Q_MI: return C_MI; case Q_VS: return C_VS; case Q_VC: return C_VC; case Q_HI: return C_HI; case Q_LS: return C_LS; case Q_GE: return C_GE; case Q_LT: return C_LT; case Q_GT: return C_GT; case Q_LE: return C_LE; default: syserr("C_FROMQ(%lx)", (long)q); case Q_AL|Q_UBIT: /* ask HCM about this in flowgraf.c */ case Q_AL: return 0; } } static void tailcallxk(RealRegister r4, int32 m, int32 inst) { int32 restored = (regmask & (M_VARREGS|M_LR)) | regbit(R_SP); if (!(pcs_flags & PCS_NOFP)) restored |= regbit(R_FP); inst |= F_RN(r4) | m; if (!(restored & regbit(r4))) { routine_exit(C_FROMQ(Q_AL), NO, 0); outinstr(inst | F_RD(R_PC)); } else { /* r4 is something restored by routine_exit() */ outinstr(inst | F_RD(R_IP)); routine_exit(C_FROMQ(Q_AL), NO, 0); outinstr(OP_MOVR | F_RD(R_PC) | R_IP); } } static void tailcallxr(RealRegister r4, RealRegister r3, int32 inst) { int32 restored = (regmask & (M_VARREGS|M_LR)) | regbit(R_SP); if (!(pcs_flags & PCS_NOFP)) restored |= regbit(R_FP); inst |= F_RN(r4) | r3; if (!(restored & (regbit(r4)|regbit(r3)))) { routine_exit(C_FROMQ(Q_AL), NO, 0); outinstr(inst | F_RD(R_PC)); } else { /* r3 or r4 is something restored by routine_exit() */ outinstr(inst | F_RD(R_IP)); routine_exit(C_FROMQ(Q_AL), NO, 0); outinstr(OP_MOVR | F_RD(R_PC) | R_IP); } } static void out_ldr_str(unsigned32 op, int32 offset) { if (offset < 0) op |= F_DOWN, offset = -offset; else op |= F_UP; if (offset > 0xfff) syserr("out_ldr_str"); outinstr(op | offset); } int32 CheckSWIValue(int32 n) { if ((uint32)n > 0xffffff) { cc_err(gen_err_swi, n); n = 0xffffff; } return n; } typedef enum { RU_ALL = 0, RU_NONE = 1, RU_DONT_UPDATE_IP = 2, RU_DONT_UPDATE_REGVALUES = 4 } RegisterUsageFlags; #define SPAREREGS_MASK 0x5fff /* R0-R11, IP, LR */ static void UpdateRegisters(RegisterUsage *reguse, RegisterUsageFlags flags) { uint32 regswritten = regs_written(reguse); if (!(flags & RU_NONE)) { if (flags & RU_DONT_UPDATE_IP) regswritten &= ~regbit(R_IP); spareregs &= ~regs_out(reguse); spareregs |= regs_free(reguse); spareregs &= SPAREREGS_MASK; if (!(flags & RU_DONT_UPDATE_REGVALUES)) KillKnownRegisterValues(regswritten); if (regswritten & regbit(R_IP)) ipvalue.valid = NO; } } #define BaseIsWordAligned(op, peep) (((op) & J_BASEALIGN4) || ((peep) & P_BASEALIGNED)) void show_inst_direct(PendingOp *p) /* The types of the arguments here are rather unsatisfactory - in */ /* particular r3 is really a big union. */ { struct DispDesc dispdesc; int32 w, msh = 0, illbits; J_OPCODE op = p->ic.op; RealRegister r1 = p->ic.r1.i, r2 = p->ic.r2.i, r3 = p->ic.r3.i, r4 = p->ic.r4.i; uint32 flags = p->ic.flags; int32 peep = p->peep, dataflow = p->dataflow; RegisterUsage regusage; RegisterUsageFlags regflags = RU_ALL; if (localcg_debug(4)) a_pr_jopcode(p); CheckJopcodeP(p, JCHK_MEM | JCHK_REGS | JCHK_SYSERR); if (codep >= mustlitby) dumplits2(YES); GetRegisterUsage(p, &regusage); msh = (op & J_SHIFTMASK) >> J_SHIFTPOS; if ((msh & SHIFT_RIGHT) == 0) { if (msh & SHIFT_ARITH) /* this encoding for ROR (left + arith) is somewhat delicate */ msh = K_ROR(msh & SHIFT_MASK); else msh = K_LSL(msh & SHIFT_MASK); } else if (msh & SHIFT_ARITH) msh = K_ASR(msh & SHIFT_MASK); else msh = K_LSR(msh & SHIFT_MASK); if (peep & P_RSHIFT) { if (msh) syserr(syserr_shifts); switch (peep & P_RSHIFT) { case P_LSL: msh = R_LSL(r4); break; case P_LSR: msh = R_LSR(r4); break; case P_ASR: msh = R_ASR(r4); break; case P_ROR: msh = R_ROR(r4); break; } } /* to enable future JOPCODE peephole optimisation expand_jop_macros() tries quite hard not to call show_inst() with instructions with no effect. */ /* illbits (and peep) check that unexpected (erroneous!) bits are not set */ illbits = op & (Q_MASK | J_SIGNED | J_UNSIGNED | J_NEGINDEX | J_SHIFTMASK); switch (op & ~(Q_MASK | J_SIGNED | J_UNSIGNED | J_NEGINDEX | J_SHIFTMASK)) #define TRANS(op) ((peep & P_TRANS) ? (peep &= ~P_TRANS, (op)|F_WRITEBACK) : (op)) #define prepost_H(op) \ ((peep & P_POST) ? (peep &= ~P_POST, TRANS(OP_H_POSTN)) : \ (peep & P_PRE) ? (peep &= ~P_PRE, OP_H_PREN | F_WRITEBACK) : OP_H_PREN) #define prepost(op) \ ((peep & P_POST) ? (peep &= ~P_POST, TRANS(OP_POSTN)) : \ (peep & P_PRE) ? (peep &= ~P_PRE, OP_PREN | F_WRITEBACK) : OP_PREN) #define prepostr_H(op) \ ((peep & P_POST) ? (peep &= ~P_POST, TRANS(OP_H_POSTR)) : \ (peep & P_PRE) ? (peep &= ~P_PRE, OP_H_PRER | F_WRITEBACK) : OP_H_PRER) #define prepostr(op) \ ((peep & P_POST) ? (peep &= ~P_POST, TRANS(OP_POSTR)) : \ (peep & P_PRE) ? (peep &= ~P_PRE, OP_PRER | F_WRITEBACK) : OP_PRER) { case J_ORG: /* pad with OP_NOOP's -- here mov r0,r0. Proper code? */ while (codep < r3) outinstr(OP_MOVR); if (codep != r3) syserr("J_ORG"); break; case J_WORD: ldm_flush(); outinstr(r3 ^ C_ALWAYS); break; case J_CMPK: /* N.B. that CMPK can use R_IP as a work register */ ldm_c_flush(regs_used(&regusage), 1); cmp_integer(r2, r3, R_IP, op & Q_MASK, peep); peep &= ~(P_CMPZ | P_SETCC | P_SETPSR); illbits &= ~Q_MASK; break; case J_CMNK: /* N.B. that CMNK can use R_IP as a work register */ ldm_c_flush(regs_used(&regusage), 1); cmn_integer(r2, r3, R_IP, op & Q_MASK, peep); peep &= ~(P_CMPZ | P_SETCC | P_SETPSR); illbits &= ~Q_MASK; break; #ifdef RANGECHECK_SUPPORTED case J_CHKLK: ldm_flush(); cmp_integer(r2, r3, R_IP, Q_LT, 0); outinstr3(OP_BL ^ Q_LT, sim.abcfault, 0); break; case J_CHKUK: ldm_flush(); cmp_integer(r2, r3, R_IP, Q_GT, 0); outinstr3(OP_BL ^ Q_GT, sim.abcfault, 0); break; case J_CHKLR: ldm_flush(); outinstr(OP_CMPR | F_RN(r2) | mr | msh); outinstr3(OP_BL ^ Q_LT, sim.abcfault, 0); break; case J_CHKUR: ldm_flush(); outinstr(OP_CMPR | F_RN(r2) | mr | msh); outinstr3(OP_BL ^ Q_GT, sim.abcfault, 0); break; case J_CHKNEK: ldm_flush(); cmp_integer(r2, r3, R_IP, Q_EQ, 0); outinstr3(OP_BL ^ Q_EQ, sim.valfault, 0); break; #endif /* RANGECHECK_SUPPORTED */ /* N.B. having someone (e.g. show_instruction) changing the next 3 ops into */ /* ADDK 0; RSBK 0; and RSBK -1; would simplify peepholing them with CMP 0 */ /* and remove 3 cases from this table but using more general code */ /* No - a better idea: use the peepholer to squash shifts and ops together */ /* (via V_INTERNAL reg), but also turn solitary shifts into J_MOV+J_SHIFTM */ /* N.B. This would make J_SHIFTM a P_PEEPn bit local to this file */ case J_MOVR: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); if (r1!=r3 || (peep & P_CMPZ)) outinstr(OP_MOVR | F_RD(r1) | r3 | SCC_of_PEEP(peep)); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); break; case J_NEGR: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); outinstr(OP_RSBN | F_RD(r1) | F_RN(r3) | SCC_of_PEEP(peep)); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); illbits &= ~J_SHIFTMASK; break; case J_NOTR: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); outinstr(OP_MVNR | F_RD(r1) | r3 | msh | SCC_of_PEEP(peep)); peep &= ~(P_RSHIFT | P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); illbits &= ~J_SHIFTMASK; break; case J_MOVK: ldm_c_flush(regs_used(&regusage), 0); load_integer(r1, r3, peep); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); regflags = RU_DONT_UPDATE_REGVALUES; break; case J_ADDK: if (r1 == r2 && ldm_state.state != PENDING_NONE && r1 == ldm_state.basereg && !(peep & P_CMPZ) && r3 <= 0xfff) { ldm_state.baseadjust += r3; } else { if (r1 == R_SP && ( (r3 < 0 && ldm_state.state != PENDING_LD) /* If the stack is being extended, its ok to move loads */ /* before the stack movement (they can't be from the new */ /* bit of stack without an intervening store which will */ /* flush the LDM state. */ || (r3 > 0 && ldm_state.state != PENDING_ST))) /* Similarly, if the stack is being contracted, stores */ /* are OK. */ ldm_flush(); else ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); add_integer(r1, r2, r3, peep); adjustipvalue(r1, r2, r3); regflags |= RU_DONT_UPDATE_IP; /* as adjustipvalue has already done this */ peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); } break; case J_SUBK: { ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); sub_integer(r1, r2, r3, peep); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); } break; case J_ADCK: { ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); adc_integer(r1, r2, r3, peep); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); } break; case J_SBCK: { ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); sbc_integer(r1, r2, r3, peep); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); } break; case J_RSBK: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); rsb_integer(r1, r2, r3, peep); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); break; case J_RSCK: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); rsc_integer(r1, r2, r3, peep); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); break; case J_ANDK: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); if ((dataflow & J_DEAD_R1) && (peep & P_CMPZ)) tst_integer(r1, r2, r3, peep); else and_integer(r1, r2, r3, peep, dataflow & J_DEAD_R1); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); break; case J_TSTK: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); tst_integer(R_IP, r2, r3, peep); peep &= ~(P_CMPZ | P_SETCC | P_SETPSR | P_ZONLY | Q_MASK); break; case J_ORRK: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); orr_integer(r1, r2, r3, peep); peep &= ~(P_CMPZ | P_SETCC | P_SETPSR | P_ZONLY | Q_MASK); break; case J_EORK: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); if ((dataflow & J_DEAD_R1) && (peep & P_CMPZ)) teq_integer(r1, r2, r3, peep); else eor_integer(r1, r2, r3, peep); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); break; case J_TEQK: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); teq_integer(R_IP, r2, r3, peep); peep &= ~(P_CMPZ | P_SETCC | P_SETPSR | P_ZONLY | Q_MASK); break; case J_MULK: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); multiply_integer(r1, r2, r3, SCC_of_PEEP(peep)); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); break; case J_MLAK: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); mla_integer(r1, r2, r3, r4, SCC_of_PEEP(peep)); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); break; case J_SHRK: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); if (r3!=0) { if (r3<=0 || r3>32) syserr(syserr_silly_shift, (long)r3); outinstr(OP_MOVR | F_RD(r1) | r2 | SCC_of_PEEP(peep) | (op & J_SIGNED ? K_ASR(r3) : K_LSR(r3))); illbits &= ~(J_SIGNED|J_UNSIGNED); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); break; } /* drop through if shift by 0 */ case J_SHLK: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); if (r3<0 || r3>31) syserr(syserr_silly_shift, (long)r3); outinstr(OP_MOVR | F_RD(r1) | r2 | SCC_of_PEEP(peep) | K_LSL(r3)); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); illbits &= ~(J_SIGNED|J_UNSIGNED); break; case J_RORK: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); if (r3<0 || r3>31) syserr(syserr_silly_shift, (long)r3); /* r3=0 is RRX */ outinstr(OP_MOVR | F_RD(r1) | r2 | SCC_of_PEEP(peep) | (r3 == 0 ? K_RRX : K_ROR(r3))); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); break; case J_SHLR: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); outinstr(OP_MOVR | F_RD(r1) | r2 | SCC_of_PEEP(peep) | R_LSL(r3)); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); illbits &= ~(J_SIGNED|J_UNSIGNED); break; case J_SHRR: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); outinstr(OP_MOVR | F_RD(r1) | r2 | SCC_of_PEEP(peep) | (op & J_SIGNED ? R_ASR(r3) : R_LSR(r3))); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); illbits &= ~(J_SIGNED|J_UNSIGNED); break; case J_RORR: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); outinstr(OP_MOVR | F_RD(r1) | r2 | SCC_of_PEEP(peep) | R_ROR(r3)); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); illbits &= ~(J_SIGNED|J_UNSIGNED); break; case J_CMPR: ldm_c_flush(regs_used(&regusage), 1); outinstr(OP_CMPR | SCC_of_PEEP(peep) | F_RN(r2) | r3 | msh); illbits &= ~(Q_MASK|J_SHIFTMASK); peep &= ~(P_RSHIFT|P_SWAPCOND|P_CMPZ|P_SETCC|P_SETPSR); break; case J_CMNR: ldm_c_flush(regs_used(&regusage), 1); outinstr(OP_CMNR | SCC_of_PEEP (peep) | F_RN(r2) | r3 | msh); illbits &= ~(Q_MASK|J_SHIFTMASK); peep &= ~(P_RSHIFT|P_SWAPCOND|P_CMPZ|P_SETCC|P_SETPSR); break; case J_ANDR: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); { int32 opc = OP_ANDR, rd = F_RD(r1); if ((dataflow & J_DEAD_R1) && (peep & P_CMPZ)) opc = OP_TSTR, rd = 0; outinstr(opc | SCC_of_PEEP(peep) | rd | F_RN(r2) | r3 | msh); illbits &= ~J_SHIFTMASK; peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK | P_RSHIFT); break; } case J_EORR: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); { int32 opc = OP_EORR, rd = F_RD(r1); if ((dataflow & J_DEAD_R1) && (peep & P_CMPZ)) opc = OP_TEQR, rd = 0; outinstr(opc | SCC_of_PEEP(peep) | rd | F_RN(r2) | r3 | msh); illbits &= ~J_SHIFTMASK; peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK | P_RSHIFT); break; } case J_TSTR: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); { outinstr(OP_TSTR | SCC_of_PEEP(peep) | F_RN(r2) | r3 | msh); illbits &= ~J_SHIFTMASK; peep &= ~(P_CMPZ | P_SETCC | P_SETPSR| P_ZONLY | Q_MASK | P_RSHIFT); break; } case J_TEQR: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); { outinstr(OP_TEQR | SCC_of_PEEP(peep) | F_RN(r2) | r3 | msh); illbits &= ~J_SHIFTMASK; peep &= ~(P_CMPZ | P_SETCC | P_SETPSR | P_ZONLY | Q_MASK | P_RSHIFT); break; } #ifdef ARM_INLINE_ASSEMBLER case J_MRS: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); { outinstr(OP_MRS | F_RD(r1) | (r2 & SPSR ? K_SPSR : 0)); peep &= ~(Q_MASK); break; } case J_MSR: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); { outinstr(OP_MSR | r3 | (r2 & SPSR ? K_SPSR : 0) | F_RN(r2 & PSR_FLAGS)); peep &= ~(Q_MASK); break; } case J_MSK: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); { r3 = Arm_EightBits(r3); outinstr(OP_MSR | OP_RXN | r3 | (r2 & SPSR ? K_SPSR : 0) | F_RN(r2 & PSR_FLAGS)); peep &= ~(Q_MASK); break; } case J_SWPB: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); { outinstr(OP_SWPB | F_RD(r1) | F_RN(r2) | r3); peep &= ~(Q_MASK); break; } case J_SWP: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); { outinstr(OP_SWP | F_RD(r1) | F_RN(r2) | r3); peep &= ~(Q_MASK); break; } case J_NULLOP: outinstr(OP_MOVR); break; #endif #define irrop(alu) \ ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); \ outinstr((alu) | SCC_of_PEEP(peep) | \ F_RD(r1) | F_RN(r2) | r3 | msh); \ illbits &= ~J_SHIFTMASK; \ peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK | P_RSHIFT); case J_BICR: irrop(OP_BICR); break; case J_ORRR: irrop(OP_ORRR); break; case J_ADDR: irrop(OP_ADDR); break; case J_ADCR: irrop(OP_ADCR); break; case J_SUBR: irrop(OP_SUBR); break; case J_SBCR: irrop(OP_SBCR); break; case J_RSBR: irrop(OP_RSBR); break; case J_RSCR: irrop(OP_RSCR); break; #undef irrop case J_MLAR: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); outinstr(OP_MLA | F_RN(r1) | F_RD(r4) | (r2 << 8) | r3 | SCC_of_PEEP(peep)); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); break; case J_MULR: ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); outinstr(OP_MUL | F_RN(r1) | (r2 << 8) | r3 | SCC_of_PEEP(peep)); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); break; case J_MULL: case J_MLAL: { uint32 mulop = ((op & ~J_SIGNED) == J_MULL) ? OP_UMULL : OP_UMLAL; ldm_c_flush(regs_used(&regusage), SCC_of_PEEP(peep)); if (p->ic.op & J_SIGNED) mulop += (OP_SMULL - OP_UMULL); outinstr(mulop | F_RN(r2) | F_RD(r1) | (r4 << 8) | r3 | SCC_of_PEEP(peep)); peep &= ~(P_CMPZ | P_SETCC | P_ZONLY | Q_MASK); illbits &= ~J_SIGNED; break; } #ifdef ARM_INLINE_ASSEMBLER case J_SWI: ldm_flush(); outinstr(OP_SWI | r1); break; case J_BL: ldm_flush(); call_k(bindsym_((Binder *) r1), 0, 0, 0); break; #endif case J_OPSYSK: ldm_flush(); outinstr(OP_SWI | r3); break; case J_CALLK: ldm_flush(); call_k((Symstr *)r3, 0, (k_fltregs_(r2) != 0 ? aof_fpreg : 0), 0); break; case J_TAILCALLK: ldm_flush(); if (pcs_flags & PCS_REENTRANT) outinstr(OP_MOVR | F_RD(R_IP) | R_SB | SCC_of_PEEP(peep)); routine_exit(C_FROMQ(Q_AL), NO, 0); call_k((Symstr *)r3, 1, (k_fltregs_(r2) != 0 ? aof_fpreg : 0), pcs_flags & PCS_REENTRANT); break; case J_CALLR: /* c.regalloc has ensured that r3 and R_LR clash */ ldm_flush(); outinstr(OP_MOVR | F_RD(R_LR) | R_PC); if (pcs_flags & PCS_INTERWORK) outinstr(OP_BX | r3); else outinstr(OP_MOVR | F_RD(R_PC) | r3); break; case J_CALLX: if (pcs_flags & PCS_INTERWORK) syserr(syserr_interwork); ldm_flush(); { int32 iop = OP_ADDN; int32 n = Arm_EightBits(r3); if (n < 0) { n = Arm_SplitForAdd(r4, r3, &iop); if (iop == OP_ADDN) r3 -= n; else r3 += n; add_integer(R_IP, r4, r3, 0); r4 = R_IP; r3 = n; } outinstr(OP_MOVR | F_RD(R_LR) | R_PC); outinstr(iop | F_RD(R_PC) | F_RN(r4) | Arm_EightBits(r3)); } break; case J_CALLI: if (pcs_flags & PCS_INTERWORK) syserr(syserr_interwork); ldm_flush(); bigdisp(&dispdesc, r3, 0xfff, r4); outinstr(OP_MOVR | F_RD(R_LR) | R_PC); outinstr(prepost(op) | F_LDR | dispdesc.u_d | F_WORD | F_RD(R_PC) | F_RN(dispdesc.r) | dispdesc.m); break; case J_CALLXR: if (pcs_flags & PCS_INTERWORK) syserr(syserr_interwork); ldm_flush(); outinstr(OP_MOVR | F_RD(R_LR) | R_PC); outinstr(((op & J_NEGINDEX) ? OP_SUBR : OP_ADDR) | F_RD(R_PC) | F_RN(r4) | r3 | msh); illbits &= ~(J_NEGINDEX|J_SHIFTMASK); break; case J_CALLIR: if (pcs_flags & PCS_INTERWORK) syserr(syserr_interwork); ldm_flush(); outinstr(OP_MOVR | F_RD(R_LR) | R_PC); outinstr(OP_LDRR | (op & J_NEGINDEX ? F_DOWN : F_UP) | F_RD(R_PC) | F_RN(r4) | r3 | msh); illbits &= ~(J_NEGINDEX|J_SHIFTMASK); break; case J_TAILCALLX: if (pcs_flags & PCS_INTERWORK) syserr(syserr_interwork); ldm_flush(); { int32 iop = OP_ADDN; int32 n = Arm_EightBits(r3); if (n < 0) { n = Arm_SplitForAdd(r4, r3, &iop); if (iop == OP_ADDN) r3 -= n; else r3 += n; add_integer(R_IP, r4, r3, 0); r4 = R_IP; r3 = n; } tailcallxk(r4, Arm_EightBits(r3), iop); } break; case J_TAILCALLI: if (pcs_flags & PCS_INTERWORK) syserr(syserr_interwork); ldm_flush(); bigdisp(&dispdesc, r3, 0xfff, r4); tailcallxk(dispdesc.r, dispdesc.m, prepost(op) | F_LDR | dispdesc.u_d | F_WORD); break; case J_TAILCALLXR: if (pcs_flags & PCS_INTERWORK) syserr(syserr_interwork); ldm_flush(); tailcallxr(r4, r3, ((op & J_NEGINDEX) ? OP_SUBR : OP_ADDR) | msh); illbits &= ~(J_NEGINDEX|J_SHIFTMASK); break; case J_TAILCALLIR: if (pcs_flags & PCS_INTERWORK) syserr(syserr_interwork); ldm_flush(); tailcallxr(r4, r3, OP_LDRR | (op & J_NEGINDEX ? F_DOWN : F_UP) | msh); illbits &= ~(J_NEGINDEX|J_SHIFTMASK); break; case J_TAILCALLR: ldm_flush(); if (pcs_flags & PCS_INTERWORK) { if (!((regmask & (M_VARREGS|M_LR)) & regbit(r3))) { routine_exit(C_FROMQ(Q_AL), NO, 0); outinstr(OP_BX | r3); } else { /* mr is restored by routine exit */ outinstr(OP_MOVR | F_RD(R_IP) | r3); routine_exit(C_FROMQ(Q_AL), NO, 0); outinstr(OP_BX | R_IP); } } else tailcallxk(r3, 0, OP_ADDN); break; case J_COUNT: ldm_flush(); #ifndef TARGET_IS_UNIX # ifndef PROFILE_COUNTS_INLINE outinstr3(OP_BL, fn_entry_sym, 0); # else /* (int)r1 is ? (I would like the character on the line) ???? */ /* (char *)r2 is the name of the file, and (int)r3 is the line number */ /* within that file. I will assume here a sensible limit on the length */ /* of files and hence pack these two pieces of information into a single */ /* 32-bit word. The structure used is count_position, and up to 16 files */ /* can be referenced. If there is any danger of running out of same I will */ /* flush out the table used to decode files names and start again. */ { count_position k; k.i = 0; /* just to stop compiler winging */ /* beware that the next line may flush literals etc. */ k.s.file = lit_of_count_name((char *)r2); k.s.line = (unsigned int)r3; k.s.posn = 0; /* Not available here */ outinstr3(OP_BL, count1routine, 0); outcodeword(0, LIT_NUMBER); /* what it increments */ outcodeword(k.i, LIT_NUMBER); } # endif #endif break; case J_INFOLINE: ldm_flush(); /* ensure codep is correct */ dbg_addcodep((VoidStar)r1, codebase+codep); /* hack -- see armdbg.c */ break; case J_INFOSCOPE: ldm_flush(); /* ensure codep is correct */ dbg_addcodep(NULL, codebase+codep); /* hack -- see armdbx.c */ break; case J_INFOBODY: dbg_bodyproc(/*codebase+codep*/); break; case J_STRING: ldm_flush(); /* flowgraf.c has replaced J_STRING by J_ADCON if FEATURE_WR_STR_LITS. */ /* * Standard ANSI mode - string lits read-only in the code seg. * Ensure that the literal will be dumped in time for it to be * addressable. Note that by using coarser alignment than 4-bytes * I could often cover a longer span of addresses - but that does * not seem worthwhile here. */ { int32 disp, offset = (int32)r2, addon = 0; StringSegList *s = (StringSegList *)r3; if ((offset & 3) != 0) addon = offset, offset = 0; if ((disp = lit_findstringincurpool(s)) >= 0) { /* This reference must be addressable if the previous one was */ addfref_(litlab, codep | LABREF_W256); outinstr(OP_ADDN | F_RD(r1) | F_RN(R_PC) | ((disp+offset) >> 2) | 0xf00); if (addon != 0) add_integer(r1, r1, addon, 0); break; } /* NB here that on the ARM a backwards displacement can go as far as 0x3fc */ /* (=1020) but NOT as far as 0x400 (sign & magnitude, not 2's comp offset) */ disp = lit_findstringinprevpools(s, codebase+codep+8-1020+offset); if (disp >= 0) { disp = (codebase+codep+8-disp+offset)>>2; outinstr(OP_SUBN | F_RD(r1) | F_RN(R_PC) | disp | 0xf00); if (addon != 0) add_integer(r1, r1, addon, 0); break; } /* For sufficiently long strings, we ensure that there's just one copy * even at the expense of more expensive access. */ if (stringlength(s) <= 8 || (disp = lit_findstringinprevpools(s, 0)) < 0) { addressability(256-offset/4); addfref_(litlab, codep | LABREF_W256); outinstr(OP_ADDN | F_RD(r1) | F_RN(R_PC) | (litpoolp + (offset>>2)) | 0xf00); codeseg_stringsegs((StringSegList *)r3, YES); if (addon != 0) add_integer(r1, r1, addon, 0); break; } r3 = (IPtr)bindsym_(codesegment); r2 = disp + addon + offset; /* fall through to generate an ADCON */ } case J_ADCON: case J_ADCON+J_BASEALIGN4: ldm_flush(); { Symstr *name = (Symstr *)r3; #ifdef TARGET_HAS_AOF # ifdef CONST_DATA_IN_CODE if (name == bindsym_(constdatasegment) && ((pcs_flags & PCS_REENTRANT) || (pcs_flags & PCS_ACCESS_CONSTDATA_WITH_ADR))) { int32 offset, op = OP_ADDN; int32 maskhi = 0x3fc00L, masklo = 0x3ffL; ldm_flush(); /* ensure codep is correct */ AddCodeXref4(X_DataAddr1+codebase+codep, name, 0); offset = (int32)r2-(codebase+codep+8); if (offset < 0) op = OP_SUBN, offset = -offset; if (offset & 3) { maskhi = 0xff00L; masklo = 0xffL; } outcodewordaux(condition_mask | op | F_RD(r1) | F_RN(R_PC) | Arm_EightBits(offset & maskhi), LIT_RELADDR, (VoidStar)name); outinstr(op | F_RD(r1) | F_RN(r1) | Arm_EightBits(offset & masklo)); } else # endif #endif if (pcs_flags & PCS_REENTRANT) { int i = adconpool_find((int32)r2, LIT_ADCON, name); ldm_flush(); /* ensure codep is correct */ AddCodeXref4(X_DataVal+codebase+codep, adconpool_lab, 0); outcodewordaux(condition_mask | OP_LDR | F_UP | F_RD(r1) | F_RN(R_SB) | i, LIT_RELADDR, (VoidStar)adconpool_lab); } else { int32 offset = (int32)r2; int32 i; /* Try to find adcon in following order: 1. current literal pool, */ /* 2. previous addressable pools, 3. new allocation in current pool. */ if ((i = lit_findword(offset, LIT_ADCON, name, LITF_INCODE|LITF_FIRST|LITF_LAST|LITF_PEEK)) >= 0) { /* adcon available in current literal pool */ /* if previous ref was addressable this one will be */ addfref_(litlab, codep | LABREF_B4096); outinstr(OP_LDR | F_UP | F_RD(r1) | F_RN(R_PC) | i); } else if ((i = lit_findadcon(name,offset,codebase+codep+8-0xffc)) >= 0) outinstr(OP_LDR | F_DOWN | F_RD(r1) | F_RN(R_PC) | codebase+codep+8-i); else { /* ensure that the literal that I am about to issue can be addressed */ addressability(1024); i = lit_findword(offset, LIT_ADCON, name, LITF_INCODE|LITF_FIRST|LITF_LAST|LITF_NEW); addfref_(litlab, codep | LABREF_B4096); outinstr(OP_LDR | F_UP | F_RD(r1) | F_RN(R_PC) | i); } /*@@@ AM: generalise the next routine into a obj_symflag() routine? */ /*@@@ or would the J_FNCON approach be better? Discuss. */ /*@@@ Hmm: what happens to static int a, *b=&a in arthur mode? */ /*@@@ ... we should really fault this. */ if (arthur_module) { ExtRef *x = symext_(name); /* flowgraf's obj_symref should ensure x!=0, but be careful */ if (x && !(x->extflags & xr_code)) { /* The next line relocates the following LDR# */ arthur_module_relocation(); outinstr(OP_LDR | F_DOWN | F_RD(R_IP) | F_RN(R_SL)); outinstr(OP_ADDR | F_RD(r1) | F_RN(R_IP) | r1); DestroyIP(); } } } } break; case J_ADCONLL: ldm_flush(); /* I do so hope very much that these instructions are used in a */ /* compatible way wrt floating point operands. */ { int32 *w = (int32 *)&p->ic.r3.i64->bin.i; int size = sizeof_longlong / sizeof_long; int32 direction = F_UP, adconop = OP_ADDN; int32 disp = lit_findwordsincurpool(w, size, LIT_INT64_1); if (disp < 0) { disp = lit_findwordsinprevpools(w, size, LIT_INT64_1, codebase+codep+8-1020); if (disp >= 0) { disp = codebase+codep+8-disp; direction = F_DOWN, adconop = OP_SUBN; } else { addressability(256); (void)lit_findword(w[0], LIT_INT64_1, NULL, LITF_INCODE|LITF_FIRST); /* use the second address in case overflow */ disp = lit_findword(w[1], LIT_INT64_2, NULL, LITF_INCODE|LITF_LAST) - 4; } } disp >>= 2; if (direction == F_UP) addfref_(litlab, codep | LABREF_W256); outinstr(adconop | F_RD(r1) | F_RN(R_PC) | disp | 0xf00); break; } case J_CONDEXEC: ldm_flush(); { int32 cond = op & Q_MASK; int32 old_condmask = condition_mask; static bool mipl; if (cond == Q_MI || cond == Q_PL) mipl = YES; else if (cond == Q_AL) mipl = NO; else if (mipl) { if (cond == Q_LT) cond = Q_MI; else if (cond == Q_GE) cond = Q_PL; } /* Here we work round a problem with the peepholer turning (eg) ADD x.. + CMPK x,#0 + CONDEXEC(LT) into ADDS x.. + CONDEXEC(MI) (The problem is that if both arms have been conditionalised, the peepholer won't see the second). This code is vulnerable to improvement in flowgraf's ability to conditionalise, but all is probably well because the real place to do improved conditionalisation is in gen.c instead. */ condition_mask = C_FROMQ(cond) ^ C_ALWAYS; illbits &= ~Q_MASK; peep &= ~P_SWAPPEDOPS; if ((old_condmask ^ (C_FROMQ(Q_AL) ^ C_ALWAYS)) != 0) { /* Could remember the state at the last condexec, and discard */ /* only if it's changed. */ spareregs = 0; KillKnownRegisterValues(AllIntRegs); ipvalue.valid = NO; } break; } case J_B: ldm_flush(); conditional_branch_to(op & Q_MASK, (LabelNumber *)r3, NO, (peep & P_ADJUSTSP) ? r4 : 0); /* only assemble literals after a guaranteed unconditional branch */ if (op==J_B && condition_mask == C_ALWAYS) dumplits2(NO); illbits &= ~Q_MASK; peep &= ~(P_ADJUSTSP|P_SWAPPEDOPS); break; case J_BXX: /* Used with case tables */ ldm_flush(); conditional_branch_to(Q_AL, (LabelNumber *)r3, YES, 0); break; case J_CASEBRANCH: /* N.B. that J_CASEBRANCH can use R_IP as a work register */ ldm_flush(); cmp_integer(r1, r3-2, R_IP, Q_LS, 0); /* -1 for default */ if (codep + 4*r3 >= mustlitby) dumplits2(YES); outinstr(OP_ADDR | C_LS | F_RD(R_PC) | F_RN(R_PC) | r1 | K_LSL(2)); break; case J_LABEL: ldm_flush(); setlabel((LabelNumber *)r3); spareregs = 0; ipvalue.valid = NO; KillKnownRegisterValues(AllIntRegs); break; case J_STACK: fpdesc_newsp(r3); break; case J_LDRBK+J_ALIGN1: ldm_flush(); { bool in_ms_byte = NO; int32 adj = 0; if (target_has_halfword_support && (op & J_SIGNED)) { bigdisp(&dispdesc, r3, 0xff, r2); w = dispdesc.u_d, r3 = dispdesc.m, r2 = dispdesc.r; if (peep & (P_PRE|P_POST)) adjustipvalue(r2, r2, adj = (w & F_UP ? r3 : -r3)); outinstr(prepost_H(op) | F_LDR | w | F_SBYTE | F_RD(r1) | F_RN(r2) | (r3 & 0x0f) | ((r3 & 0xf0) << 4)); if (r2 == R_SP && adj != 0) fpdesc_notespchange(-adj); } else { if ((op & J_SIGNED) && !(peep & (P_PRE|P_POST))) { if (!(config & CONFIG_NO_UNALIGNED_LOADS)) { /* For signed loads, we can use the barrel shifter to rotate the byte we want into the MS byte of the word, saving a shift in propagating the sign, provided that we know that the base is word-aligned. (Unfortunately, the hardware doesn't do the sensible thing on big-endian ARMs, rotating the desired byte into the MS byte only for offsets 0 and 2 mod 4) */ if (BaseIsWordAligned(op, peep)) { if (!target_lsbytefirst) in_ms_byte = (r3 & 1) == 0; else { r3 = (r3 & ~3L) | ((r3+1) & 3L); in_ms_byte = YES; } } } else /* CONFIG_NO_UNALIGNED_LOADS */ if (BaseIsWordAligned(op, peep)) { if ((r3 & 3L) == (target_lsbytefirst ? 3L : 0L)) { in_ms_byte = YES; r3 &= ~3L; } } } bigdisp(&dispdesc, r3, 0xfff, r2); w = dispdesc.u_d, r3 = dispdesc.m, r2 = dispdesc.r; if (peep & (P_PRE|P_POST)) adjustipvalue(r2, r2, adj = (w & F_UP ? r3 : -r3)); outinstr(prepost(op) | F_LDR | w | (in_ms_byte ? F_WORD : F_BYTE) | F_RD(r1) | F_RN(r2) | r3); if (r2 == R_SP && adj != 0) fpdesc_notespchange(-adj); if (op & J_SIGNED) { if (!in_ms_byte) outinstr(OP_MOVR | F_RD(r1) | r1 | K_LSL(24)); if (!(peep & P_MS)) outinstr(OP_MOVR | F_RD(r1) | r1 | K_ASR(24)); } } } regflags = RU_DONT_UPDATE_IP; /* (ip state has already been set) */ peep &= ~(P_BASEALIGNED | P_MS); illbits &= ~(J_SIGNED|J_UNSIGNED); break; case J_LDRBR+J_ALIGN1: ldm_flush(); w = (op & J_NEGINDEX) ? F_DOWN : F_UP; if (target_has_halfword_support && (op & J_SIGNED)) { if (msh) { outinstr(OP_MOVR | F_RD(R_IP) | r3 | msh); r3 = R_IP; DestroyIP(); } outinstr(prepostr_H(op) | F_LDR | w | F_SBYTE | F_RD(r1) | F_RN(r2) | r3); } else { outinstr(prepostr(op) | F_LDR | F_BYTE | w | F_RD(r1) | F_RN(r2) | r3 | msh); if (op & J_SIGNED) { outinstr(OP_MOVR | F_RD(r1) | r1 | K_LSL(24)); if (!(peep & P_MS)) outinstr(OP_MOVR | F_RD(r1) | r1 | K_ASR(24)); } } peep &= ~(P_BASEALIGNED|P_MS|P_RSHIFT); illbits &= ~(J_SIGNED|J_UNSIGNED|J_NEGINDEX|J_SHIFTMASK); break; case J_LDRWK+J_ALIGN2: case J_LDRWK+J_ALIGN1: ldm_flush(); illbits &= ~(J_SIGNED|J_UNSIGNED); /* note that LDRWK with neither J_UNSIGNED nor J_SIGNED is valid and leaves */ /* junk in top 16 bits */ if (target_has_halfword_support && (op & J_ALIGNMENT) == J_ALIGN2) { if (peep & P_MS) syserr(syserr_jop_mode, (long)op, (long)peep); bigdisp(&dispdesc, r3, 0xff, r2); w = dispdesc.u_d, r3 = dispdesc.m, r2 = dispdesc.r; { int32 adj = 0; if (peep & (P_PRE|P_POST)) adjustipvalue(r2, r2, adj = (w & F_UP ? r3 : -r3)); outinstr(prepost_H(op) | F_LDR | w | ((op & J_SIGNED) ? F_SHALF : F_UHALF) | F_RD(r1) | F_RN(r2) | (r3 & 0x0f) | ((r3 & 0xf0) << 4)); if (r2 == R_SP && adj != 0) fpdesc_notespchange(-adj); } regflags = RU_DONT_UPDATE_IP; /* (ip state has already been set) */ } else { bool in_ms_half = !target_lsbytefirst; bool forcetwobytes = NO; int32 offset = r3 & 3L; int32 adj = 0; if ((op & J_ALIGNMENT) == J_ALIGN1) forcetwobytes = !BaseIsWordAligned(op, peep) || offset > 2 || (!target_lsbytefirst && offset == 1); if ((config & CONFIG_NO_UNALIGNED_LOADS) || forcetwobytes) { bool twobytes = YES; if (BaseIsWordAligned(op, peep) && !forcetwobytes) { /* base register of known alignment: we may be able to use normal access code */ if (peep & P_POST) twobytes = NO; else if (peep & P_PRE) twobytes = (r3 & 2L) != 0; else { if (r3 & 2L) in_ms_half = !in_ms_half; r3 &= ~2L; twobytes = NO; } } if (twobytes) { int32 lsbyte, msbyte; int32 p = peep; /* prepost() removes P_PRE, P_POST from peep */ bigdisp(&dispdesc, r3, 0xffe, r2); w = dispdesc.u_d, r3 = dispdesc.m, r2 = dispdesc.r; if (peep & (P_PRE | P_POST)) adjustipvalue(r2, r2, adj = (w & F_UP ? r3 : -r3)); outinstr(prepost(op) | F_LDR | w | F_BYTE | F_RD(r1) | F_RN(r2) | r3); if (r2 == R_SP && adj != 0) fpdesc_notespchange(-adj); if (p & P_PRE) r3 = 1 | F_UP; else if ((p & P_POST) && r3 != 0) { if (w & F_UP) r3 = (r3-1) | F_DOWN; else r3 = (r3+1) | F_UP; } else if (w == F_UP) r3 = (r3 + 1) | w; else r3 = (r3 - 1) | w; outinstr(OP_LDRB | F_RD(R_IP) | F_RN(r2) | r3); if (target_lsbytefirst) lsbyte = r1, msbyte = R_IP; else lsbyte = R_IP, msbyte = r1; if (peep & P_MS) { outinstr(OP_MOVR | F_RD(msbyte) | msbyte | K_LSL(24)); outinstr(OP_ORRR | F_RD(r1) | F_RN(msbyte) | lsbyte | K_LSL(16)); } else if (op & J_SIGNED) { outinstr(OP_MOVR | F_RD(msbyte) | msbyte | K_LSL(24)); outinstr(OP_ORRR | F_RD(r1) | F_RN(lsbyte) | msbyte | K_ASR(16)); } else outinstr(OP_ORRR | F_RD(r1) | F_RN(lsbyte) | msbyte | K_LSL(8)); peep &= ~(P_BASEALIGNED | P_MS); DestroyIP(); break; } } else if (target_lsbytefirst && BaseIsWordAligned(op, peep) && !(peep & (P_PRE|P_POST)) && ((peep & P_MS) || (op & (J_SIGNED | J_UNSIGNED)))) { /* on a little-endian ARM, we can save one shift in zero or sign * extension by addressing the halfword we don't want (provided we * know that the base is word-aligned). */ r3 ^= 2; in_ms_half = YES; } else if (!target_lsbytefirst && BaseIsWordAligned(op, peep) && !(peep & (P_PRE|P_POST)) && !(op & (J_SIGNED | J_UNSIGNED)) && !(peep & P_MS)) { /* for a plain load on a big-endian ARM, we can save a shift by * addressing the halfword we don't want (provided we know that * the base is word-aligned). */ r3 ^= 2; in_ms_half = NO; } bigdisp(&dispdesc, r3, 0xfff, r2); w = dispdesc.u_d, r3 = dispdesc.m, r2 = dispdesc.r; if (peep & (P_PRE | P_POST)) adjustipvalue(r2, r2, adj = (w & F_UP ? r3 : -r3)); /* the following line uses that non-aligned 32 bits loads go via the */ /* ARM barrel shifter. Hence all is OK for aligned 16 bit loads! */ outinstr(prepost(op) | F_LDR | w | F_WORD | F_RD(r1) | F_RN(r2) | r3); if (r2 == R_SP && adj != 0) fpdesc_notespchange(-adj); if (in_ms_half || (op & (J_SIGNED | J_UNSIGNED)) || (peep & P_MS)) { if (!in_ms_half) outinstr(OP_MOVR | F_RD(r1) | r1 | K_LSL(16)); if (!(peep & P_MS)) { if (op & J_SIGNED) outinstr(OP_MOVR | F_RD(r1) | r1 | K_ASR(16)); else outinstr(OP_MOVR | F_RD(r1) | r1 | K_LSR(16)); } } regflags = RU_DONT_UPDATE_IP; /* (ip state has already been set) */ } peep &= ~(P_BASEALIGNED | P_MS); break; case J_LDRWR+J_ALIGN2: ldm_flush(); w = (op & J_NEGINDEX) ? F_DOWN : F_UP; if (target_has_halfword_support) { if (msh) { outinstr(OP_MOVR | F_RD(R_IP) | r3 | msh); r3 = R_IP; DestroyIP(); } outinstr(prepostr_H(op) | F_LDR | w | ((op & J_SIGNED) ? F_SHALF : F_UHALF) | F_RD(r1) | F_RN(r2) | r3); } else if (config & CONFIG_NO_UNALIGNED_LOADS) { int32 lsbyte, msbyte; if (op & J_NEGINDEX) outinstr(OP_SUBR | F_RD(R_IP) | F_RN(r2) | r3 | msh); else outinstr(OP_ADDR | F_RD(R_IP) | F_RN(r2) | r3 | msh); outinstr(OP_LDRB | F_UP | F_RD(r1) | F_RN(R_IP) | 0); outinstr(OP_LDRB | F_UP | F_RD(R_IP) | F_RN(R_IP) | 1); if (target_lsbytefirst) lsbyte = r1, msbyte = R_IP; else lsbyte = R_IP, msbyte = r1; if (op & J_SIGNED) { outinstr(OP_MOVR | F_RD(msbyte) | msbyte | K_LSL(24)); outinstr(OP_ORRR | F_RD(r1) | F_RN(lsbyte) | msbyte | K_ASR(16)); } else outinstr(OP_ORRR | F_RD(r1) | F_RN(lsbyte) | msbyte | K_LSL(8)); DestroyIP(); } else { outinstr(OP_LDRR | w | F_RD(r1) | F_RN(r2) | r3 | msh); if (!target_lsbytefirst || (op & (J_SIGNED | J_UNSIGNED)) || (peep & P_MS)) { if (target_lsbytefirst) outinstr(OP_MOVR | F_RD(r1) | r1 | K_LSL(16)); if (!(peep & P_MS)) { if (op & J_SIGNED) outinstr(OP_MOVR | F_RD(r1) | r1 | K_ASR(16)); else outinstr(OP_MOVR | F_RD(r1) | r1 | K_LSR(16)); } peep &= ~P_MS; } } peep &= ~(P_BASEALIGNED|P_RSHIFT); illbits &= ~(J_SIGNED|J_UNSIGNED|J_NEGINDEX|J_SHIFTMASK); break; case J_STRK+J_ALIGN1: if (BaseIsWordAligned(op, peep) && (r3 & 3) == 0) { peep &= ~P_BASEALIGNED; goto AlignedStore; } { uint32 value = 0x01020304; /* unknown value - all bytes different */ uint32 lastval; uint32 storebits = 0x01010101; int32 shift; RealRegister valreg = r1; int32 inc = 1; if (ValueIsKnown(r1)) value = KnownValue(r1); ldm_flush(); if (!target_lsbytefirst) inc = -1, r3 += 3; lastval = value & 255; /* skip the first LSR */ while (storebits != 0) { for (shift = 0; shift < 32; shift += 8) if (storebits & (1 << shift) && lastval == ((value >> shift) & 255)) break; if (shift == 32) /* didn't find the same value */ { for (shift = 0; !(storebits & (1 << shift)); shift += 8) continue; lastval = (value >> shift) & 255; outinstr(OP_MOVR | F_RD(R_IP) | r1 | K_LSR(shift)); valreg = R_IP; } out_ldr_str(OP_STRB | F_RN(r2) | F_RD(valreg), r3 + inc * (shift >> 3)); storebits ^= 1 << shift; } peep &= ~P_BASEALIGNED; if (valreg == R_IP) DestroyIP(); break; } case J_LDRK+J_ALIGN1: if (r1 == R_A4 || r1 == R_IP) syserr("LDRK unaligned: dest r%ld", (long)r1); if (!BaseIsWordAligned(op, peep)) { bool l_e = target_lsbytefirst; RealRegister w1 = R_A4, w2 = R_IP; ldm_flush(); if (r3 != 0) { add_integer(r1, r2, r3, 0); r2 = r1; } DestroyIP(); KillKnownRegisterValue(R_A1+3); outinstr(OP_LDMIA | F_RN(r2) | regbit(w1) | regbit(w2)); outinstr(OP_ANDN | F_RD(r1) | F_RN(r2) | 3); outinstr(OP_MOVR | F_RD(r1) | r1 | K_LSL(3)); outinstr(OP_MOVR | F_RD(w1) | w1 | (l_e ? R_LSR(r1) : R_LSL(r1))); outinstr(OP_RSBN | F_RD(r1) | F_RN(r1) | 32); outinstr(OP_ORRR | F_RD(r1) | F_RN(w1) | w2 | (l_e ? R_LSL(r1) : R_LSR(r1))); break; } else if ((r3 & 3) != 0) { bool l_e = target_lsbytefirst; int32 w = r3 & ~3; int32 n = r3 & 3; RealRegister w1 = R_A4, w2 = R_IP; /* It's just possible we may be able to peephole the loads here with pending loads from the same base, so we don't generate the LDM directly. */ ldm_c_flush(regbit(w1) | regbit(w2), 0); DestroyIP(); if (r2 == w1) { ldm_outinstr(OP_LDR | F_UP | F_RD(w2) | F_RN(r2) | (w+4), 0); ldm_outinstr(OP_LDR | F_UP | F_RD(w1) | F_RN(r2) | w, dataflow); } else { ldm_outinstr(OP_LDR | F_UP | F_RD(w1) | F_RN(r2) | w, 0); ldm_outinstr(OP_LDR | F_UP | F_RD(w2) | F_RN(r2) | (w+4), dataflow); } ldm_flush(); outinstr(OP_MOVR | F_RD(r1) | w1 | (l_e ? K_LSR(8*n) : K_LSL(8*n))); outinstr(OP_ORRR | F_RD(r1) | F_RN(r1) | w2 | (l_e ? K_LSL(8*(4-n)) : K_LSR(8*(4-n)))); peep &= ~P_BASEALIGNED; break; } /* else fall through to correctly aligned case */ case J_LDRK+J_ALIGN4: case J_STRK+J_ALIGN4: AlignedStore: w = loads_r1(op) ? F_LDR : F_STR; bigdisp(&dispdesc, r3, 0xfff, r2); w |= dispdesc.u_d, r3 = dispdesc.m, r2 = dispdesc.r; /* Only free a to be loaded register if it's not equal to the base register */ { int32 adj = 0; if (peep & (P_PRE | P_POST)) adjustipvalue(r2, r2, adj = (w & F_UP ? r3 : -r3)); ldm_outinstr((prepost(op) | w | F_WORD | F_RD(r1) | F_RN(r2) | r3), dataflow); if (r2 == R_SP && adj != 0) fpdesc_notespchange(-adj); } regflags = RU_NONE | RU_DONT_UPDATE_IP; /* instr is buffered, so don't update register usage */ /* (and ip state has already been set) */ peep &= ~P_BASEALIGNED; break; case J_LDRR+J_ALIGN4: case J_STRR+J_ALIGN4: ldm_flush(); w = loads_r1(op) ? F_LDR : F_STR; w |= (op & J_NEGINDEX) ? F_DOWN : F_UP; outinstr(prepostr(op) | w | F_RD(r1) | F_RN(r2) | r3 | msh); peep &= ~(P_BASEALIGNED|P_RSHIFT); illbits &= ~(J_NEGINDEX|J_SHIFTMASK); break; case J_STRBK+J_ALIGN1: ldm_flush(); bigdisp(&dispdesc, r3, 0xfff, r2); w = dispdesc.u_d, r3 = dispdesc.m, r2 = dispdesc.r; { int32 adj = 0; if (peep & (P_PRE | P_POST)) adjustipvalue(r2, r2, adj = (w & F_UP ? r3 : -r3)); outinstr(prepost(op) | F_STR | F_BYTE | w | F_RD(r1) | F_RN(r2) | r3); if (r2 == R_SP && adj != 0) fpdesc_notespchange(-adj); } regflags = RU_DONT_UPDATE_IP; /* (ip state has already been set) */ peep &= ~P_BASEALIGNED; break; case J_STRBR+J_ALIGN1: ldm_flush(); w = (op & J_NEGINDEX) ? F_DOWN : F_UP; outinstr(prepostr(op) | F_STR | F_BYTE | w | F_RD(r1) | F_RN(r2) | r3 | msh); peep &= ~(P_BASEALIGNED|P_RSHIFT); illbits &= ~(J_NEGINDEX|J_SHIFTMASK); break; /* J_STRW is done by cg.c for the ARM */ case J_STRWK+J_ALIGN1: if (!BaseIsWordAligned(op, peep) || (r3 & 1) != 0) { int32 inc = 1; bool bytesequal = NO; RealRegister ip = R_IP; if (target_lacks_halfword_store) syserr("J_STRW issued with no halfword store"); if (ValueIsKnown(r1)) { int32 value = KnownValue(r1); int32 b0 = value & 0xff, b1 = (value >> 8) & 0xff; if (b0 == b1) bytesequal = YES; /* Expected to be useful really only for 0 / -1 */ } ldm_flush(); if (!target_lsbytefirst) inc = -1, r3 += 1; out_ldr_str(OP_STRB | F_RN(r2) | F_RD(r1), r3); if (bytesequal) ip = r1; else { outinstr(OP_MOVR | F_RD(ip) | r1 | K_LSR(8)); DestroyIP(); } out_ldr_str(OP_STRB | F_RN(r2) | F_RD(ip), r3+inc); peep &= ~P_BASEALIGNED; break; } case J_STRWK+J_ALIGN2: if (target_lacks_halfword_store) syserr("J_STRW issued with no halfword store"); ldm_flush(); bigdisp(&dispdesc, r3, 0xff, r2); w = dispdesc.u_d, r3 = dispdesc.m, r2 = dispdesc.r; { int32 adj = 0; if (peep & (P_PRE | P_POST)) adjustipvalue(r2, r2, adj = (w & F_UP ? r3 : -r3)); outinstr(prepost_H(op) | F_STR | w | F_UHALF | F_RD(r1) | F_RN(r2) | (r3 & 0x0f) | ((r3 & 0xf0) << 4)); if (r2 == R_SP && adj != 0) fpdesc_notespchange(-adj); } peep &= ~P_BASEALIGNED; break; case J_STRWR+J_ALIGN2: if (target_lacks_halfword_store) syserr("J_STRW issued with no halfword store"); ldm_flush(); w = (op & J_NEGINDEX) ? F_DOWN : F_UP; if (msh) { outinstr(OP_MOVR | F_RD(R_IP) | r3 | msh); r3 = R_IP; DestroyIP(); } outinstr(prepostr_H(op) | F_STR | w | F_UHALF | F_RD(r1) | F_RN(r2) | r3); peep &= ~(P_BASEALIGNED|P_RSHIFT); illbits &= ~(J_NEGINDEX|J_SHIFTMASK); break; case J_ENDPROC: ldm_flush(); if (!lab_isset_(returnlab) && returnlab->u.frefs != NULL) /* at least one pending ref */ conditional_branch_to(Q_AL, RETLAB, NO, 0); dumplits2(NO); /* to ensure that all literals for a proc get put out */ dump_count_names(); fpdesc_endproc(); /* Fill in argument binders with offsets which can be used to access the * arguments in a containing procedure from a base of 'local 0'. The need * to do something like this is target-independent, but what exactly needs * doing is of course strongly target-dependent. * (Not used in C or C++, of course) */ { BindList *b; /* /* work to be done here for NOFP */ for (b = argument_bindlist; b != NULL; b = b->bindlistcdr) { Binder *v = b->bindlistcar; int32 p = bindaddr_(v) & ~BINDADDR_MASK; if (p >= 4*argwordsbelowfp) p += 4 * bitcount(regmask & M_VARREGS) + 16; p += 12*bitcount(regmask & M_FVARREGS); bindaddr_(v) = (bindaddr_(v) & BINDADDR_MASK) | p; } } break; case J_ENTER: routine_entry(r3); #ifdef TARGET_HAS_SAVE break; case J_SAVE: #endif routine_saveregs(r3); break; /* J_PUSHR should never reach armgen (removed in flowgraf) */ case J_PUSHM: ldm_flush(); { int32 count = 4 * bitcount(r3); out_ldm_instr(OP_STMFD | F_WRITEBACK | F_RN(R_SP) | r3); fpdesc_notespchange(count); adjustipvalue(R_SP, R_SP, -count); } break; case J_POPMB: /* version of POP with a specified base */ ldm_flush(); { int32 ldmop = OP_LDMDB; int32 count = 4 * bitcount(r3); if (peep & P_PRE) { add_integer(r2, r2, r1-count, 0); r1 = count; peep &= ~P_PRE; } if (r1 != 0) { if (count == r1) ldmop = OP_LDMIA; else { int32 r = power_of_two(r3 & (-r3)); add_integer(r, r2, r1, 0); r2 = r; } } out_ldm_instr(ldmop | F_RN(r2) | r3); spareregs &= ~r3; KillKnownRegisterValues(r3); } break; #ifdef ARM_INLINE_ASSEMBLER case J_LDM: case J_LDMW: case J_STM: case J_STMW: { uint32 ldmop = 0; switch (flags & MM_TYPE) { case MM_IA: ldmop = OP_LDMIA; break; case MM_IB: ldmop = OP_LDMIB; break; case MM_DA: ldmop = OP_LDMDA; break; case MM_DB: ldmop = OP_LDMDB; break; } if (op == J_STM || op == J_STMW) ldmop -= OP_LDMIA - OP_STMIA; else KillKnownRegisterValues(r3); if (op == J_STMW || op == J_LDMW) ldmop += F_WRITEBACK; if (flags & SET_CC) ldmop += F_PSR; ldm_flush(); out_ldm_instr(ldmop | F_RN(r1) | r3); peep &= ~(P_SETCC | P_CMPZ); break; } case J_CDP: outinstr(OP_CDP | r4); break; case J_MRC: outinstr(OP_MRC | r4 | F_RD(r1)); break; case J_MCR: outinstr(OP_MCR | r4 | F_RD(r1)); break; case J_LDC: case J_LDCW: case J_STC: case J_STCW: { uint32 op = OP_LDC | F_UP; if (OPCODE(flags) == A_STC) op = OP_STC | F_UP; if (r3 < 0) r3 = -r3, op ^= F_UP; if (flags & M_LONG) op |= F_LONG; if (flags & M_WB) op |= F_WB; if (flags & M_PREIDX) op |= F_PRE; outinstr(op | F_RN(r2) | r3 | r4); } break; #endif case J_USE: case J_VSTORE: ldm_flush(); case J_USEF: case J_USED: break; case J_INLINE1: syserr(syserr_inline1); break; case J_CLRC+J_ALIGN4: case J_MOVC+J_ALIGN4: case J_PUSHC+J_ALIGN4: ldm_flush(); { RealRegister loopreg = NoRegister; int32 regs; unsigned rcount; unsigned count = (unsigned)r3 / 4; bool useloop = r3 > MOVC_LOOP_THRESHOLD; /* That is, we are prepared to compile 3 load+store pairs. This number is also used in regalloc (for number of registers believed corrupted) and flowgraf (for conditionalisability). Later, we may revise our ideas about whether a loop is indicated. */ J_OPCODE baseop = op & J_TABLE_BITS; int32 ldm, stm; bool ismove = (baseop != J_CLRC); p->ic.r4.i |= spareregs; regs = movc_workregs(p); rcount = bitcount(regs); if (baseop == J_PUSHC) ldm = OP_LDMDB | F_WRITEBACK, stm = OP_STMDB | F_WRITEBACK; else if (peep & P_POST) ldm = OP_LDMIA | F_WRITEBACK, stm = OP_STMIA; else ldm = OP_LDMIA, stm = OP_STMIA; if (useloop) { if ( (ismove && count <= 3*rcount) || (count <= 4*rcount)) useloop = NO; else { /* We really do want to compile a loop - we will need a register for the count. We take an arbitrary register from the work registers. */ uint32 rbit = regs & -regs; rcount--; loopreg = logbase2(rbit); regs ^= rbit; KillKnownRegisterValues(rbit); } } { /* Remove unneeded registers if the register count either exeeds ldm_regs_max or rcount. Update the register set used by this function. */ int i, num_instr; if (count < ldm_regs_max) i = rcount - count; else i = rcount - ldm_regs_max; if (i > 0) { rcount -= i; regs = LSBits(regs, rcount); } regmask |= regs; KillKnownRegisterValues(regs); /* Count the number of instructions required to be sure we dump the literal pool before it overflows. A loop takes 4 instr max, plus max 3 for loading the loop counter No loop: max 3*2 or 4*1 instr. CLRC needs an additional rcount instr to initialize the registers to zero. Thus 7 for MOVC & PUSHC, rcount+6 for CLRC. */ num_instr = ismove ? 7 : rcount + 6; if (codep + 4*num_instr >= mustlitby) dumplits2(YES); } if (!ismove) { int32 i = R_A1; for (; i <= R_LR; i++) if (regs & regbit(i)) load_integer(i, 0, 0); } if (!useloop) for (; count > rcount; count -= rcount) { if (ismove && count == rcount+1 && rcount < ldm_regs_max && (dataflow & J_DEAD_R2) && !(peep & P_POST)) { rcount++; regs |= regbit(r2); ldm &= ~F_WRITEBACK; break; } if (ismove) out_ldm_instr(ldm | F_WRITEBACK | F_RN(r2) | regs); out_ldm_instr(stm | F_WRITEBACK | F_RN(r1) | regs); } else { LabelNumber *lab = nextlabel(); unsigned n = count / rcount; count = count % rcount; load_integer(loopreg, n, 0); setlabel(lab); if (ismove) out_ldm_instr(ldm | F_WRITEBACK | F_RN(r2) | regs); out_ldm_instr(stm | F_WRITEBACK | F_RN(r1) | regs); add_integer(loopreg, loopreg, -1, P_CMPZ); conditional_branch_to(Q_NE, lab, NO, 0); } if (count > 0) { regs = LSBits(regs, count); if (ismove) outinstr(ldm | F_RN(r2) | regs); outinstr(stm | F_RN(r1) | regs); } } peep &= ~(P_POST); break; case J_CMPFK: case J_CMPDK: case J_CMPFR: case J_CMPDR: ldm_c_flush(regs_used(&regusage), 1); fp_gen->show(p); illbits = peep = 0; /* already checked in show_fp */ break; #ifdef RANGECHECK_SUPPORTED case J_CHKNEFR: case J_CHKNEDR: ldm_flush(); fp_gen->show(p); illbits = peep = 0; /* already checked in show_fp */ break; #endif #ifdef TARGET_HAS_DATA_VTABLES case J_WORD_ADCON: obj_symref((Symstr *)r3, xr_code, 0); AddCodeXref4(X_absreloc | codebase+codep, (Symstr *)r3, 0); outcodeword(0, LIT_ADCON); break; case J_WORD_LABEL: addfref_((LabelNumber *)r3, codep | LABREF_WORD32); outcodeword(0, LIT_ADCON); break; #endif case J_TYPECASE: break; default: ldm_c_flush(regs_used(&regusage), 0); fp_gen->show(p); illbits = peep = 0; /* already checked in show_fp */ break; } if (localcg_debug(4)) cc_msg(" use %4lx def %4lx corrupt %4lx spare %4lx", (long)regusage.use, (long)regusage.def, (long)regusage.corrupt, (long)spareregs); UpdateRegisters(&regusage, regflags); if (localcg_debug(4)) cc_msg(" -> spare %4lx\n", (long)spareregs); #ifdef PARANOID_CONSISTENCY_CHECK { /* Consistency check on spareregs: kill the values in all free regs... */ /* BEWARE: For debugging purposes only as it affects code quality... */ if (spareregs != 0 && ((op & J_TABLE_BITS) != J_CASEBRANCH) && ((op & J_TABLE_BITS) != J_BXX)) out_ldm_instr (OP_LDMIA | F_RN(R_PC) | spareregs); } #endif if (illbits | peep) syserr(syserr_jop_mode, (long)op, (long)peep); } static Uint saved_fpreg_words; static Uint fp_arg_words; #define NFPLITERALS 16 typedef struct { FloatCon *val; int32 immop; } FPLiteral; static FPLiteral fpliterals[NFPLITERALS] = { {NULL, 0 | F_CONSTOP}, {NULL, 1 | F_CONSTOP}, {NULL, 2 | F_CONSTOP}, {NULL, 3 | F_CONSTOP}, {NULL, 4 | F_CONSTOP}, {NULL, 5 | F_CONSTOP}, {NULL, 6 | F_CONSTOP}, {NULL, 7 | F_CONSTOP}, {NULL, 0 | F_CONSTOP}, {NULL, 1 | F_CONSTOP}, {NULL, 2 | F_CONSTOP}, {NULL, 3 | F_CONSTOP}, {NULL, 4 | F_CONSTOP}, {NULL, 5 | F_CONSTOP}, {NULL, 6 | F_CONSTOP}, {NULL, 7 | F_CONSTOP} }; static int32 posfpliteral(FloatCon const *val) { int i; if (fpu_type == fpu_fpa) for ( i = 0 ; i != NFPLITERALS ; i++ ) if (fpliterals[i].val->floatlen == (val->floatlen & TYPEDEFINHIBITORS) && fpliterals[i].val->floatbin.irep[0] == val->floatbin.irep[0] && ( (val->floatlen & bitoftype_(s_short)) || fpliterals[i].val->floatbin.irep[1] == val->floatbin.irep[1])) return fpliterals[i].immop; return 0; } static int32 negfpliteral(FloatCon const *val) { int i; if (fpu_type == fpu_fpa) for ( i = 0 ; i != NFPLITERALS ; i++ ) if (fpliterals[i].val->floatlen == (val->floatlen & TYPEDEFINHIBITORS) && (fpliterals[i].val->floatbin.irep[0] ^ 0x80000000) == (uint32)val->floatbin.irep[0] && ( (val->floatlen & bitoftype_(s_short)) || fpliterals[i].val->floatbin.irep[1] == val->floatbin.irep[1])) return fpliterals[i].immop; return 0; } bool fpliteral(FloatCon const *val, J_OPCODE op) { int32 n = posfpliteral(val); if ( n != 0 && /* disgusting bodge to ensure we can't fall foul of FPE bug - MULxK x, x, #0.0 non-functional This case should never arise, anyhow */ !(n == F_CONSTOP && (op == J_MULFK || op == J_MULDK))) return YES; /* -ve cases also valid for ADDxK/SUBxK */ if ((op == J_ADDFK || op == J_SUBFK || op == J_ADDDK || op == J_SUBDK) && negfpliteral(val)) return YES; return NO; } static int32 checkfreg(RealRegister r) { if (r < R_F0) /* already checked to be <= R_F7 */ syserr(syserr_gen_freg, (long)r); return r & 0xf; } static void fpa_show(const PendingOp *p) { struct DispDesc dispdesc; J_OPCODE op = p->ic.op; RealRegister r1 = p->ic.r1.i, r2 = p->ic.r2.i, r3 = p->ic.r3.i; int peep = p->peep; int32 w, illbits; illbits = op & (Q_MASK | J_SIGNED | J_UNSIGNED | J_NEGINDEX | J_SHIFTMASK); switch (op & ~(Q_MASK | J_SIGNED | J_UNSIGNED | J_NEGINDEX | J_SHIFTMASK)) { /* Now the floating point part of the instruction set */ /* This is a version for FPE2 */ #define cpprepost(op) \ ((peep & P_POST) ? (peep &= ~P_POST, OP_CPPOST | F_WRITEBACK) : \ (peep & P_PRE) ? (peep &= ~P_PRE, OP_CPPRE | F_WRITEBACK) : OP_CPPRE) case J_PUSHD: { ldm_flush(); outinstr(OP_CPPRE | F_DOWN | F_WRITEBACK | F_STR | F_RN(R_SP) | F_RD(checkfreg(r1)) | F_DOUBLE | 2); adjustipvalue(R_SP, R_SP, -8); } break; case J_PUSHF: { ldm_flush(); outinstr(OP_CPPRE | F_DOWN | F_WRITEBACK | F_STR | F_RN(R_SP) | F_RD(checkfreg(r1)) | F_SINGLE | 1); adjustipvalue(R_SP, R_SP, -4); } break; case J_MOVFK: case J_MOVDK: /* load single & double literals the same way */ { int32 imm = posfpliteral((FloatCon *) r3); if (imm != 0) { outinstr(OP_CPOP | F_MVF | CPDO_FLTOFJ(op) | F_RD(checkfreg(r1)) | imm); break; } if ((imm = negfpliteral((FloatCon *) r3)) != 0) { outinstr(OP_CPOP | F_MNF | CPDO_FLTOFJ(op) | F_RD(checkfreg(r1)) | imm); break; } } /* Otherwise, drop through to create a FP literal */ case J_ADCONF: case J_ADCOND: ldm_flush(); /* I do so hope very much that these instructions are used in a */ /* compatible way wrt floating point operands. */ { FloatCon *fc = (FloatCon *)r3; int size = (op==J_MOVDK || op==J_ADCOND) ? 2 : 1; int32 direction = F_UP, adconop = OP_ADDN; int32 disp = lit_findwordsincurpool(fc->floatbin.irep, size, LIT_FPNUM); if (disp < 0) { disp = lit_findwordsinprevpools(fc->floatbin.irep, size, LIT_FPNUM, codebase+codep+8-1020); if (disp >= 0) { disp = codebase+codep+8-disp; direction = F_DOWN, adconop = OP_SUBN; } else { addressability(256); if (size == 1) disp = lit_findwordaux(fc->floatbin.fb.val, LIT_FPNUM, fc->floatstr, LITF_INCODE|LITF_FIRST|LITF_LAST); else { (void)lit_findwordaux(fc->floatbin.db.msd, LIT_FPNUM1, fc->floatstr, LITF_INCODE|LITF_FIRST); /* use the second address in case overflow */ disp = lit_findwordaux(fc->floatbin.db.lsd, LIT_FPNUM2, fc->floatstr, LITF_INCODE|LITF_LAST) - 4; } } } disp >>= 2; if (direction == F_UP) addfref_(litlab, codep | LABREF_W256); if (op == J_ADCONF || op==J_ADCOND) outinstr(adconop | F_RD(r1) | F_RN(R_PC) | disp | 0xf00); else outinstr(OP_CPPRE | F_LDR | CPDT_FLTOFJ(op) | direction | F_RD(checkfreg(r1)) | F_RN(R_PC) | disp); break; } case J_CMPFR: case J_CMPDR: /* Note that in FPE2 it is not necessary to specify the width of */ /* numbers to be compared. */ { int32 test = op & Q_MASK; outinstr(OP_CPOP | ((test==Q_EQ || test==Q_NE) ? F_CMF : F_CMFE) | F_REGOP | F_RN(checkfreg(r2)) | (checkfreg(r3))); } illbits &= ~Q_MASK; break; case J_MOVFDR: /* With FPE2 conversion to double is a noop */ /* drop through */ case J_MOVFR: case J_MOVDR: if (r1==r3) syserr(syserr_remove_fp_noop); outinstr(OP_CPOP | F_MVF | F_REGOP | CPDO_FLTOFJ(op) | F_RD(checkfreg(r1)) | (checkfreg(r3))); break; case J_NEGFR: case J_NEGDR: outinstr(OP_CPOP | F_MNF | F_REGOP | CPDO_FLTOFJ(op) | F_RD(checkfreg(r1)) | (checkfreg(r3))); break; case J_FIXDRM: case J_FIXFRM: /* signed fix towards minus infinity */ outinstr(OP_CPOP | F_FIX | CPDO_SINGLE | CPDO_RNDDN | F_RD(r1) | checkfreg(r3)); illbits ^= J_SIGNED; break; case J_FIXFR: case J_FIXDR: /* C signed 'fix' is truncate towards zero */ outinstr(OP_CPOP | F_FIX | CPDO_SINGLE | CPDO_RNDZ | F_RD(r1) | checkfreg(r3)); illbits ^= J_SIGNED; break; case J_FLTFR: case J_FLTDR: outinstr(OP_CPOP | F_FLT | CPDO_FLTOFJ(op) | F_RD(r3) | F_RN(checkfreg(r1))); illbits ^= J_SIGNED; /* only signed version acceptable */ break; case J_MOVIFR: /* Load FP register from an integer one */ { out_ldm_instr(OP_STMFD | F_WRITEBACK | F_RN(R_SP) | regbit(r3)); outinstr(OP_CPPOST | F_UP | F_LDR | F_WRITEBACK | F_RN(R_SP) | F_RD(checkfreg(r1)) | F_SINGLE | 1); } break; case J_MOVFIR: /* Load integer register from fp register */ { ldm_flush(); outinstr(OP_CPPRE | F_DOWN | F_STR | F_WRITEBACK | F_RN(R_SP) | F_RD(checkfreg(r3)) | F_SINGLE | 1); out_ldm_instr(OP_LDMFD | F_WRITEBACK | F_RN(R_SP) | regbit(r1)); } break; case J_MOVDIR: /* Load integer register pair from fp register */ { ldm_flush(); if (r2 <= r1) syserr(syserr_bad_regpair); outinstr(OP_CPPRE | F_DOWN | F_STR | F_WRITEBACK | F_RN(R_SP) | F_RD(checkfreg(r3)) | F_DOUBLE | 2); outinstr(OP_LDMFD | F_WRITEBACK | F_RN(R_SP) | regbit(r1) | regbit(r2)); } break; case J_MOVIDM: /* Load n FP registers from 2n integer registers. r3 holds a bitmap of */ /* integer registers, r1 a bitmap of the fp registers. */ { int32 r; ldm_flush(); out_ldm_instr(OP_STMFD | F_WRITEBACK | F_RN(R_SP) | r3); for (r = R_F0; r1 != 0; r++) if (r1 & regbit(r)) { outinstr(OP_CPPOST | F_UP | F_LDR | F_WRITEBACK | F_RN(R_SP) | F_RD(checkfreg(r)) | F_DOUBLE | 2); r1 ^= regbit(r); } } break; case J_MOVDIM: /* Load 2n integer registers from n FP registers. r3 holds a bitmap of */ /* fp registers, r1 a bitmap of the integer registers. There may be more */ /* than 2n registers in the r1 map because unconnected individual */ /* pops (of an object split between registers and stack) may have been */ /* added. */ { int32 r; int32 netpush = 2 * bitcount(r3) - bitcount(r1); ldm_flush(); for (r = R_F0+NFLTREGS-1; r3 != 0; r--) if (r3 & regbit(r)) { outinstr(OP_CPPRE | F_DOWN | F_STR | F_WRITEBACK | F_RN(R_SP) | F_RD(checkfreg(r)) | F_DOUBLE | 2); r3 ^= regbit(r); } out_ldm_instr(OP_LDMFD | F_WRITEBACK | F_RN(R_SP) | r1); adjustipvalue(R_SP, R_SP, -netpush); KillKnownRegisterValues(r1); } break; case J_MOVIDR: /* Load FP register from 2 integer registers. Only happens just after */ /* function entry, with the integer registers being argument rgisters. */ /* If arguments have been pushed on the stack, we can load the fp value */ /* directly. (It would be nice to ensure that if anything had been */ /* pushed on entry, the argument registers of the MOVIDR had). */ { ldm_flush(); if (r3 <= r2) syserr(syserr_bad_regpair); if (!(procflags & PROC_ARGPUSH)) { out_ldm_instr(OP_STMFD | F_WRITEBACK | F_RN(R_SP) | regbit(r3) | regbit(r2)); outinstr(OP_CPPOST | F_UP | F_LDR | F_WRITEBACK | F_RN(R_SP) | F_RD(checkfreg(r1)) | F_DOUBLE | 2); break; } { int32 addr = BINDADDR_ARG + r2*4; op = J_LDRDK; r3 = local_addr_a(addr); r2 = local_base_a(addr); /* and fall through to handle the load */ } } case J_LDRFK+J_ALIGN4: case J_LDRDK+J_ALIGN4: case J_LDRDK+J_ALIGN8: case J_STRFK+J_ALIGN4: case J_STRDK+J_ALIGN4: case J_STRDK+J_ALIGN8: ldm_flush(); w = loads_r1(op) ? F_LDR : F_STR; bigdisp(&dispdesc, r3, 0x3fc, r2); w |= dispdesc.u_d, r3 = dispdesc.m, r2 = dispdesc.r; outinstr(cpprepost(op) | w | CPDT_FLTOFJ(op) | F_RD(checkfreg(r1)) | F_RN(r2) | (r3>>2)); if (r2 == R_SP && (op & F_WRITEBACK)) fpdesc_notespchange(dispdesc.u_d == F_DOWN ? r3 : -r3); peep &= ~P_BASEALIGNED; break; case J_MOVDFR: /* Round from double to single precision */ /* I guess I hope this gives exponent overflow if necessary */ outinstr(OP_CPOP | F_MVF | F_REGOP | CPDO_SINGLE | F_RD(checkfreg(r1)) | (checkfreg(r3))); break; case J_ADDFR: case J_ADDDR: outinstr(OP_CPOP | F_ADF | F_REGOP | CPDO_FLTOFJ(op) | F_RD(checkfreg(r1)) | F_RN(checkfreg(r2)) | (checkfreg(r3))); break; case J_SUBFR: case J_SUBDR: outinstr(OP_CPOP | F_SUF | F_REGOP | CPDO_FLTOFJ(op) | F_RD(checkfreg(r1)) | F_RN(checkfreg(r2)) | (checkfreg(r3))); break; case J_RSBFR: case J_RSBDR: outinstr(OP_CPOP | F_RSF | F_REGOP | CPDO_FLTOFJ(op) | F_RD(checkfreg(r1)) | F_RN(checkfreg(r2)) | (checkfreg(r3))); break; case J_MULFR: case J_MULDR: outinstr(OP_CPOP | F_MUF | F_REGOP | CPDO_FLTOFJ(op) | F_RD(checkfreg(r1)) | F_RN(checkfreg(r2)) | (checkfreg(r3))); break; case J_DIVFR: case J_DIVDR: outinstr(OP_CPOP | F_DVF | F_REGOP | CPDO_FLTOFJ(op) | F_RD(checkfreg(r1)) | F_RN(checkfreg(r2)) | (checkfreg(r3))); break; case J_RDVFR: case J_RDVDR: outinstr(OP_CPOP | F_RDF | F_REGOP | CPDO_FLTOFJ(op) | F_RD(checkfreg(r1)) | F_RN(checkfreg(r2)) | (checkfreg(r3))); break; case J_ADDFK: case J_ADDDK: { FloatCon *f = (FloatCon *) r3; int32 imm = posfpliteral(f); if (imm != 0) outinstr(OP_CPOP | F_ADF | CPDO_FLTOFJ(op) | F_RD(checkfreg(r1)) | F_RN(checkfreg(r2)) | imm); else if ((imm = negfpliteral(f)) != 0) outinstr(OP_CPOP | F_SUF | CPDO_FLTOFJ(op) | F_RD(checkfreg(r1)) | F_RN(checkfreg(r2)) | imm); else syserr(syserr_fp_const, f->floatbin.irep[0]); break; } case J_SUBFK: case J_SUBDK: { FloatCon *f = (FloatCon *) r3; int32 imm = posfpliteral(f); if (imm != 0) outinstr(OP_CPOP | F_SUF | CPDO_FLTOFJ(op) | F_RD(checkfreg(r1)) | F_RN(checkfreg(r2)) | imm); else if ((imm = negfpliteral(f)) != 0) outinstr(OP_CPOP | F_ADF | CPDO_FLTOFJ(op) | F_RD(checkfreg(r1)) | F_RN(checkfreg(r2)) | imm); else syserr(syserr_fp_const, f->floatbin.irep[0]); break; } case J_RSBFK: case J_RSBDK: outinstr(OP_CPOP | F_RSF | CPDO_FLTOFJ(op) | F_RD(checkfreg(r1)) | F_RN(checkfreg(r2)) | posfpliteral((FloatCon *) r3)); break; case J_MULDK: case J_MULFK: outinstr(OP_CPOP | F_MUF | CPDO_FLTOFJ(op) | F_RD(checkfreg(r1)) | F_RN(checkfreg(r2)) | posfpliteral((FloatCon *) r3)); break; case J_DIVFK: case J_DIVDK: outinstr(OP_CPOP | F_DVF | CPDO_FLTOFJ(op) | F_RD(checkfreg(r1)) | F_RN(checkfreg(r2)) | posfpliteral((FloatCon *) r3)); break; case J_RDVFK: case J_RDVDK: outinstr(OP_CPOP | F_RDF | CPDO_FLTOFJ(op) | F_RD(checkfreg(r1)) | F_RN(checkfreg(r2)) | posfpliteral((FloatCon *) r3)); break; case J_CMPFK: case J_CMPDK: { int32 test = op & Q_MASK; outinstr(OP_CPOP | ((test==Q_EQ || test==Q_NE) ? F_CMF : F_CMFE) | F_RN(checkfreg(r2)) | posfpliteral((FloatCon *) r3)); } illbits &= ~Q_MASK; break; case J_INLINE1F: case J_INLINE1D: outinstr(r3 | F_RD(checkfreg(r1)) | (checkfreg(r2))); break; #ifdef RANGECHECK_SUPPORTED case J_CHKNEFR: case J_CHKNEDR: outinstr(OP_CPOP | F_CMF | F_REGOP | F_RN(checkfreg(r2)) | (checkfreg(r3))); outinstr3(OP_BL ^ Q_EQ, sim.valfault, 0); break; #endif default: syserr(syserr_show_inst_dir, (long)op); illbits = 0; break; } if (illbits | peep) syserr(syserr_jop_mode, (long)op, (long)peep); #undef cpprepost } static int32 amp_checkfreg(RealRegister r) { if (r < R_F0) /* already checked to be <= R_F7 */ syserr(syserr_gen_freg, (long)r); return r - R_F0 + AMP_F0; } static void amp_show(const PendingOp *p) { struct DispDesc dispdesc; J_OPCODE op = p->ic.op; RealRegister r1 = p->ic.r1.i, r2 = p->ic.r2.i, r3 = p->ic.r3.i; int peep = p->peep; int32 w, illbits; illbits = op & (Q_MASK | J_SIGNED | J_UNSIGNED | J_NEGINDEX | J_SHIFTMASK); switch (op & ~(Q_MASK | J_SIGNED | J_UNSIGNED | J_NEGINDEX | J_SHIFTMASK)) { /* Now the floating point part of the instruction set */ #define cpprepost(w) \ ((peep & P_POST) ? (peep &= ~P_POST, w | CPDT_POST) : \ (peep & P_PRE) ? (peep &= ~P_PRE, w | CPDT_PRE | CPDT_WB) : w | CPDT_PRE) case J_PUSHF: ldm_flush(); outinstr(AMP_DT(CPDT_PRE | CPDT_DOWN | CPDT_WB | CPDT_ST, R_SP, amp_checkfreg(r1), 4)); adjustipvalue(R_SP, R_SP, -4); break; case J_MOVFK: case J_ADCONF: case J_ADCOND: /* Although AMP supports only single-precision floating point, ADCONDs */ /* can still arise (via software floating point) from use of doubles. */ /* (but MOVDKs can't) */ ldm_flush(); { FloatCon *fc = (FloatCon *)r3; int size = (op==J_ADCOND) ? 2 : 1; int32 direction = CPDT_UP, adconop = OP_ADDN; int32 disp = lit_findwordsincurpool(fc->floatbin.irep, size, LIT_FPNUM); if (disp < 0) { disp = lit_findwordsinprevpools(fc->floatbin.irep, size, LIT_FPNUM, codebase+codep+8-1020); if (disp >= 0) { disp = codebase+codep+8-disp; direction = CPDT_DOWN, adconop = OP_SUBN; } else { addressability(256); if (size == 1) disp = lit_findwordaux(fc->floatbin.fb.val, LIT_FPNUM, fc->floatstr, LITF_INCODE|LITF_FIRST|LITF_LAST); else { (void)lit_findwordaux(fc->floatbin.db.msd, LIT_FPNUM1, fc->floatstr, LITF_INCODE|LITF_FIRST); /* use the second address in case overflow */ disp = lit_findwordaux(fc->floatbin.db.lsd, LIT_FPNUM2, fc->floatstr, LITF_INCODE|LITF_LAST) - 4; } } } if (direction == CPDT_UP) addfref_(litlab, codep | LABREF_W256); if (op == J_ADCONF || op==J_ADCOND) outinstr(adconop | F_RD(r1) | F_RN(R_PC) | (disp >> 2) | 0xf00); else outinstr(AMP_DT(CPDT_LD | CPDT_PRE | direction, R_PC, amp_checkfreg(r1), disp)); break; } case J_CMPFR: /* Note that in FPE2 it is not necessary to specify the width of */ /* numbers to be compared. */ { int32 test = op & Q_MASK; int32 fop = test==Q_EQ || test==Q_NE ? AMP_FCMPEQ : test==Q_LT || test==Q_GE ? AMP_FCMPLT : AMP_FCMPLE; outinstr(AMP_TCM_EXU(fop, AMP_WorkReg, amp_checkfreg(r2), amp_checkfreg(r3))); outinstr(AMP_MRC(MCR_32, R_IP, AMP_WorkReg)); outinstr(OP_RSBN | F_SCC | F_RD(R_IP) | F_RN(R_IP) | (test==Q_LT || test==Q_GE ? 0 : 1)); DestroyIP(); } illbits &= ~Q_MASK; break; case J_MOVFR: if (r1==r3) syserr(syserr_remove_fp_noop); outinstr(AMP_TCM_EXU(AMP_FMAX, amp_checkfreg(r1), amp_checkfreg(r3), amp_checkfreg(r3))); break; case J_NEGFR: outinstr(AMP_TCM_EXU(AMP_FSUB, amp_checkfreg(r1), AMP_ZeroReg, amp_checkfreg(r3))); break; case J_FIXFR: case J_FIXFRM: outinstr(AMP_TCM_MBU(AMP_MFCSR, AMP_WorkReg, 0, AMP_FPCR)); outinstr(AMP_MRC(MCR_32, R_IP, AMP_WorkReg)); and_integer(r1, R_IP, ~AMP_FPCR_RND, 0, NO); orr_integer(r1, r1, (op & J_TABLE_BITS == J_FIXFR ? AMP_FPCR_RND_Z : AMP_FPCR_RND_D), 0); outinstr(AMP_MCR(MCR_32, r1, AMP_WorkReg)); outinstr(AMP_TCM_MBU(AMP_MTCSR, 0, AMP_WorkReg, AMP_FPCR)); outinstr(AMP_TCM_EXU(AMP_FCVTFI, AMP_WorkReg, amp_checkfreg(r3), AMP_ZeroReg)); outinstr(AMP_MRC(MCR_32, r1, AMP_WorkReg)); outinstr(AMP_MCR(MCR_32, R_IP, AMP_WorkReg)); outinstr(AMP_TCM_MBU(AMP_MTCSR, 0, AMP_WorkReg, AMP_FPCR)); illbits ^= J_SIGNED; /* only signed version acceptable */ break; case J_FLTFR: outinstr(AMP_MCR(MCR_32, r3, AMP_WorkReg)); outinstr(AMP_TCM_EXU(AMP_FCVTIF, amp_checkfreg(r1), AMP_WorkReg, AMP_ZeroReg)); illbits ^= J_SIGNED; /* only signed version acceptable */ break; case J_MOVIFR: /* Load FP register from an integer one */ outinstr(AMP_MCR(MCR_32, r3, amp_checkfreg(r1))); break; case J_MOVFIR: /* Load integer register from fp one */ outinstr(AMP_MRC(MCR_32, r1, amp_checkfreg(r3))); break; case J_LDRFK+J_ALIGN4: case J_STRFK+J_ALIGN4: ldm_flush(); w = loads_r1(op) ? CPDT_LD : CPDT_ST; bigdisp(&dispdesc, r3, 0x3fc, r2); w |= dispdesc.u_d, r3 = dispdesc.m, r2 = dispdesc.r; outinstr(AMP_DT(cpprepost(w), r2, amp_checkfreg(r1), r3)); if (r2 == R_SP && (op & F_WRITEBACK)) fpdesc_notespchange(dispdesc.u_d == F_DOWN ? r3 : -r3); peep &= ~P_BASEALIGNED; break; case J_ADDFR: outinstr(AMP_TCM_EXU(AMP_FADD, amp_checkfreg(r1), amp_checkfreg(r2), amp_checkfreg(r3))); break; case J_SUBFR: outinstr(AMP_TCM_EXU(AMP_FSUB, amp_checkfreg(r1), amp_checkfreg(r2), amp_checkfreg(r3))); break; case J_RSBFR: outinstr(AMP_TCM_EXU(AMP_FSUB, amp_checkfreg(r1), amp_checkfreg(r3), amp_checkfreg(r2))); break; case J_MULFR: outinstr(AMP_TCM_EXU(AMP_FMUL0, amp_checkfreg(r1), amp_checkfreg(r2), amp_checkfreg(r3))); break; case J_DIVFR: outinstr(AMP_TCM_EXU(AMP_FDIV, 0, amp_checkfreg(r2), amp_checkfreg(r3))); outinstr(AMP_TCM_EXU(AMP_FMFQ, amp_checkfreg(r1), 0, 0)); break; case J_RDVFR: outinstr(AMP_TCM_EXU(AMP_FMUL0, 0, amp_checkfreg(r3), amp_checkfreg(r2))); outinstr(AMP_TCM_EXU(AMP_FMFQ, amp_checkfreg(r1), 0, 0)); break; #ifdef RANGECHECK_SUPPORTED case J_CHKNEFR: DestroyIP(); outinstr(AMP_TCM_EXU(AMP_FCMPEQ, AMP_WorkReg, amp_checkfreg(r2), amp_checkfreg(r3))); outinstr(AMP_MRC(MCR_32, R_IP, AMP_WorkReg)); outinstr(OP_RSBN | F_SCC | F_RD(R_IP) | F_RN(R_IP) | 1); outinstr3(OP_BL ^ Q_EQ, sim.valfault, 0); break; #endif default: syserr(syserr_show_inst_dir, (long)op); illbits = 0; break; } if (illbits | peep) syserr(syserr_jop_mode, (long)op, (long)peep); #undef cpprepost } int32 power_of_two(int32 n) { /* If n is an exact power of two this returns the power, else -1 */ if (n == 0 || n != (n&(-n))) return -1; return logbase2(n); } bool ImmediateOperand(int32 n, J_OPCODE op) { switch (op & J_TABLE_BITS) { case J_ADDK: case J_SUBK: case J_CMPK: return Arm_EightBits(n) >= 0 || Arm_EightBits(-n) >= 0; case J_ANDK: case J_MOVK: return Arm_EightBits(n) >= 0 || Arm_EightBits(~n) >= 0; case J_ORRK: case J_EORK: return Arm_EightBits(n) >= 0; default: return NO; } } static void describe_literal_pool(void) { if (!in_code) { if (codebase+codep != literal_pool_start) { char b[32]; sprintf(b, "x$litpool$%d", literal_pool_number); obj_symref(sym_insert_id(b), xr_code+xr_defloc+xr_dataincode, literal_pool_start); sprintf(b, "x$litpool_e$%d", literal_pool_number++); obj_symref(sym_insert_id(b), xr_code+xr_defloc+xr_dataincode, codebase+codep-1); } in_code = YES; } } /* although the idea of setlabel is machine independent, it stays here because it back-patches code. In the long term setlabel should be in codebuf.c and call a machine dependent backpatch routine. */ void setlabel(LabelNumber *l) { List *p = l->u.frefs; Symstr *labname = NULL; for (; p!=NULL; p = (List*) discard2(p)) { int32 v = car_(p); int32 q = (v & 0x00ffffff); /* BYTE address */ int32 w = code_inst_(q); unsigned32 d; switch (v & 0xff000000) { case LABREF_BRANCH: /* Bxx instruction */ /* note the assumption that the address field contained zero */ d = (codep-q-8 >> 2) & 0x00ffffffL; w = (w & 0xff000000) | d; break; case LABREF_B4096: /* LDR r1, [pc, #nn] forward ref */ d = (codep-q-8) + (w & 0xfff); if (d >= 0x1000) syserr(syserr_displacement, (long)d); w = (w & 0xfffff000) | d; break; case LABREF_W256: /* ADD r1, pc, #nn with nn shifted left 2 bits */ /* LDFD f1, [pc, #nn] - again nn is a word offset */ d = (codep-q-8 >> 2) + (w & 0xff); if (d >= 0x100) syserr(syserr_displacement, (long)d); w = (w & 0xffffff00) | d; break; #ifdef TARGET_HAS_DATA_VTABLES case LABREF_WORD32: { /* DCD L<N> */ if (labname == NULL) { char b[256]; sprintf(b, "L%.6lx.J%ld.%s", codebase+codep, lab_name_(l) & 0x7fffffff, symname_(currentfunction.symstr)); labname = sym_insert_id(b); obj_symdef(labname, xr_code+xr_defloc, codebase+codep); } AddCodeXref4(X_absreloc | codebase+q, labname, 0); break; } #endif default: syserr(syserr_unknown_label, (long)v); } code_inst_(q) = w; } lab_setloc_(l, codep | 0x80000000); /* cheapo union checker for ->frefs */ asm_lablist = (LabList *) syn_cons2((VoidStar) asm_lablist, (VoidStar) l); if (l != litlab) describe_literal_pool(); } static void move_register(RealRegister r1, RealRegister r2, int32 scc) { /* r1 = r2 */ if (r1!=r2 || scc!=0) outinstr(OP_MOVR | scc | F_RD(r1) | r2); } static void negate_register(RealRegister r1, RealRegister r2, int32 scc) { /* r1 = -r2 */ outinstr(OP_RSBN | scc | F_RD(r1) | F_RN(r2)); } static int32 *adc_integer_i(RealRegister r1, RealRegister r2, int32 n, int32 scc, int32 *v) { /* Generate code for r1 = r2 + n + carry. */ int32 packed; packed = Arm_EightBits(n); if (packed>=0) { *v++ = (OP_ADCN | scc | F_RD(r1) | F_RN(r2) | packed); return v; } packed = Arm_EightBits(~n); /* ADC x,y,#N is equivalent SBC x,y,#NOT N ! */ if (packed>=0) { *v++ = (OP_SBCN | scc | F_RD(r1) | F_RN(r2) | packed); return v; } { ValueDesc vd; int rc = RegisterContainingValue(n, V_Inverted+V_AnyShift, &vd); if (rc != 0) { int32 w = F_RD(r1) | F_RN(r2) | scc | vd.r | vd.op3.shift; if (rc == V_Inverted) w |= OP_SBCR; else w |= OP_ADCR; *v++ = w; return v; } } /* * here it will take at least two instructions... */ { int32 op; int32 n1 = Arm_SplitForAdd(r1, n, &op); if (op == OP_SUBN) n += n1; else n -= n1; *v++ = (op | F_RD(r1) | F_RN(r2) | Arm_EightBits(n1)); return adc_integer_i(r1, r1, n, scc, v); } } static void add_integer(RealRegister r1, RealRegister r2, int32 n, int32 flags) { int32 v[4]; int32 *ve; int32 *p; ve = arm_add_integer(r1, r2, n, SCC_of_PEEP(flags), RegisterContainingValue, v); if (ve - v > 1 && (flags & P_SETCC)) { /* correct overflow & carry flags required */ load_integer(R_IP, n, 0); outinstr (OP_ADDR | SCC_of_PEEP (flags) | F_RD(r1) | F_RN(r2) | R_IP); return; } for (p = &v[0]; p != ve; p++) { int32 w = *p; outinstr(w); if (r1 == R_SP) { int32 op = w & F_DPOP; int32 n = w & 0xff; int32 sh = 2 * ((w >> 8) & 0xf); n = ROR(n, sh); if (op == F_ADD) fpdesc_notespchange(-n); else if (op == F_SUB) fpdesc_notespchange(n); } } } static void sub_integer(RealRegister r1, RealRegister r2, int32 n, int32 flags) { int32 packed = Arm_EightBits(n); if (packed >= 0) { outinstr(OP_SUBN | SCC_of_PEEP(flags) | F_RD(r1) | F_RN(r2) | packed); } else if (flags & P_SETCC) { load_integer(R_IP, n, 0); outinstr(OP_SUBR | SCC_of_PEEP(flags) | F_RD(r1) | F_RN(r2) | R_IP); } else add_integer(r1, r2, -n, flags); } static void adc_integer(RealRegister r1, RealRegister r2, int32 n, int32 flags) { int32 v[4]; int32 *ve; int32 *p; ve = adc_integer_i(r1, r2, n, SCC_of_PEEP(flags), v); if (ve - v > 1 && (flags & P_SETCC)) { /* correct overflow & carry flags required */ load_integer(R_IP, n, 0); outinstr(OP_ADCR | SCC_of_PEEP(flags) | F_RD(r1) | F_RN(r2) | R_IP); return; } for (p = &v[0]; p != ve; p++) { int32 w = *p; outinstr(w); } } static void sbc_integer(RealRegister r1, RealRegister r2, int32 n, int32 flags) { int32 packed = Arm_EightBits(n); if (packed >= 0) { outinstr(OP_SBCN | SCC_of_PEEP(flags) | F_RD(r1) | F_RN(r2) | packed); } else if (flags & P_SETCC) { load_integer(R_IP, n, 0); outinstr(OP_SBCR | SCC_of_PEEP(flags) | F_RD(r1) | F_RN(r2) | R_IP); } else adc_integer(r1, r2, ~n, flags); } static void rsb_integer(RealRegister r1, RealRegister r2, int32 n, int32 flags) { /* Generate code for r1 = n - r2. */ int32 packed = Arm_EightBits(n); int32 scc = SCC_of_PEEP (flags); if (packed >= 0) outinstr(OP_RSBN | scc | F_RD(r1) | F_RN(r2) | packed); else if (flags & P_SETCC) { load_integer(R_IP, n, 0); outinstr(OP_RSBR | scc | F_RD(r1) | F_RN(r2) | R_IP); } else { ValueDesc vd; int rc = RegisterContainingValue(n, V_AnyShift, &vd); if (rc != 0) { outinstr(OP_RSBR | scc | F_RD(r1) | F_RN(r2) | vd.r | vd.op3.shift); } else { int32 tail = 0x3, mask = 0xff; while ((n & tail)==0) tail = tail << 2, mask = mask << 2; mask &= n; n -= mask; outinstr(OP_RSBN | F_RD(r1) | F_RN(r2) | Arm_EightBits(mask)); add_integer(r1, r1, n, flags); } } } static void rsc_integer(RealRegister r1, RealRegister r2, int32 n, int32 flags) { /* Generate code for r1 = n - r2 + carry. */ int32 packed = Arm_EightBits(n); int32 scc = SCC_of_PEEP (flags); if (packed >= 0) outinstr(OP_RSCN | scc | F_RD(r1) | F_RN(r2) | packed); else if (flags & P_SETCC) { load_integer(R_IP, n, 0); outinstr(OP_RSCR | scc | F_RD(r1) | F_RN(r2) | R_IP); } else { ValueDesc vd; int rc = RegisterContainingValue(n, V_AnyShift, &vd); if (rc != 0) { outinstr(OP_RSCR | scc | F_RD(r1) | F_RN(r2) | vd.r | vd.op3.shift); } else { int32 tail = 0x3, mask = 0xff; while ((n & tail)==0) tail = tail << 2, mask = mask << 2; mask &= n; n -= mask; outinstr(OP_RSCN | F_RD(r1) | F_RN(r2) | Arm_EightBits(mask)); add_integer(r1, r1, n, flags); } } } static int32 *load_integer_i(RealRegister r, int32 n, int32 scc, int32 *v); static int32 *symmetricload(RealRegister r, uint32 n, uint32 mask, int shift, int32 scc, int32 *v) { int c; for (c = 0 ; c < shift ; mask <<= 2, c += 2) { int k; for (k = 1-shift ; k < shift ; k++) if ((n & mask) == ROR((n & ~mask), shift+k)) { v = load_integer_i(r, n & mask, 0, v); *v++ = (OP_ADDR | scc | F_RD(r) | F_RN(r) | r | K_ROR(32L-shift-k)); return v; } } return v; } static int32 *load_integer_i(RealRegister r, int32 n, int32 scc, int32 *v) { /* Set register r to the integer n, setting condition codes on scc */ int32 op = OP_MOVN, packed = Arm_EightBits(n); ValueDesc vd; int rc; if (packed<0) op = OP_MVNN, packed = Arm_EightBits(~n); if (packed>=0) { *v++ = (op | F_RD(r) | scc | packed); return v; } if ((rc = RegisterContainingValue(n, V_KAdded+V_Orred+V_Inverted+V_AnyShift+V_RegPair, &vd)) != 0) { int32 w = F_RD(r) | scc; if (rc == V_Inverted) w |= OP_MVNR | vd.r | vd.op3.shift; else if (rc == V_Orred) w |= OP_ORRR | F_RN(vd.r) | vd.r | vd.op3.shift; else if (rc == V_KAdded || rc == V_RegPair) w |= vd.op3.add.op | F_RN(vd.r) | vd.op3.add.k; else if (vd.r != r || vd.op3.shift != 0) w |= OP_MOVR | vd.r | vd.op3.shift; else return v; *v++ = w; return v; } else { int32 pos1 = 0, size1 = 0, value1 = -1; int32 pos2 = 0, size2 = 0, value2 = -1; int32 startsize = 0, startvalue = -1; int32 pos = 0, value = -1, start = -1; int32 mask = 3; /* find the two longest strings of pairs of 00 or 11 (on an even bit boundary), setting sizen to the number of bits, posn to the ls bit, valuen to 0 for 00, 1 for 11 (n=1 longest) */ for ( ; pos <= 32; mask = mask<<2, pos += 2) { int32 newvalue = mask == 0 ? -1 : ((n & mask) == mask) ? 3 : ((n & mask) == 0) ? 0 : -1; if (value != newvalue) { if (value != -1) { int32 size = pos - start; if (start == 0) { startsize = size; startvalue = value; /* disregard a string in the ls bits if these are the same as the ms bits (it will be included in the string including the ms bits). */ if (((n >> 30) & 3) == value) size = -1; } if (pos == 32 && value == startvalue) size += startsize; if (size >= size1) { pos2 = pos1; size2 = size1; value2 = value1; size1 = size; pos1 = start; value1 = value; } else if (size >= size2) { size2 = size; pos2 = start; value2 = value; } } value = newvalue; start = pos; } } { int32 remainder, k; int32 nextpos = pos1 + size1; if (nextpos >= 32) nextpos -= 32; if ( value1 == 3 && size1 > 8 && (value2 == 3 || pos1 == 0)) { /* both longest strings are 1s, or the longest is 1s and starts at the ls bit. And in any case, the length of the longest string is sensible (eg beware 55aa3355). Maybe should also look for a (shorter) sensible length for the second string. Use MVN to construct the 8-bit chunk above the longest string (which will give us 1s in the two longest strings for free) */ op = OP_MVNN; k = (~n) & ROR(255L, (32-nextpos)); remainder = n - ~k; } else if ((value1 == 3 && size1 > 8) || (value2 == 3 && size2 > 8)) { /* one of the two longest strings is a sensible length and of 1s (the other is 0s). Take the 8-bit chunk above the string of 1s incremented by 1 in its last place unless that is bit 0 of n. (The idea being that we will generate the string of 1s by subtracting something) */ if (value2 == 3) { nextpos = pos2 + size2; if (nextpos >= 32) nextpos -= 32; } op = OP_MOVN; if (nextpos != 0) k = (n & ROR(255L, (32 - nextpos))) + (1L << nextpos); /* (k has only 8 bits - (n & ...) cannot be 255<<nextpos or it would have been included in the string of 1s) */ else { if (startvalue == 0) nextpos += startsize; k = n & ROR(255L, (32 - nextpos)); } remainder = n - k; } else { /* The longest two strings are of 0s. Take the 8-bit chunk above the longer. */ op = OP_MOVN; k = n & ROR(255L, (32 - nextpos)); remainder = n - k; } if (Arm_EightBits(remainder) < 0 && Arm_EightBits(-remainder) < 0) { int32 *v1 = symmetricload(r, n, 0xffff, 16, scc, v); if (v1 != v) return v1; v1 = symmetricload(r, n, 0xff00ff, 8, scc, v); if (v1 != v) return v1; } *v++ = (op | F_RD(r) | Arm_EightBits(k)); KillKnownRegisterValue(r); return arm_add_integer(r, r, remainder, scc, RegisterContainingValue, v); } } } static void load_integer_literal(RealRegister r, int32 n) { int32 dirn = F_UP; int32 i; ldm_flush(); i = lit_findwordsincurpool(&n, 1, LIT_NUMBER); if (i < 0) { i = lit_findwordsinprevpools(&n, 1, LIT_NUMBER, codebase+codep+8-4092); if (i >= 0) { i = codebase+codep+8-i; dirn = F_DOWN; } else { addressability(1024); i = lit_findword(n, LIT_NUMBER, 0, LITF_INCODE|LITF_FIRST|LITF_LAST); } } if (dirn == F_UP) addfref_(litlab, codep | LABREF_B4096); outinstr(OP_LDR | dirn | F_RD(r) | F_RN(R_PC) | i); } static void load_integer(RealRegister r, int32 n, int32 flags) { int32 v[5]; /* Pessimism here about the number of instructions add_integer may decide to generate */ int32 scc = SCC_of_PEEP (flags); int32 *ve = load_integer_i(r, n, scc, v); int max = (scc == 0) ? integer_load_max : integer_load_max+1; if (ve-v <= max) { int32 *p = v; for (; p != ve; p++) outinstr(*p); } else { load_integer_literal(r, n); /* This should never happen, since load_integer gets called with */ /* scc non-zero only perhaps from multiply_integer by 0, when n */ /* is zero, so shouldn't get into this code at all */ if (scc != 0) /* last three arguments to compare_integer irrelevant for */ /* comparison against 0. */ cmp_integer(r, 0, 0, 0, 0); } killipvalue(r); SetKnownRegisterValue(r, n); } static int clears_lobits(int32 n) { int shift; for (shift = 0; shift < 32; ++shift) { int32 lobits = (1L << shift) - 1L; if (n == ~lobits) return shift; } return 0; } static int clears_hibits(int32 n) { int shift; for (shift = 0; shift < 32; ++shift) { int32 hibits = (~0L) << (32-shift); if (n == ~hibits) return shift; } return 0; } static void and_integer(RealRegister r1, RealRegister r2, int32 n, int32 peep, bool dead_r1) { /* Generate code for r1 = r2 & n. */ int shift; int32 op = OP_ANDN, packed = Arm_EightBits(n); int32 scc = SCC_of_PEEP(peep); int32 mask = peep & Q_MASK; if (n == -1) { move_register(r1, r2, scc); return; } if (packed < 0) op = OP_BICN, packed = Arm_EightBits(~n); if (packed >= 0) { outinstr(op | scc | F_RD(r1) | F_RN(r2) | packed); return; } { ValueDesc vd; int rc = RegisterContainingValue(n, V_Inverted+V_AnyShift, &vd); if (rc != 0) { int32 w = scc | F_RD(r1) | F_RN(r2) | vd.r | vd.op3.shift; if (rc == V_Inverted) outinstr(OP_BICR | w); else outinstr(OP_ANDR | w); return; } } if ((shift = clears_hibits(n)) != 0) { if (dead_r1 || (peep & P_ZONLY)) { mask &= ~Q_UBIT; if (mask == Q_EQ || mask == Q_NE) { if (scc) outinstr(OP_MOVR | scc | F_RD(r1) | r2 | K_LSL(shift)); return; } } outinstr(OP_MOVR | 0 | F_RD(r1) | r2 | K_LSL(shift)); outinstr(OP_MOVR | scc | F_RD(r1) | r1 | K_LSR(shift)); return; } if ((shift = clears_lobits(n)) != 0) { if (dead_r1 || (peep & P_ZONLY)) { if (scc) outinstr(OP_MOVR | scc | F_RD(r1) | r2 | K_ASR(shift)); return; } outinstr(OP_MOVR | 0 | F_RD(r1) | r2 | K_LSR(shift)); outinstr(OP_MOVR | scc | F_RD(r1) | r1 | K_LSL(shift)); return; } { int32 tail=0x3, mask = 0xff; while ((~n & tail)==0) tail = tail << 2, mask = mask << 2; and_integer(r1, r2, n | mask, 0, NO); outinstr(OP_BICN | scc | F_RD(r1) | F_RN(r1) | Arm_EightBits(~n & mask)); } } static void orr_integer(RealRegister r1, RealRegister r2, int32 n, int32 flags) { /* Generate code for r1 = r2 | n. */ int32 packed = Arm_EightBits(n); int32 scc = SCC_of_PEEP(flags); if (n == 0) { move_register(r1, r2, scc); } else if (packed >= 0) { outinstr(OP_ORRN | scc | F_RD(r1) | F_RN(r2) | packed); } else { ValueDesc vd; int rc = RegisterContainingValue(n, V_AnyShift, &vd); if (rc != 0) { outinstr(OP_ORRR | scc | F_RD(r1) | F_RN(r2) | vd.r | vd.op3.shift); } else { int32 tail=0x3, mask = 0xff; while ((n & tail)==0) tail = tail << 2, mask = mask << 2; orr_integer(r1, r2, n & (~mask), 0); outinstr(OP_ORRN | scc | F_RD(r1) | F_RN(r1) | Arm_EightBits(n & mask)); } } } static void eor_integer(RealRegister r1, RealRegister r2, int32 n, int32 flags) { /* Generate code for r1 = r2 ^ n. */ int32 packed = Arm_EightBits(n); int32 scc = SCC_of_PEEP(flags); if (n == 0) { move_register(r1, r2, scc); } else if (packed >= 0) { outinstr(OP_EORN | scc | F_RD(r1) | F_RN(r2) | packed); } else { ValueDesc vd; int rc = RegisterContainingValue(n, V_AnyShift, &vd); if (rc != 0) { outinstr(OP_EORR | scc | F_RD(r1) | F_RN(r2) | vd.r | vd.op3.shift); } else { int32 tail=0x3, mask = 0xff; while ((n & tail)==0) tail = tail << 2, mask = mask << 2; eor_integer(r1, r2, n & (~mask), 0); outinstr(OP_EORN | scc | F_RD(r1) | F_RN(r1) | Arm_EightBits(n & mask)); } } } static void teq_integer(RealRegister rt, RealRegister r2, int32 n, int32 flags) { /* Generate code for r2 ^ n. */ int32 packed = Arm_EightBits(n); int32 scc = SCC_of_PEEP(flags); if (packed >= 0) { outinstr(OP_TEQN | scc | F_RN(r2) | packed); } else { ValueDesc vd; int rc = RegisterContainingValue(n, V_AnyShift, &vd); if (rc != 0) { outinstr(OP_TEQR | scc | F_RN(r2) | vd.r | vd.op3.shift); } else if (flags & P_SETPSR) { /* TEQP */ load_integer(rt, n, 0); outinstr (OP_TEQR | scc | F_RN(r2) | rt); } else eor_integer(rt, r2, n, flags); } } static void tst_integer(RealRegister rt, RealRegister r2, int32 n, int32 flags) { /* Generate code for r2 & n. */ int32 packed = Arm_EightBits(n); int32 scc = SCC_of_PEEP(flags); if (packed >= 0) { outinstr(OP_TSTN | scc | F_RN(r2) | packed); } else { ValueDesc vd; int rc = RegisterContainingValue(n, V_AnyShift, &vd); if (rc != 0) { outinstr(OP_TSTR | scc | F_RN(r2) | vd.r | vd.op3.shift); } else if (flags & P_SETPSR) { /* TSTP */ load_integer(rt, n, 0); outinstr (OP_TSTR | scc | F_RN(r2) | rt); } else and_integer(rt, r2, n, flags, YES); } } static int32 eightbit_floor(int32 n) /* n is a positive integer - find a number representable as an ARM */ /* operand that is less than (or ==) n but as close to it as possible */ { unsigned32 m1 = 0xff000000, m2 = 0xc0000000; /* the special case is needed to cover n==0 */ if ((n & 0xff)==n) return n; while ((n & m2)==0) { m1 = m1 >> 2; m2 = m2 >> 2; } return (n & m1); } static int32 eightbit_ceiling(int32 n) /* n is a positive integer - find a number >= n that is representable */ /* as an ARM operand. */ { unsigned32 m1 = 0xff000000, m2 = 0xc0000000; if ((n & 0xff)==n) return n; while ((n & m2)==0) { m1 = m1 >> 2; m2 = m2 >> 2; } /* In the next line I increment an 8-bit value by the lowest bit of m1, */ /* which operation can certainly cause overflow from 0xff to 0x100, but */ /* 0x100 is representable in 8-bits on ARM so this does not matter. Also */ /* there can be the generation of 0x80000000 as (e.g.) the nearest value */ /* above 0x7fxxxxxx - I will need to be careful about that when I call */ /* this horrid function. */ return (n & m1) + (m1 & (0-m1)); } static int32 *compare_integer_i(RealRegister r, int32 n, RealRegister workreg, int32 mask, int32 when, int32 *v) { /* Compare register r with integer n, setting condition codes */ int32 op = OP_CMPN, packed = Arm_EightBits(n); if (packed < 0) { op = OP_CMNN; packed = Arm_EightBits(-n); } if (packed >= 0) *v++ = (when | op | F_RN(r) | packed); else { ValueDesc vd; int rc = RegisterContainingValue(n, V_Negated+V_AnyShift, &vd); if (rc != 0) { int32 w = when | F_RN(r) | vd.r | vd.op3.shift; if (rc == V_Negated) w |= OP_CMNR; else w |= OP_CMPR; *v++ = w; } else { int32 m = 0, cond = 0; /* Note that n!=0 here */ if (mask == Q_EQ || mask == Q_NE || mask == Q_UNE || mask == Q_UEQ) { m = (n > 0) ? eightbit_floor(n) : -eightbit_floor(-n); } else if (mask == Q_UNDEF || condition_mask != C_ALWAYS) { /* nothing */ } else if (mask & Q_UBIT) { if (n > 0) m = eightbit_floor(n), cond = C_HS; else m = -eightbit_floor(-n), cond = C_LS; when |= F_SCC; } else { if (n > 0) m = eightbit_floor(n), cond = C_GE; else m = -eightbit_floor(-n), cond = C_LE; when |= F_SCC; } if (m != 0) { v = arm_add_integer(workreg, r, -m, when, RegisterContainingValue, v); v = compare_integer_i(workreg, n-m, workreg, mask, cond, v); } } } return v; } static void compare_integer(RealRegister r, int32 n, RealRegister workreg, int32 mask, int32 when) { int32 v[5], w[5]; int32 *ve = compare_integer_i(r, n, workreg, mask, when, v); unsigned iv = ve - v; int32 *we = load_integer_i(workreg, n, 0, w); unsigned iw = we - w + 1; if (0 < iv && iv <= integer_load_max+1 && iv <= iw && when == 0) { for (iv = 0; &v[iv] != ve; iv++) outinstr(v[iv]); killipvalue(workreg); KillKnownRegisterValue(workreg); } else { if (iw <= integer_load_max+1) { for (iw = 0; &w[iw] != we; iw++) outinstr(w[iw]); } else load_integer_literal(workreg, n); outinstr(OP_CMPR | F_RN(r) | workreg | when); killipvalue(workreg); SetKnownRegisterValue(workreg, n); } } static void cmp_integer(RealRegister r, int32 n, RealRegister workreg, int32 condition, int32 flags) { int32 op = OP_CMPN, packed = Arm_EightBits(n); if (packed < 0) { op = OP_CMNN; packed = Arm_EightBits(-n); } if (flags & P_SETPSR) op |= F_RD(15); if (packed >= 0) outinstr(op | F_RN(r) | packed); else compare_integer(r, n, workreg, condition, flags & P_SETPSR ? F_RD(15) : 0); } static void cmn_integer(RealRegister r, int32 n, RealRegister workreg, int32 condition, int32 flags) { int32 op = OP_CMNN, packed = Arm_EightBits(n); if (packed < 0) { op = OP_CMPN; packed = Arm_EightBits(-n); } if (flags & P_SETPSR) op |= F_RD(15); if (packed>=0) outinstr(op | F_RN(r) | packed); else compare_integer(r, -n, workreg, condition, flags & P_SETPSR ? F_RD(15) : 0); } typedef struct { int32 i[32]; RealRegister workreg; int n; } InstDesc; static int32 multiply_1(RealRegister r1, RealRegister r2, int32 n, int32 scc) { int32 s; if ((s = power_of_two(n)) >= 0) return OP_MOVR | scc | F_RD(r1) | r2 | K_LSL(s); else if ((s = power_of_two(n-1)) >= 0) return OP_ADDR | scc | F_RD(r1) | F_RN(r2) | r2 | K_LSL(s); else if ((s = power_of_two(1-n)) >= 0) return OP_SUBR | scc | F_RD(r1) | F_RN(r2) | r2 | K_LSL(s); else if ((s = power_of_two(n+1)) >= 0) return OP_RSBR | scc | F_RD(r1) | F_RN(r2) | r2 | K_LSL(s); return 0; } static bool multiply_2(RealRegister r1, RealRegister r2, int32 n, int32 scc, InstDesc *i) { /* is n of the form (2^p +/- 1)(2^q +/- 1) ? * (2^(p+q)+/-2^p+/-2^q+/-1) * thus if n is of this form (and p != q), one factor is s+/-1 where s is * the bottom bit of n after adding or subtracting 1. * if p == q, this is wrong, but we can still do the multiply in two * instructions as 2^(2*p)+/-2^(p+1)+/-1 using a work register */ int32 k = (n & 2) == 0 ? n - 1 : n + 1; int32 s = k & (-k); int32 factor; int32 i0; if ( ((n % (factor = s - 1)) == 0 && (i0 = multiply_1(r1, r2, n / factor, 0)) != 0) || ((n % (factor = s + 1)) == 0 && (i0 = multiply_1(r1, r2, n / factor, 0)) != 0)) { i->i[i->n] = i0; i->i[i->n+1] = multiply_1(r1, r1, factor, scc); i->workreg = NoRegister; i->n += 2; return YES; } if (i->workreg != NoRegister) { RealRegister r3 = i->workreg; int32 sh; /* is n of the form 2^a +/- 2^b +/- 1 ? */ if ((sh = power_of_two(k-s)) >= 0) { i->i[i->n] = multiply_1(r3, r2, s+n-k,0); i->i[i->n+1] = OP_ADDR | scc | F_RD(r1) | F_RN(r3) | r2 | K_LSL(sh); i->n += 2; return YES; } else if ((sh = power_of_two(k+s)) >= 0) { i->i[i->n] = multiply_1(r3, r2, s-n+k, 0); i->i[i->n+1] = OP_RSBR | scc | F_RD(r1) | F_RN(r3) | r2 | K_LSL(sh); i->n += 2; return YES; } } return NO; } static bool multiply_3(RealRegister r1, RealRegister r2, int32 n, int32 scc, InstDesc *i) { int32 k; /* is n of the form (2^p+/-1)*m, where m can be multiplied by in two instructions? */ for (k = 0x00010000; k >= 4; k = k >> 1) { if ((n % (k-1)) == 0 && multiply_2(r1, r2, n/(k-1), 0, i)) { i->i[i->n++] = multiply_1(r1, r1, k-1, scc); return YES; } if ((n % (k+1)) == 0 && multiply_2(r1, r2, n/(k+1), 0, i)) { i->i[i->n++] = multiply_1(r1, r1, k+1, scc); return YES; } } if (i->workreg != NoRegister) { /* is n of the form +/-2^p+/-m, where m can be multiplied by in two instructions? */ RealRegister r3 = i->workreg; k = (n & 2) == 0 ? n - 1 : n + 1; while (k != 0) { int32 s = k & (-k); if (multiply_2(r3, r2, n-s, 0, i)) { s = power_of_two(s); i->i[i->n++] = OP_ADDR | scc | F_RD(r1) | F_RN(r3) | r2 | K_LSL(s); i->workreg = r3; return YES; } else if (multiply_2(r3, r2, n+s, 0, i)) { s = power_of_two(s); i->i[i->n++] = OP_SUBR | scc | F_RD(r1) | F_RN(r3) | r2 | K_LSL(s); i->workreg = r3; return YES; } if (k & (s << 1)) k += s; else k -= s; } } return NO; } static void multiply_i(RealRegister r1, RealRegister r2, int32 n, int32 scc, InstDesc *i) { int32 s, k; RealRegister r3 = i->workreg; if ((s = multiply_1(r1, r2, n, scc)) != 0) { i->i[i->n++] = s; i->workreg = NoRegister; return; } else if ((s = n & (-n)) != 1) { /* divisible by a power of 2 */ multiply_i(r1, r2, n/s, 0, i); i->i[i->n++] = multiply_1(r1, r1, s, scc); return; } if (multiply_2(r1, r2, n, scc, i) || multiply_3(r1, r2, n, scc, i)) { return; } /* Determine whether our number has a factor of the form 2^s+1 or 2^s-1 */ /* Note that since various cases have already been checked the number n */ /* is not of any of the forms 2^s+1, 2^s-1, 1-2^s. */ for (k = 0x00010000; k >= 4; k = k >> 1) { if ((n % (k-1)) == 0) { k = k-1; break; } else if ((n % (k+1)) == 0) { k = k+1; break; } } if (k > 2) { multiply_i(r1, r2, n/k, 0, i); i->i[i->n++] = multiply_1(r1, r1, k, scc); return; } if ((n&2) == 0) { k = n - 1; s = k & (-k); multiply_i(r3, r2, k/s, 0, i); s = power_of_two(s); i->i[i->n++] = OP_ADDR | scc | F_RD(r1) | F_RN(r2) | r3 | K_LSL(s); } else { k = n + 1; s = k & (-k); multiply_i(r3, r2, k/s, 0, i); s = power_of_two(s); i->i[i->n++] = OP_RSBR | scc | F_RD(r1) | F_RN(r2) | r3 | K_LSL(s); } i->workreg = r3; } static void multiply_integer(RealRegister r1, RealRegister r2, int32 n, int32 scc) /* **** Keep this in step with MultiplyNeedsWorkreg below **** */ { /* Generate code for r1 = r2 * n. scc can be used to set condn codes. */ if (codep >= mustlitby) dumplits2(YES); if (n==0) load_integer(r1, 0, scc); else if (n==1) move_register(r1, r2, scc); else if (n==-1) negate_register(r1, r2, scc); else { InstDesc insts; RealRegister workreg; int32 w[5]; int load_time, multiply_time; bool use_multiply = NO; if (r1 != r2) workreg = r1; /* if source != dest, can use dest reg */ else workreg = R_IP; /* otherwise a fixed register */ insts.n = 0; insts.workreg = workreg; multiply_i(r1, r2, n, scc, &insts); load_time = load_integer_i(r1, n, 0, w) - w; multiply_time = (config & CONFIG_OPTIMISE_SPACE) ? 1 : multiply_cycles(n, NO); if (load_time + multiply_time < insts.n) use_multiply = YES; if (use_multiply) { load_integer(workreg, n, 0); /* /* Maybe n is available in a register */ if (r1 == r2) outinstr(OP_MUL | F_RN(r1) | (r2 << 8) | workreg | scc); else outinstr(OP_MUL | F_RN(r1) | (workreg << 8) | r2 | scc); } else { int i = 0; if (insts.workreg != NoRegister) { killipvalue(insts.workreg); KillKnownRegisterValue(insts.workreg); } for (; i < insts.n; i++) outinstr(insts.i[i]); } } } bool MultiplyNeedsWorkreg(int32 n) /* **** Keep this in step with multiply_integer above **** */ { InstDesc insts; static struct { int32 n; bool res; } last = {0, 0}; int load_time, multiply_time; bool use_multiply = NO; if (last.n == n) return last.res; if (n >= -1 && n <= 1) return NO; last.n = n; insts.n = 0; insts.workreg = 0; /* This may be called before registers have been assigned (hence the 0s below). Fortunately, the pattern of instructions generated isn't affected, just the register used as workreg if one is needed. */ multiply_i(0, 0, n, 0, &insts); load_time = integer_load_max; /* cannot call load_integer_i!!! */ multiply_time = (config & CONFIG_OPTIMISE_SPACE) ? 1 : multiply_cycles(n, NO); if (load_time + multiply_time < insts.n) use_multiply = YES; if (use_multiply) return last.res = (insts.workreg != NoRegister); else return last.res = YES; } static void mla_integer(RealRegister r1, RealRegister r2, int32 n, RealRegister acc, int32 scc) /* **** Keep this in step with MultiplyNeedsWorkreg below **** */ { /* Generate code for r1 = r2 * n + acc. scc can be used to set condn codes. */ if (codep >= mustlitby) dumplits2(YES); if (n==0) move_register(r1, acc, scc); else if (n==1) outinstr(OP_ADDR | F_RD(r1) | F_RN(acc) | r2 | scc); else if (n==-1) outinstr(OP_SUBR | F_RD(r1) | F_RN(acc) | r2 | scc); else { InstDesc insts; RealRegister workreg; int32 w[5]; int32 shift, m; int load_time, multiply_time; bool use_multiply = NO; shift = n & -n; m = n / shift; /* remove trailing zeroes of n */ shift = logbase2(shift); workreg = R_IP; /* always use a fixed register */ insts.n = 0; insts.workreg = workreg; multiply_i(workreg, r2, m, 0, &insts); load_time = load_integer_i(r1, n, 0, w) - w; multiply_time = (config & CONFIG_OPTIMISE_SPACE) ? 1 : multiply_cycles(n, YES); if (load_time + multiply_time < insts.n + 1) use_multiply = YES; if (use_multiply) { load_integer(workreg, n, 0); if (r1 == r2) outinstr(OP_MLA | F_RN(r1) | F_RD(acc) | (r2 << 8) | workreg | scc); else outinstr(OP_MLA | F_RN(r1) | F_RD(acc) | (workreg << 8) | r2 | scc); } else { int i = 0; if (insts.workreg != NoRegister) { killipvalue(insts.workreg); KillKnownRegisterValue(insts.workreg); } for (; i < insts.n; i++) outinstr(insts.i[i]); outinstr(OP_ADDR | F_RD(r1) | F_RN(acc) | K_LSL(shift) | workreg | scc); } } } #if DEBUG_X /* For truly grim debugging I can make each compiled function display */ /* its name each time it is entered. This is arranged here. Ugh. */ static void desperate_codetrace(void) { int32 w = 0, c, i = 0; outinstr(0x0f000001); /* SWI KString */ while ((c=symname_(currentfunction.symstr)[i++]) != 0) { w = ((w>>8) & 0x00ffffff) | (c << 24); if ((w & 0xff)!=0) outcodeword(w, LIT_STRING), w=0; } w = ((w>>8) & 0x00ffffff) | (((int32)'\r')<<24); if ((w & 0xff)!=0) outcodeword(w, LIT_STRING), w=0; w = ((w>>8) & 0x00ffffff) | (((int32)'\n')<<24); if ((w & 0xff)!=0) { outcodeword(w,LIT_STRING); outcodeword(0,LIT_STRING); } else { while ((w & 0xff)==0) w = (w>>8) & 0x00ffffff; outcodeword(w,LIT_STRING); } } #endif /* DEBUG_X */ static RealRegister local_base_a(int32 p) { switch (p & BINDADDR_MASK) { default: syserr(syserr_local_base, (long)p); case BINDADDR_ARG: if ((procflags & NONLEAF) && !(pcs_flags & PCS_NOFP) && !(procauxflags & bitoffnaux_(s_irq))) return R_FP; /* drop through */ case BINDADDR_LOC: return R_SP; } } RealRegister local_base(Binder const *b) { return local_base_a(bindaddr_(b)); } static bool saveregs_done; static int32 local_addr_a(int32 p) { /* fp_minus_sp is now maintained by show_instruction_direct, so is up to date even if the instruction to modify the sp hasn't yet been generated thanks to peepholing. */ switch (p & BINDADDR_MASK) { default: syserr(syserr_local_addr, (long)p); case BINDADDR_LOC: p = fp_minus_sp - (p & ~BINDADDR_MASK); /* * You might have thought that the next line was a sensible thing to have * put in as a consistency check, but CSE elimination can lift an ADCONV * outside the scope of the variable being addressed. The result is that * the address is sometimes computed as a negative offset relative to sp, * ready for when sp gets dropped later. Ugh! * if (p < 0) syserr(syserr_neg_addr, (long)p, (long)p, b); */ return p; case BINDADDR_ARG: p &= ~BINDADDR_MASK; #if 0 if (!(procflags & NONLEAF)) { /* LDRV1 only - hence nargwords > NARGREGS. SP relative. */ if (p < 4*nregargwords) syserr(syserr_local_addr1); p += fp_minus_sp; return p - 16 + 4*(bitcount(regmask & (M_VARREGS | regbit(R_LR))) + saved_fpreg_words * bitcount(regmask & M_FVARREGS)); } #endif /* on the ARM the args go in different places depending on */ /* their number. This saves one STM for <= NARGREGS args. */ p -= (p >= 4*argwordsbelowfp) ? 4*(argwordsbelowfp - savewordsabovefp) : 4*(argwordsbelowfp + intsavewordsbelowfp); return (!(procflags & NONLEAF) || (pcs_flags & PCS_NOFP) || (procauxflags & bitoffnaux_(s_irq))) ? p + fp_minus_sp + 4*(intsavewordsbelowfp + realargwordsbelowfp + saved_fpreg_words * bitcount(regmask & M_FVARREGS)) : p; } } int32 local_address(Binder const *b) { return local_addr_a(bindaddr_(b)); } #ifdef TARGET_HAS_DEBUGGER /* The miserable debugger cannot cope with SP relative addresses so we */ /* have to calculate FP relative ones specially! */ /* Lets hope that we have calculated these correctly! */ /* This means that cg.c has set PROC_ARGPUSH which thereby inhibits */ /* leaf procedure optimisation (else there would be no FP!) */ int32 local_fpaddress(Binder const *b) /* exported for debugger */ { int32 p = bindaddr_(b) & ~BINDADDR_MASK; switch (bindaddr_(b) & BINDADDR_MASK) { case BINDADDR_LOC: p = -(p + 4*(intsavewordsbelowfp + realargwordsbelowfp + saved_fpreg_words * bitcount(regmask & M_FVARREGS))); break; case BINDADDR_ARG: if (p >= 4*argwordsbelowfp) p -= 4*(argwordsbelowfp - savewordsabovefp); else p -= 4*(argwordsbelowfp + intsavewordsbelowfp); break; default: syserr(syserr_debug_addr); return 0; } return (!(procflags & NONLEAF) || (pcs_flags & PCS_NOFP) || (procauxflags & bitoffnaux_(s_irq))) ? p + 4 : p; } RealRegister local_fpbase(Binder const *b) { IGNORE(b); return !(procflags & NONLEAF) || (pcs_flags & PCS_NOFP) || (procauxflags & bitoffnaux_(s_irq)) ? R_NOFPREG : R_FP; } #endif /* TARGET_HAS_DEBUGGER */ static int32 const fm_countbits[] = { F_FM_1, F_FM_2, F_FM_3, F_FM_4 }; static void fpa_saveregs(int32 mask) { RealRegister r1; for (r1 = R_F7; r1 >= R_F4; r1--) if (mask & regbit(r1)) { if (pcs_flags & PCS_FPE3) { int32 count = 1; while (--r1 >= R_F4 && count < 4 && (mask & regbit(r1))) count++; outinstr(OP_CPPRE | F_DOWN | F_WRITEBACK | F_STR | F_RN(R_SP) | F_RD((r1+1) & 0xf) | fm_countbits[count-1] | (3 * count)); fpdesc_notespchange(count * 3 * 4); } else { outinstr(OP_CPPRE | F_DOWN | F_WRITEBACK | F_STR | F_RN(R_SP) | F_RD(r1 & 0xf) | F_EXTENDED | 3); fpdesc_notespchange(3 * 4); } } } static int32 fpa_restoresize(int32 mask) { RealRegister r1; int32 n = 0; for (r1 = R_F7; r1 >= R_F4; r1--) if (mask & regbit(r1)) n += 3 * 4; return n; } static void fpa_restoreregs(int32 mask, int32 condition, FP_RestoreBase base, int32 offset) { RealRegister r; int32 n = intsavewordsbelowfp + 3 * bitcount(regmask & M_FVARREGS) + realargwordsbelowfp; for (r = R_F4; r <= R_F7; r++) if (regbit(r) & mask) { if (base == UseSP_Adjust) { int32 count = 1; if (pcs_flags & PCS_FPE3) { RealRegister r1 = r; while (count < 4 && ++r <= R_F7 && (mask & regbit(r))) count++; outinstr(OP_CPPOST | condition | F_UP | F_LDR | F_WRITEBACK | F_RN(R_SP) | F_RD(r1 & 0xf) | fm_countbits[count-1] | (3 * count)); } else outinstr(OP_CPPOST | condition | F_UP | F_LDR | F_WRITEBACK | F_RN(R_SP) | F_RD(r & 0xf) | F_EXTENDED | 3); fpdesc_notespchange(-count * 3 * 4); } else if (base == UseSP_NoAdjust) { int32 count = 1; if (pcs_flags & PCS_FPE3) { RealRegister r1 = r; while (count < 4 && ++r <= R_F7 && (mask & regbit(r))) count++; outinstr(OP_CPPRE | condition | F_UP | F_LDR | F_RN(R_SP) | F_RD(r1 & 0xf) | fm_countbits[count-1] | (offset/4)); offset += 12 * count; } else { outinstr(OP_CPPRE | condition | F_UP | F_LDR | F_RN(R_SP) | F_RD(r & 0xf) | F_EXTENDED | (offset/4)); offset += 12; } } else { int32 count = 1; if (pcs_flags & PCS_FPE3) { RealRegister r1 = r; while (++r <= R_F7 && (mask & regbit(r))) count++; outinstr(OP_CPPRE | condition | F_DOWN | F_LDR | F_RN(R_FP) | F_RD(r1 & 0xf) | fm_countbits[count-1] | n); } else outinstr(OP_CPPRE | condition | F_DOWN | F_LDR | F_RN(R_FP) | F_RD(r & 0xf) | F_EXTENDED | n); n -= 3 * count; } } } static void fpa_saveargs(int32 n) { for (; --n >= 0; ) { outinstr(OP_CPPRE | F_DOWN | F_WRITEBACK | F_STR | F_RN(R_SP) | F_RD(R_F0+n) | F_DOUBLE | 2); fpdesc_notespchange(2 * 4); } } static FP_Gen const fpa_gen = { fpa_show, fpa_saveregs, fpa_restoresize, fpa_restoreregs, fpa_saveargs }; static void amp_saveregs(int32 mask) { RealRegister r1; for (r1 = R_F7; r1 >= R_F4; r1--) if (mask & regbit(r1)) outinstr(AMP_DT(CPDT_PRE | CPDT_DOWN | CPDT_WB | CPDT_ST, R_SP, amp_checkfreg(r1), 4)); } static int32 amp_restoresize(int32 mask) { RealRegister r1; int32 n = 0; for (r1 = R_F7; r1 >= R_F4; r1--) if (mask & regbit(r1)) n += 4; return n; } static void amp_restoreregs(int32 mask, int32 condition, FP_RestoreBase base, int32 offset) { RealRegister r; int32 n = intsavewordsbelowfp + bitcount(regmask & M_FVARREGS) + realargwordsbelowfp; for (r = R_F4; r <= R_F7; r++) if (regbit(r) & mask) { if (base == UseSP_Adjust) { outinstr(AMP_DT(CPDT_POST | CPDT_UP | CPDT_WB | CPDT_LD, R_SP, amp_checkfreg(r), 4) | condition); fpdesc_notespchange(-4); } else if (base == UseSP_NoAdjust) { outinstr(AMP_DT(CPDT_PRE | CPDT_UP | CPDT_LD, R_SP, amp_checkfreg(r), offset) | condition); offset += 4; } else { outinstr(AMP_DT(CPDT_PRE | CPDT_DOWN | CPDT_LD, R_FP, amp_checkfreg(r), n*4) | condition); n -= 1; } } } static void amp_saveargs(int32 n) { for (; --n >= 0; ) { outinstr(AMP_DT(CPDT_PRE | CPDT_DOWN | CPDT_WB | CPDT_ST, R_SP, amp_checkfreg(R_F0+n), 4)); fpdesc_notespchange(4); } } static FP_Gen const amp_gen = { amp_show, amp_saveregs, amp_restoresize, amp_restoreregs, amp_saveargs }; static int32 LSBits(int32 mask, int n) { int32 mask1 = 0; for (; --n >= 0;) { int32 bit = mask & (-mask); mask1 |= bit; mask ^= bit; } return mask1; } static int32 MSBits(int32 mask, int n) { int n1 = (int)bitcount(mask) - n; for (; --n1 >= 0;) { mask ^= mask & (-mask); } return mask; } static void PushRegs(int32 mask) { unsigned count = (unsigned)bitcount(mask); int32 stm = OP_STMFD | F_WRITEBACK | F_RN(R_SP); for (; count > ldm_regs_max; count -= ldm_regs_max) { int32 mask1 = MSBits(mask, ldm_regs_max); mask ^= mask1; outinstr(stm | mask1); fpdesc_notespchange(bitcount(mask1) * 4); } outinstr(stm | mask); fpdesc_notespchange(bitcount(mask) * 4); } static void routine_entry(int32 m) { condition_mask = C_ALWAYS; #if DEBUG_X if (debugging(DEBUG_X)) desperate_codetrace(); #endif { Symstr *name = currentfunction.symstr; int flags = currentfunction.xrflags; if ((pcs_flags & PCS_REENTRANT) && (procflags & PROC_USESADCONS)) flags |= aof_usessb; if (!(procflags & NONLEAF)) { #ifndef TARGET_IS_UNIX if (!(procflags & BLK0EXIT)) flags |= aof_leaf; #endif } else if (feature & FEATURE_SAVENAME) /* Dump a function name only if the function will have a stack frame... */ /* Without a frame the name isn't locatable (RISC OS and RISCiX kernel) */ codeseg_function_name(name, /* nargwords, unused on ARM */ m); if (k_fltregs_(m) != 0) flags |= aof_fpreg; dbg_enterproc(); fpdesc_startproc(); show_entry(name, flags); } #ifdef TARGET_IS_UNIX if (profile_option) { int32 loc = data_size(); gendcI(4, 0); move_register(R_IP, R_LR, 0); outinstr3(OP_BL, countroutine, 0); obj_symref(bindsym_(datasegment), xr_data, 0); AddCodeXref4(X_backaddrlit | (codebase + codep), bindsym_(datasegment), loc); outcodeword(loc, LIT_ADCON); } #endif fp_minus_sp = 0; returnlab = nextlabel(); saveregs_done = NO; argwordsbelowfp = realargwordsbelowfp = 0; intsavewordsbelowfp = savewordsabovefp = argstopopabovefp = 0; ipvalue.valid = NO; spareregs = 0; if (!(pcs_flags & PCS_REENTRANT)) spareregs |= regbit(R_IP); /* IP free on entry of non-reentrant fn */ if (!k_isvariadic_(m) && k_intregs_(m) < NARGREGS) spareregs |= M_ARGREGS & ~(regbit(k_intregs_(m)) - 1); spareregs &= regmask; /* only add registers that are really free */ } static void routine_saveregs(int32 m) { int32 intregs = k_intregs_(m), fltregs = k_fltregs_(m); saveregs_done = YES; if (m < 0) syserr(syserr_enter, (long)m); nargwords = k_argwords_(m); nregargwords = intregs + fp_arg_words*fltregs; #if DEBUG_X if (debugging(DEBUG_X)) desperate_codetrace(); #endif if (!(procflags & NONLEAF) || (pcs_flags & PCS_NOFP) || (procauxflags & bitoffnaux_(s_irq))) { int32 mask; if (feature & FEATURE_DONTUSE_LINKREG) regmask |= M_LR; if ((regmask & M_VARREGS) != 0 && (config & CONFIG_OPTIMISE_SPACE)) regmask |= M_LR; if (procauxflags & bitoffnaux_(s_irq)) { mask = regmask & (M_VARREGS | M_ARGREGS | regbit(R_IP) | M_LR); } else { mask = regmask & (M_VARREGS | M_LR); if (procflags & PROC_ARGPUSH) { bool maybevariadic = fltregs == 0 && intregs < nargwords; if (maybevariadic) { fpdesc_setinitoffset(-4-NARGREGS*4); PushRegs(M_ARGREGS); argstopopabovefp = NARGREGS; } else { argwordsbelowfp = nregargwords; mask |= (regbit(R_A1+intregs) - regbit(R_A1)); realargwordsbelowfp = nregargwords; } } else argwordsbelowfp = nregargwords; } if ((pcs_flags & PCS_REENTRANT) && (procflags & (PROC_USESADCONS+BLK0EXIT))) { outinstr(OP_MOVR | F_RD(R_IP) | R_SB); DestroyIP(); regmask |= regbit(R_SB); mask |= regbit(R_SB); fpdesc_enterproc(); PushRegs(mask); outinstr(OP_MOVR | F_RD(R_SB) | R_IP); } else if (mask != 0) { fpdesc_enterproc(); PushRegs(mask); } intsavewordsbelowfp = bitcount(mask & ~M_ARGREGS); if (procflags & PROC_ARGPUSH) fp_gen->saveargs(fltregs); fp_gen->calleesave(regmask); } else { bool saveargs = ((feature & FEATURE_SAVENAME) || (procflags & PROC_ARGPUSH)); bool maybevariadic = fltregs == 0 && intregs < nargwords && saveargs; int32 mask; savewordsabovefp = 1; if (pcs_flags & PCS_REENTRANT) { int32 fpoff; regmask |= regbit(R_SB); mask = (regmask & M_VARREGS) | regbit(R_FP); intsavewordsbelowfp = bitcount(mask) + 2; /* + sp and lr */ fpoff = intsavewordsbelowfp; outinstr(OP_MOVR | F_RD(R_IP) | R_SB); DestroyIP(); if (!maybevariadic) { PushRegs(regbit(R_SP) | M_LR | M_PC); argwordsbelowfp = nregargwords; if (saveargs) { mask |= (regbit(R_A1+intregs) - regbit(R_A1)); realargwordsbelowfp = nregargwords; } PushRegs(mask); if (saveargs) { fp_gen->saveargs(fltregs); fpoff += argwordsbelowfp; } outinstr(OP_MOVR | F_RD(R_SB) | R_IP); } else { PushRegs(M_ARGREGS); PushRegs(mask | regbit(R_SP) | M_LR | M_PC); outinstr(OP_MOVR | F_RD(R_SB) | R_IP); add_integer(R_IP, R_SP, 28+4*bitcount(mask), 0); outinstr(OP_STR | F_DOWN | F_RD(R_IP) | F_RN(R_IP) | 28); } add_integer(R_FP, R_SP, 4*fpoff, 0); } else { int32 fpoff = 4; mask = (regmask & M_VARREGS) | regbit(R_FP) | regbit(R_IP) | M_LR | M_PC; intsavewordsbelowfp = bitcount(mask) - 1; /* not pc */ outinstr(OP_MOVR | F_RD(R_IP) | R_SP); DestroyIP(); if (!maybevariadic) { argwordsbelowfp = nregargwords; if (saveargs) { mask |= (regbit(R_A1+intregs) - regbit(R_A1)); realargwordsbelowfp = nregargwords; } } else { fpoff += NARGREGS*4; PushRegs(M_ARGREGS); } PushRegs(mask); if (saveargs) fp_gen->saveargs(fltregs); add_integer(R_FP, R_IP, -fpoff, 0); } fp_gen->calleesave(regmask); if ((procflags & STACKCHECK) && /* not a leaf function and no large frame */ !no_stack_checks && /* not locally turned off (pragma -s) */ !(pcs_flags & PCS_NOSTACKCHECK)) /* not globally turned of (-apcs 3/noswst) */ { Symstr *name = stackoverflow; if (greatest_stackdepth > 256) { int32 n = eightbit_ceiling(greatest_stackdepth); add_integer(R_IP, R_SP, -n, 0); DestroyIP(); outinstr(OP_CMPR | F_RN(R_IP) | R_SL); name = stack1overflow; } else outinstr(OP_CMPR | F_RN(R_SP) | R_SL); outinstr3(OP_BL | C_MI, name, 0); } } spareregs |= regmask & (regbit(R_IP) | regbit(R_LR) | (regbit(R_V6+1) - regbit(R_V1))); /* Could add V8, and V7 if FP not used */ } static void PopRegs(int32 condition, int32 mask) { int32 setsp = mask & F_PSR; mask &= ~F_PSR; { unsigned count = (unsigned)bitcount(mask); unsigned maxcount = ldm_regs_max < 3 ? 3 : ldm_regs_max; int32 ldm = OP_LDMFD | condition | F_WRITEBACK | F_RN(R_SP); if (maxcount < count) { setsp |= MSBits(mask, maxcount); mask &= ~setsp; count -= maxcount; do { unsigned n = count > maxcount ? maxcount : count; int32 mask1 = LSBits(mask, n); mask ^= mask1; outinstr(ldm | mask1); fpdesc_notespchange(-4L * n); count -= n; } while (count != 0); mask = setsp; } if (mask & regbit(R_SP)) ldm &= ~F_WRITEBACK; outinstr(ldm | mask | setsp); fpdesc_notespchange(-bitcount(mask) * 4); } } static bool ReturnIsSingleInstruction(void) { /* This must be kept up to date with routine_exit(), or code will be broken in places which assume a return is a single instruction (principly in switches). To help, its structure follows that of routine_exit(). */ if ((procflags & NONLEAF) && (pcs_flags & PCS_INTERWORK)) return NO; if (target_stack_moves_once && !(procflags & NONLEAF)) return NO; #ifndef PROFILE_COUNTS_INLINE if (profile_option) return NO; #endif if (regmask & M_FVARREGS || procauxflags & bitoffnaux_(s_irq)) return NO; if ((procflags & NONLEAF) && !(pcs_flags & PCS_NOFP)) { return bitcount(regmask & M_VARREGS) + 3 <= ldm_regs_max; } else { if (realargwordsbelowfp != 0 || argstopopabovefp != 0 || (!(regmask & M_LR) && (regmask & M_VARREGS)) || bitcount(regmask & M_VARREGS)+1 > ldm_regs_max) return NO; return YES; } } /* Restore all registers for routine exit. Normally to_pc is set to give */ /* a return, but if unset causes LR to be restored for a TAILCALL. */ static void routine_exit(int32 condition, bool to_pc, int32 adjustsp) { int32 mask = regmask; int32 ldm_link = (to_pc == 0 || (pcs_flags & PCS_INTERWORK)) ? M_LR : procauxflags & bitoffnaux_(s_irq) ? M_LR : (pcs_flags & PCS_CALLCHANGESPSR) ? M_PC : M_PC | F_PSR; bool isleaf = !(procflags & NONLEAF) || !saveregs_done; if (!saveregs_done) mask = 0; /* Simulate J_SETSP, and its ARM elision before NONLEAF return. */ /* Use the condition mask to get the correct condition */ if (target_stack_moves_once && isleaf && saveregs_done) { /* don't update fp_minus_fp, since next basic block requires. */ condition_mask ^= condition; add_integer(R_SP, R_SP, greatest_stackdepth, 0); condition_mask ^= condition; } if (!saveregs_done) mask = 0; else if (feature & FEATURE_DONTUSE_LINKREG) mask |= M_LR; #ifndef PROFILE_COUNTS_INLINE if (profile_option) outinstr3(OP_BL | condition, fn_exit_sym, NO); #endif if ( !isleaf && !(pcs_flags & PCS_NOFP) && !(procauxflags & bitoffnaux_(s_irq))) { unsigned count = (unsigned)bitcount(mask & M_VARREGS); fp_gen->calleerestore(mask, condition, UseFP, 0); mask = (mask & M_VARREGS) | regbit(R_FP) | regbit(R_SP) | ldm_link; if (count+3 <= ldm_regs_max) outinstr(OP_LDMDB | condition | F_RN(R_FP) | mask); else { /* sp may already be right, but I can't know because SETSPs have been peepholed out before returns */ outinstr(OP_SUBN | condition | F_RD(R_SP) | F_RN(R_FP) | 4*(count + 3L)); PopRegs(condition, mask); } if (mask & M_PC) return; } else { int32 realmask = mask; int32 extra_adjust = 0; FP_RestoreBase base = UseSP_Adjust; if (procauxflags & bitoffnaux_(s_irq)) { if (adjustsp != 0) { condition_mask ^= condition; add_integer(R_SP, R_SP, adjustsp, 0); condition_mask ^= condition; } mask &= M_VARREGS | M_ARGREGS | regbit(R_IP) | M_LR; } else { if (realargwordsbelowfp == 0 && adjustsp != 0) { condition_mask ^= condition; add_integer(R_SP, R_SP, adjustsp, 0); condition_mask ^= condition; adjustsp = 0; } else if (adjustsp != 0) { base = UseSP_NoAdjust; extra_adjust = fp_gen->restoresize(mask); } mask &= M_VARREGS; } fp_gen->calleerestore(realmask, condition, base, adjustsp); if (realargwordsbelowfp != 0 || adjustsp != 0) { condition_mask ^= condition; add_integer(R_SP, R_SP, (4*realargwordsbelowfp)+adjustsp+extra_adjust, 0); condition_mask ^= condition; } if (!saveregs_done) /* nothing */; else if ((regmask & M_LR) == 0 || argstopopabovefp != 0) { mask |= (regmask & M_LR); if (mask != 0) /* AM: for odd circ's in tail recursion */ PopRegs(condition, mask); if (argstopopabovefp != 0) outinstr(OP_ADDN | condition | F_RD(R_SP) | F_RN(R_SP) | (4*argstopopabovefp)); } else { PopRegs(condition, mask | ldm_link); if (ldm_link & M_PC) return; } } if (to_pc) { if (procauxflags & bitoffnaux_(s_irq)) outinstr(OP_SUBN | condition | F_RD(R_PC) | F_RN(R_LR) | F_SCC | 4); else if ((pcs_flags & PCS_INTERWORK)) outinstr(OP_BX | condition | R_LR); else outinstr(OP_MOVR | condition | F_RD(R_PC) | R_LR | ((pcs_flags & PCS_CALLCHANGESPSR) ? 0 : F_SCC)); } } static void conditional_branch_to(int32 condition, LabelNumber *destination, bool bxxcase, int32 adjustsp) { condition = C_FROMQ(condition); if (destination == RETLAB) /* The test here is expected to detect all cases where the return ought */ /* to expand into just one instruction. Such cases are: 1. in a switch */ /* branchtable, 2. returns with fp regs to restore when we try (harder) */ /* to generate a single return sequence. The latter trades a little loss */ /* of speed for a (bigger?) improvement in code density. */ { if (adjustsp == 0 && ( (bxxcase && !ReturnIsSingleInstruction()) || /* AM: extra test to avoid generating conditional returns as (a) there will */ /* will probably be an unconditional one (main reason) and (b) slow on ARM-1 */ ( (condition != (C_ALWAYS^C_ALWAYS) || condition_mask != C_ALWAYS || lab_isset_(returnlab)) && (regmask & M_FVARREGS)!=0))) { destination = returnlab; } else { /* Only set a return label if this is an UNCONDITIONAL return. */ if (condition == (C_ALWAYS^C_ALWAYS) && condition_mask == C_ALWAYS && adjustsp == 0 && saveregs_done && !lab_isset_(returnlab)) setlabel(returnlab); dbg_return(codebase+codep); routine_exit(condition, YES, adjustsp); return; } } /* This is where I need to discriminate between the two sorts of things */ /* that I put in the ->frefs field of a label entry. */ if (lab_isset_(destination)) { int32 w = destination->u.defn; /* ->frefs */ outinstr(OP_B | condition | ((((w & 0x00ffffff) - codep - 8) >> 2) & 0x00ffffff)); } else { addfref_(destination, codep | LABREF_BRANCH); outinstr(OP_B | condition); } } /* Exported routines... */ static uint32 cond = Q_AL; static void show_instruction_1(Icode const *ic) { PendingOp cur; cur.ic = *ic; cur.dataflow = cur.ic.op & J_DEADBITS; cur.ic.op &= ~J_DEADBITS; /* remove dataflow bits */ cur.cond = cond; cur.peep = 0; if (is_asminstr(cur.ic.op)) translate_asm_instr (&cur); CheckJopcodeP(&cur, JCHK_MEM | JCHK_REGS | JCHK_SYSERR); /* While code is still in flux, we assume all STRW's coming here have */ /* J_ALIGN4&J_ALIGNWR set... */ /* /* apparently, they don't have ALIGNWR... */ { int32 op1 = cur.ic.op & (J_TABLE_BITS | J_ALIGNMENT); if (op1 == J_STRWK+J_ALIGN4 || op1 == J_STRWR+J_ALIGN4) cur.ic.op += J_STRK - J_STRWK; } switch (cur.ic.op) { case J_SETSP: { int32 oldstack = cur.ic.r2.i, newstack = cur.ic.r3.i; int32 diff = newstack - oldstack; if (fp_minus_sp != oldstack) syserr(syserr_setsp_confused, (long)fp_minus_sp, (long)oldstack, (long)newstack); fp_minus_sp = newstack; cur.ic.op = J_ADDK; cur.ic.r1.rr = R_SP; cur.ic.r2.rr = R_SP; cur.ic.r3.i = -diff; cur.dataflow = J_DEAD_R2; } break; case J_STACK: fp_minus_sp = cur.ic.r3.i; break; case J_PUSHM: fp_minus_sp += (4 * bitcount(cur.ic.r3.i)); break; case J_PUSHD: cur.ic.r3.i = 0; fp_minus_sp += 8; break; /* case J_PUSHR: should never reach armgen (removed in flowgraf.c) */ case J_PUSHF: cur.ic.r3.i = 0; fp_minus_sp += 4; break; case J_SUBK: if ((cur.peep & P_SETCC) == 0 || cur.ic.r3.i != 0) { cur.ic.op = J_ADDK; cur.ic.r3.i = -cur.ic.r3.i; } /* don't transform SUBS Rx, Ry, #0 into ADDS Rx, Ry, #0!!! */ break; case J_BICK: cur.ic.op = J_ANDK; cur.ic.r3.i = ~cur.ic.r3.i; break; case J_CMNK: if ((cur.peep & (P_SETPSR | P_SETCC)) == 0 || cur.ic.r3.i != 0) { cur.ic.op = J_CMPK; cur.ic.r3.i = -cur.ic.r3.i; } break; case J_SHLK+J_SIGNED: case J_SHLK+J_UNSIGNED: cur.ic.r3.i &= 255; if (cur.ic.r3.i >= 32) { cur.ic.op = J_MOVK; cur.dataflow &= ~J_DEAD_R2; cur.ic.r3.i = 0; } break; case J_SHRK+J_UNSIGNED: cur.ic.r3.i &= 255; /* allow LSR #32 if the PSR is altered */ if (cur.ic.r3.i > 32 || (cur.ic.r3.i == 32 && !(cur.peep & P_SETCC))) { cur.ic.op = J_MOVK; cur.dataflow &= ~J_DEAD_R2; cur.ic.r3.i = 0; } break; case J_SHRK+J_SIGNED: cur.ic.r3.i &= 255; if (cur.ic.r3.i > 32) cur.ic.r3.i = 32; /* allow ASR #32 */ break; } { bool flush = NO; switch (cur.ic.op & ~Q_MASK) { case J_ENTER: case J_ENDPROC: cond = Q_AL; flush = YES; break; case J_SAVE: case J_INFOLINE: case J_INFOBODY: case J_INFOSCOPE: case J_OPSYSK: case J_CALLK: case J_CALLR: case J_CALLI: #ifdef ARM_INLINE_ASSEMBLER case J_SWI: #endif case J_CASEBRANCH: case J_BXX: case J_WORD: case J_ORG: case J_VSTORE: case J_USE: flush = YES; break; case J_ADDK: if (target_stack_moves_once && cur.ic.r1.r == R_SP && cur.ic.r2.r == R_SP) flush = YES; break; case J_CONDEXEC: cond = cur.ic.op & Q_MASK; /*flush = YES; */ break; case J_LABEL: cond = Q_AL; case J_B: case J_STACK: /*flush = YES;*/ break; } if ((cur.ic.op & J_BASEALIGN4) && !j_is_adcon(cur.ic.op)) { cur.ic.op = cur.ic.op & ~J_BASEALIGN4; cur.peep |= (cur.ic.op & J_ALIGNMENT) < J_ALIGN4 ? P_BASEALIGNED : 0; } if (cur.ic.flags & SET_CC) cur.peep |= (P_CMPZ | P_SETCC); peephole_op(&cur, flush); if (flush) ldm_flush(); } } static bool ExpandInline(Symstr const *target, bool resinflags) { Icode op; if (target == bindsym_(exb_(sim.llfroml))) { INIT_IC(op, J_SHRK+J_SIGNED); op.r1.rr = R_A1+1; op.r2.rr = R_A1; op.r3.i = 31; show_instruction_1(&op); return YES; } if (target == bindsym_(exb_(sim.llfromu))) { INIT_IC(op, J_MOVK); op.r1.rr = R_A1+1; op.r3.i = 0; show_instruction_1(&op); return YES; } if (target == bindsym_(exb_(sim.lltol))) { return YES; } if (target == bindsym_(exb_(sim.lland))) { INIT_IC(op, J_ANDR+J_DEAD_R3); op.r1.rr = R_A1+1; op.r2.rr = R_A1+1; op.r3.rr = R_A1+3; show_instruction_1(&op); op.r1.rr = R_A1; op.r2.rr = R_A1; op.r3.rr = R_A1+2; show_instruction_1(&op); return YES; } if (target == bindsym_(exb_(sim.llor))) { INIT_IC(op, J_ORRR+J_DEAD_R3); op.r1.rr = R_A1+1; op.r2.rr = R_A1+1; op.r3.rr = R_A1+3; show_instruction_1(&op); op.r1.rr = R_A1; op.r2.rr = R_A1; op.r3.rr = R_A1+2; show_instruction_1(&op); return YES; } if (target == bindsym_(exb_(sim.lleor))) { INIT_IC(op, J_EORR+J_DEAD_R3); op.r1.rr = R_A1+1; op.r2.rr = R_A1+1; op.r3.rr = R_A1+3; show_instruction_1(&op); op.r1.rr = R_A1; op.r2.rr = R_A1; op.r3.rr = R_A1+2; show_instruction_1(&op); return YES; } if (target == bindsym_(exb_(sim.llnot))) { INIT_IC(op, J_NOTR); op.r1.rr = R_A1+1; op.r3.rr = R_A1+1; show_instruction_1(&op); op.r1.rr = R_A1; op.r3.rr = R_A1; show_instruction_1(&op); return YES; } if (target == bindsym_(exb_(sim.lladd)) && cond == Q_AL) { INIT_IC(op, J_ABINRR+J_DEAD_R3); op.flags = MKOP(A_ADD,CL_BIN)+SET_CC; op.r1.rr = R_A1; op.r2.rr = R_A1; op.r3.rr = R_A1+2; show_instruction_1(&op); op.flags = MKOP(A_ADC,CL_BIN); op.r1.rr = R_A1+1; op.r2.rr = R_A1+1; op.r3.rr = R_A1+3; show_instruction_1(&op); return YES; } if (target == bindsym_(exb_(sim.llsub)) && cond == Q_AL) { INIT_IC(op, J_ABINRR+J_DEAD_R3); op.flags = MKOP(A_SUB,CL_BIN)+SET_CC; op.r1.rr = R_A1; op.r2.rr = R_A1; op.r3.rr = R_A1+2; show_instruction_1(&op); op.flags = MKOP(A_SBC,CL_BIN); op.r1.rr = R_A1+1; op.r2.rr = R_A1+1; op.r3.rr = R_A1+3; show_instruction_1(&op); return YES; } if (target == bindsym_(exb_(sim.llrsb)) && cond == Q_AL) { INIT_IC(op, J_ABINRR+J_DEAD_R3); op.flags = MKOP(A_RSB,CL_BIN)+SET_CC; op.r1.rr = R_A1; op.r2.rr = R_A1; op.r3.rr = R_A1+2; show_instruction_1(&op); op.flags = MKOP(A_RSC,CL_BIN); op.r1.rr = R_A1+1; op.r2.rr = R_A1+1; op.r3.rr = R_A1+3; show_instruction_1(&op); return YES; } if (target == bindsym_(exb_(sim.llneg)) && cond == Q_AL) { INIT_IC(op, J_ABINRK); op.flags = MKOP(A_RSB+RN_CONST,CL_BIN)+SET_CC; op.r1.rr = R_A1; op.r2.rr = R_A1; op.r3.i = 0; show_instruction_1(&op); op.flags = MKOP(A_RSC+RN_CONST,CL_BIN); op.r1.rr = R_A1+1; op.r2.rr = R_A1+1; op.r3.i = 0; show_instruction_1(&op); return YES; } if (resinflags && cond == Q_AL) { if (target == bindsym_(exb_(sim.llcmpeq)) || target == bindsym_(exb_(sim.llcmpne)) || target == bindsym_(exb_(sim.llucmplt)) || target == bindsym_(exb_(sim.llucmple)) || target == bindsym_(exb_(sim.llucmpgt)) || target == bindsym_(exb_(sim.llucmpge))) { INIT_IC(op, J_CMPR+J_DEAD_R2+J_DEAD_R3); op.r1.rr = GAP; op.r2.rr = R_A2; op.r3.rr = R_A4; show_instruction_1(&op); INIT_IC(op, J_CONDEXEC+Q_EQ); show_instruction_1(&op); INIT_IC(op, J_CMPR+J_DEAD_R2+J_DEAD_R3+Q_EQ); op.r1.rr = GAP; op.r2.rr = R_A1; op.r3.rr = R_A3; show_instruction_1(&op); INIT_IC(op, J_CONDEXEC+Q_AL); show_instruction_1(&op); return YES; } if (target == bindsym_(exb_(sim.llscmpge)) || target == bindsym_(exb_(sim.llscmplt))) { INIT_IC(op, J_ABINRR+J_DEAD_R1+J_DEAD_R2+J_DEAD_R3); op.flags = MKOP(A_SUB,CL_BIN)+SET_CC; op.r1.rr = R_A1; op.r2.rr = R_A1; op.r3.rr = R_A1+2; show_instruction_1(&op); op.flags = MKOP(A_SBC,CL_BIN)+SET_CC; op.r1.rr = R_A1+1; op.r2.rr = R_A1+1; op.r3.rr = R_A1+3; show_instruction_1(&op); return YES; } if (target == bindsym_(exb_(sim.llscmple)) || target == bindsym_(exb_(sim.llscmpgt))) { INIT_IC(op, J_ABINRR+J_DEAD_R1+J_DEAD_R2+J_DEAD_R3); op.flags = MKOP(A_SUB,CL_BIN)+SET_CC; op.r1.rr = R_A1; op.r2.rr = R_A3; op.r3.rr = R_A1; show_instruction_1(&op); op.flags = MKOP(A_SBC,CL_BIN)+SET_CC; op.r1.rr = R_A2; op.r2.rr = R_A4; op.r3.rr = R_A2; show_instruction_1(&op); return YES; } } return NO; } void show_instruction(Icode const *const ic) { if (ic->op == J_SAVE && target_stack_moves_once) { Icode op; show_instruction_1(ic); INIT_IC(op, J_SETSP); op.r1.rr = 0; op.r2.i = fp_minus_sp; op.r3.i = fp_minus_sp+greatest_stackdepth; show_instruction_1(&op); return; } else if (ic->op == J_CALLK && ExpandInline(ic->r3.sym, ic->r2.i & K_RESULTINFLAGS)) { return; } else if (ic->op == J_TAILCALLK && ExpandInline(ic->r3.sym, ic->r2.i & K_RESULTINFLAGS)) { Icode op; INIT_IC(op, J_B); op.r3.l = RETLAB; show_instruction_1(&op); return; } show_instruction_1(ic); } /* the next routine is required for the machine independent codebuf.c */ void branch_round_literals(LabelNumber *m) { int32 c = condition_mask; condition_mask = C_ALWAYS; /* in case conditional instructions */ literal_pool_start = codebase+codep+4; conditional_branch_to(Q_AL, m, NO, 0); condition_mask = c; } static struct { char *name; Symstr const *sym; int32 op; } inlinetable[] = { #ifdef FORTRAN {"__r_sqrt", 0, OP_CPOP | CPDO_SINGLE | F_SQT}, {"__r_exp", 0, OP_CPOP | CPDO_SINGLE | F_EXP}, {"__r_log", 0, OP_CPOP | CPDO_SINGLE | F_LGN}, {"__r_lg10", 0, OP_CPOP | CPDO_SINGLE | F_LOG}, {"__r_sin", 0, OP_CPOP | CPDO_SINGLE | F_SIN}, {"__r_cos", 0, OP_CPOP | CPDO_SINGLE | F_COS}, {"__r_tan", 0, OP_CPOP | CPDO_SINGLE | F_TAN}, {"__r_asin", 0, OP_CPOP | CPDO_SINGLE | F_ASN}, {"__r_acos", 0, OP_CPOP | CPDO_SINGLE | F_ACS}, {"__r_atan", 0, OP_CPOP | CPDO_SINGLE | F_ATN}, {"__r_abs", 0, OP_CPOP | CPDO_SINGLE | F_ABS}, {"__d_sqrt", 0, OP_CPOP | CPDO_DOUBLE | F_SQT}, {"__d_exp", 0, OP_CPOP | CPDO_DOUBLE | F_EXP}, {"__d_log", 0, OP_CPOP | CPDO_DOUBLE | F_LGN}, {"__d_lg10", 0, OP_CPOP | CPDO_DOUBLE | F_LOG}, {"__d_tan", 0, OP_CPOP | CPDO_DOUBLE | F_TAN}, {"__d_asin", 0, OP_CPOP | CPDO_DOUBLE | F_ASN}, {"__d_acos", 0, OP_CPOP | CPDO_DOUBLE | F_ACS}, #endif {"__d_sin", 0, OP_CPOP | CPDO_DOUBLE | F_SIN}, {"__d_cos", 0, OP_CPOP | CPDO_DOUBLE | F_COS}, {"__d_atan", 0, OP_CPOP | CPDO_DOUBLE | F_ATN}, {"__d_abs", 0, OP_CPOP | CPDO_DOUBLE | F_ABS}, {0,0,0}}; static void initinlinetable(void) { int i; for (i = 0; ; i++) { char *name = inlinetable[i].name; if (name == NULL) return; inlinetable[i].sym = sym_insert_id(name); } } int32 target_inlinable(Binder const *b, int32 nargs) { if (nargs == 1) { int i; Symstr const *sym = bindsym_(b); for (i = 0; ; i++) { Symstr const *tsym = inlinetable[i].sym; if (tsym == 0) return 0; if (tsym == sym) return inlinetable[i].op; } } return 0; } #define TYPESPEC_DOUBLE typespecmap_(te_double) #define TYPESPEC_FLOAT typespecmap_(te_float) #define INFINITY 0x10000000 void localcg_newliteralpool(void) { if (in_code) { literal_pool_start = codebase+codep; in_code = NO; } mustlitby = INFINITY; } void localcg_endcode(void) { describe_literal_pool(); } void localcg_reinit(void) { ipvalue.valid = NO; spareregs = 0; fpdesc_init(); peephole_reinit(); KillKnownRegisterValues(AllIntRegs); } void mcdep_init(void) { ldm_reinit(); adconpool_init(); in_code = YES; literal_pool_number = 0; localcg_newliteralpool(); condition_mask = C_ALWAYS; if (fpu_type == fpu_amp) { fp_gen = &amp_gen; disass_addcopro(AMP_DisassCP); saved_fpreg_words = 1; fp_arg_words = 1; } else { fp_gen = &fpa_gen; saved_fpreg_words = 3; fp_arg_words = 2; } lib_reloc_sym = sym_insert_id("_Lib$Reloc$Off"); mod_reloc_sym = sym_insert_id("_Mod$Reloc$Off"); #ifndef PROFILE_COUNTS_INLINE fn_entry_sym = sym_insert_id("__fn_entry"); fn_exit_sym = sym_insert_id("__fn_exit"); #endif /* we must do the following initialisations once per module to */ /* avoid the store being reallocated (misapprehension & bug fix). */ fpliterals[0].val = fc_zero.d; fpliterals[1].val = fc_one.d; fpliterals[2].val = fc_two.d; fpliterals[3].val = real_of_string("3.0", TYPESPEC_DOUBLE); fpliterals[4].val = real_of_string("4.0", TYPESPEC_DOUBLE); fpliterals[5].val = real_of_string("5.0", TYPESPEC_DOUBLE); fpliterals[6].val = real_of_string("0.5", TYPESPEC_DOUBLE); fpliterals[7].val = real_of_string("10.0", TYPESPEC_DOUBLE); fpliterals[8].val = fc_zero.s; fpliterals[9].val = fc_one.s; fpliterals[10].val = fc_two.s; fpliterals[11].val = real_of_string("3.0", TYPESPEC_FLOAT); fpliterals[12].val = real_of_string("4.0", TYPESPEC_FLOAT); fpliterals[13].val = real_of_string("5.0", TYPESPEC_FLOAT); fpliterals[14].val = real_of_string("0.5", TYPESPEC_FLOAT); fpliterals[15].val = real_of_string("10.0", TYPESPEC_FLOAT); if (feature & FEATURE_DONTUSE_LINKREG) avoidallocating(R_LR); #ifdef TARGET_IS_UNIX avoidallocating(R_SL); #else if (!(pcs_flags & PCS_NOSTACKCHECK)) { avoidallocating(R_SL); asm_setregname(R_SL, "sl"); } else asm_setregname(R_SL, "v7"); #endif if (!(pcs_flags & PCS_NOFP)) { avoidallocating(R_FP); asm_setregname(R_FP, "fp"); } else asm_setregname(R_FP, "v8"); if (pcs_flags & PCS_REENTRANT) { avoidallocating(R_SB); asm_setregname((int)R_SB, "sb"); } else asm_setregname((int)R_SB, "v6"); initinlinetable(); peephole_init(); } void localcg_tidy(void) { dbg_finalise(); peephole_tidy(); } /* End of section arm/gen.c */
stardot/ncc
tests/2483.c
/* ARM C library test $RCSfile$. */ /* (Fault this tests for is /softfp only) */ /* Copyright (C) Advanced RISC Machines, 1997. All Rights Reserved */ /* SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <stdio.h> #include "testutil.h" #include "mathtest.h" #include "mathtest.c" static int count; #define do_something (count++) /* double-precision tests */ static void t2483a(void) { /* Test (QNaN == QNaN) -> false */ double_ints x; dset_to_qnan(&x); if (x.f == x.f) EQI(1, 0); return; } static void t2483b(void) { /* Test (QNaN != QNaN) -> true */ double_ints x; dset_to_qnan(&x); if (x.f != x.f) do_something; else EQI(1, 0); return; } static void t2483c(void) { /* Test (Inf == Inf) -> true */ double_ints x; dset_to_inf(&x); if (x.f == x.f) do_something; else EQI(1, 0); return; } static void t2483d(void) { /* Test (Inf != Inf) -> false */ double_ints x; dset_to_inf(&x); if (x.f != x.f) EQI(1, 0); return; } static void t2483e(void) { /* Test (1.0 == 1.0) -> true */ double_ints x; dset_to_one(&x); if (x.f == x.f) do_something; else EQI(1, 0); return; } static void t2483f(void) { /* Test (1.0 != 1.0) -> false */ double_ints x; dset_to_one(&x); if (x.f != x.f) EQI(1, 0); return; } /* single-precision tests */ static void t2483g(void) { /* Test (QNaN == QNaN) -> false */ float_int x; fset_to_qnan(&x); if (x.f == x.f) EQI(1, 0); } static void t2483h(void) { /* Test (QNaN != QNaN) -> true */ float_int x; fset_to_qnan(&x); if (x.f != x.f) do_something; else EQI(1, 0); } static void t2483i(void) { /* Test (Inf == Inf) -> true */ float_int x; fset_to_inf(&x); if (x.f == x.f) do_something; else EQI(1, 0); } static void t2483j(void) { /* Test (Inf != Inf) -> false */ float_int x; fset_to_inf(&x); if (x.f != x.f) EQI(1, 0); } static void t2483k(void) { /* Test (1.0 == 1.0) -> true */ float_int x; fset_to_one(&x); if (x.f == x.f) do_something; else EQI(1,0); } static void t2483l(void) { /* Test (1.0 != 1.0) -> false */ float_int x; fset_to_one(&x); if (x.f != x.f) EQI(1,0); } int main(void) { BeginTest(); t2483a(); /* these two are the actual bug */ t2483b(); /* " " " " " " */ t2483c(); /* these are just misc tests to check */ t2483d(); /* the fix doesn't break anything */ t2483e(); t2483f(); t2483g(); t2483h(); t2483i(); t2483j(); t2483k(); t2483l(); EndTest(); return 0; }
stardot/ncc
cfe/asmsyn.c
<filename>cfe/asmsyn.c /* * asmsyn.c: syntax analysis & parsing of ARM/Thumb inline assembler * Copyright (C) Advanced Risc Machines Ltd., 1997. All rights reserved. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <string.h> #include <ctype.h> #include "globals.h" #include "syn.h" #include "pp.h" #include "lex.h" #include "simplify.h" #include "bind.h" #include "sem.h" #include "aetree.h" #include "builtin.h" #include "vargen.h" #include "mcdep.h" #include "store.h" #include "errors.h" #include "aeops.h" #include "armops.h" #include "cgdefs.h" #include "inlnasm.h" #if defined(ARM_INLINE_ASSEMBLER) || defined(THUMB_INLINE_ASSEMBLER) typedef enum { Str_UpperCase = 1, Str_LowerCase = 2, Str_SubString = 4, Str_Opcode = Str_SubString, Str_Register = Str_LowerCase, Str_ShiftOp = Str_LowerCase, Str_Coproc = Str_LowerCase, Str_PSR = Str_SubString, Str_Null = 0 } StrFlags; typedef char *string; typedef uint32 ID; #define NIL_ID 0xffffffffU #define SizeofArr(arr) (sizeof (arr) / sizeof (arr [0])) #define R_ARMONLY 16 typedef enum { NO_SHIFT, CONST_SHIFT, REG_SHIFT } ShiftType; typedef enum { LVALUE, RVALUE, CONSTVALUE, OPND_RN } OpndType; typedef struct { const char * str; ID id; } IdentDef; static IdentDef const cc_tab[] = { /* increasing order! */ { "AL", CC_AL }, { "CC", CC_CC }, { "CS", CC_CS }, { "EQ", CC_EQ }, { "GE", CC_GE }, { "GT", CC_GT }, { "HI", CC_HI }, { "HS", CC_CS }, { "LE", CC_LE }, { "LO", CC_CC }, { "LS", CC_LS }, { "LT", CC_LT }, { "MI", CC_MI }, { "NE", CC_NE }, { "PL", CC_PL }, { "VC", CC_VC }, { "VS", CC_VS } }; static IdentDef const arm_mm_tab[] = { /* increasing order! */ { "DA", MM_DA }, { "DB", MM_DB }, { "EA", MM_DB | MM_STACK }, { "ED", MM_IB | MM_STACK }, { "FA", MM_DA | MM_STACK }, { "FD", MM_IA | MM_STACK }, { "IA", MM_IA }, { "IB", MM_IB } }; static IdentDef const arm_opcode_tab[] = { /* increasing order! */ { "ADC", MKOP (A_ADC, CL_BIN) }, { "ADD", MKOP (A_ADD, CL_BIN) }, { "AND", MKOP (A_AND, CL_BIN) }, { "BIC", MKOP (A_BIC, CL_BIN) }, { "CDP", MKOP (A_CDP, CL_COP) }, { "CMN", MKOP (A_CMN, CL_CMP) | SET_CC }, { "CMP", MKOP (A_CMP, CL_CMP) | SET_CC }, { "EOR", MKOP (A_EOR, CL_BIN) }, { "LDC", MKOP (A_LDC, CL_CMEM)}, { "LDM", MKOP (A_LDM, CL_LDM) }, { "LDR", MKOP (A_LDR, CL_MEM) }, { "MCR", MKOP (A_MCR, CL_COP) }, { "MLA", MKOP (A_MLA, CL_MUL) }, { "MOV", MKOP (A_MOV, CL_MOV) }, { "MRC", MKOP (A_MRC, CL_COP) }, { "MRS", MKOP (A_MRS, CL_PSR) }, { "MSR", MKOP (A_MSR, CL_PSR) }, { "MUL", MKOP (A_MUL, CL_MUL) }, { "MVN", MKOP (A_MVN, CL_MOV) }, { "NOP", MKOP (A_NOP, CL_NOP) }, { "ORR", MKOP (A_ORR, CL_BIN) }, { "RSB", MKOP (A_RSB, CL_BIN) }, { "RSC", MKOP (A_RSC, CL_BIN) }, { "SBC", MKOP (A_SBC, CL_BIN) }, { "SMLAL", MKOP (A_MLAL,CL_MUL) | M_SIGNED }, { "SMULL", MKOP (A_MULL,CL_MUL) | M_SIGNED }, { "STC", MKOP (A_STC, CL_CMEM)}, { "STM", MKOP (A_STM, CL_LDM) }, { "STR", MKOP (A_STR, CL_MEM) }, { "SUB", MKOP (A_SUB, CL_BIN) }, { "SWI", MKOP (A_SWI, CL_SWI) }, { "SWP", MKOP (A_SWP, CL_SWP) }, { "TEQ", MKOP (A_TEQ, CL_CMP) | SET_CC }, { "TST", MKOP (A_TST, CL_CMP) | SET_CC }, { "UMLAL", MKOP (A_MLAL,CL_MUL ) }, { "UMULL", MKOP (A_MULL,CL_MUL ) }, }; static IdentDef const thumb_opcode_tab[] = { /* increasing order! */ { "ADC", MKOP (A_ADC, CL_BIN) }, { "ADD", MKOP (A_ADD, CL_BIN) }, { "AND", MKOP (A_AND, CL_BIN) }, { "ASL", MKOP (T_LSL, CL_SH) }, { "ASR", MKOP (T_ASR, CL_SH) }, { "BIC", MKOP (A_BIC, CL_BIN) }, { "CMN", MKOP (A_CMN, CL_CMP) }, { "CMP", MKOP (A_CMP, CL_CMP) }, { "EOR", MKOP (A_EOR, CL_BIN) }, { "LDMIA", MKOP (A_LDM, CL_LDM) | MM_IA | M_WB }, { "LDR", MKOP (A_LDR, CL_MEM) }, { "LDRB", MKOP (A_LDR, CL_MEM) | M_BYTE }, { "LDRH", MKOP (A_LDR, CL_MEM) | M_HALF }, { "LDSB", MKOP (A_LDR, CL_MEM) | M_BYTE | M_SIGNED }, { "LDSH", MKOP (A_LDR, CL_MEM) | M_HALF | M_SIGNED }, { "LSL", MKOP (T_LSL, CL_SH) }, { "LSR", MKOP (T_LSR, CL_SH) }, { "MOV", MKOP (A_MOV, CL_MOV) }, { "MUL", MKOP (A_MUL, CL_MUL) }, { "MVN", MKOP (A_MVN, CL_MOV) }, { "NEG", MKOP (T_NEG, CL_MOV) }, { "NOP", MKOP (A_NOP, CL_NOP) }, { "ORR", MKOP (A_ORR, CL_BIN) }, { "POP", MKOP (A_LDM, CL_LDM) | MM_STACK | MM_IA | M_WB }, { "PUSH", MKOP (A_STM, CL_LDM) | MM_STACK | MM_DB | M_WB }, { "ROR", MKOP (T_ROR, CL_SH) }, { "SBC", MKOP (A_SBC, CL_BIN) }, { "STMIA", MKOP (A_STM, CL_LDM) | MM_IA | M_WB }, { "STR", MKOP (A_STR, CL_MEM) }, { "STRB", MKOP (A_STR, CL_MEM) | M_BYTE }, { "STRH", MKOP (A_STR, CL_MEM) | M_HALF }, { "SUB", MKOP (A_SUB, CL_BIN) }, { "SWI", MKOP (A_SWI, CL_SWI) }, { "TST", MKOP (A_TST, CL_CMP) }, }; static IdentDef const arm_shift_tab[] = { /* increasing order! */ { "ASL", SH_LSL }, { "ASR", SH_ASR }, { "LSL", SH_LSL }, { "LSR", SH_LSR }, { "ROR", SH_ROR }, { "RRX", SH_RRX } }; static IdentDef const register_tab[] = { /* increasing order! */ { "A1", R_A1}, { "A2", R_A2}, { "A3", R_A3}, { "A4", R_A4}, { "FP", R_FP | R_ARMONLY }, { "IP", R_IP}, { "LR", R_LR}, { "PC", R_PC}, { "PSR",R_PSR | R_ARMONLY }, { "R0", 0 }, { "R1", 1 }, { "R10", 10 }, { "R11", 11 }, { "R12", 12 }, { "R13", 13 }, { "R14", 14 }, { "R15", 15 }, { "R2", 2 }, { "R3", 3 }, { "R4", 4 }, { "R5", 5 }, { "R6", 6 }, { "R7", 7 }, { "R8", 8 }, { "R9", 9 }, { "SB", R_SB | R_ARMONLY }, { "SL", R_SL}, { "SP", R_SP}, { "V1", R_V1}, { "V2", R_V2}, { "V3", R_V3}, { "V4", R_V4}, { "V5", R_V5}, { "V6", R_V6}, { "V7", R_SL}, { "V8", R_FP} }; static IdentDef const psr_tab[] = { /* increasing order! */ { "CPSR", CPSR + PSR_CF }, { "CPSR_", CPSR }, { "SPSR", SPSR + PSR_CF }, { "SPSR_", SPSR } }; static IdentDef const coproc_id_tab[] = { /* increasing order! */ { "P0", 0 }, { "P1", 1 }, { "P10", 10 }, { "P11", 11 }, { "P12", 12 }, { "P13", 13 }, { "P14", 14 }, { "P15", 15 }, { "P2", 2 }, { "P3", 3 }, { "P4", 4 }, { "P5", 5 }, { "P6", 6 }, { "P7", 7 }, { "P8", 8 }, { "P9", 9 } }; static IdentDef const coproc_reg_tab[] = { /* increasing order! */ { "C0", 0 }, { "C1", 1 }, { "C10", 10 }, { "C11", 11 }, { "C12", 12 }, { "C13", 13 }, { "C14", 14 }, { "C15", 15 }, { "C2", 2 }, { "C3", 3 }, { "C4", 4 }, { "C5", 5 }, { "C6", 6 }, { "C7", 7 }, { "C8", 8 }, { "C9", 9 }, }; static const char *prefix_str(const char *str, const char *substr) { char ch1, ch2; do { ch1 = *str++; ch2 = *substr++; } while (ch1 == ch2 && ch1 != 0); if (ch1 != ch2 && ch2 != 0) return NULL; return str-1; } static void toupper_str(char *dst, const char *src, int len) { bool is_lower_str; const char *p; for (p = src; *p != 0; p++) if (isalpha(*p) && isupper(*p)) break; is_lower_str = (*p == 0); if (is_lower_str) while (--len) *dst++ = toupper(*src++); else while (--len) *dst++ = *src++; if (len == 0) dst[-1] = 0; } static ID read_substring(char const **str_ptr, IdentDef const ident[], int num_idents, StrFlags flags) { char const *str = *str_ptr; char const *id_str; uint32 low = 0, high = num_idents; while (high > low) { uint32 mid = (low + high) >> 1; if (strcmp(str, ident[mid].str) < 0) high = mid; else low = mid + 1; } if (low == 0) return NIL_ID; low--; id_str = prefix_str(str, ident[low].str); if (id_str == NULL || (!(flags & Str_SubString) && *id_str != '\0')) return NIL_ID; *str_ptr += id_str - str; return ident[low].id; } static ID read_string(char const *str_src, IdentDef const ident[], int num_idents, StrFlags flags) { char str_arr[32]; char *str = str_arr; if (flags & Str_LowerCase) toupper_str(str, str_src, sizeof(str_arr)); else strncpy(str, str_src, sizeof(str_arr)); return read_substring((char const **)&str, ident, num_idents, flags); } static ID read_cc(char const * *str_ptr) { ID cc = read_substring(str_ptr, cc_tab, SizeofArr(cc_tab), Str_Opcode); return (cc == NIL_ID) ? CC_AL : cc; } static ID arm_opcode(char const *opcode_str) { ID opcode; char str_arr[32]; char *str = str_arr; toupper_str(str, opcode_str, sizeof(str_arr)); opcode = read_substring((char const **)&str, arm_opcode_tab, SizeofArr(arm_opcode_tab), Str_Opcode); /* special case for B and BL since BLS/BLO conflicts with BL */ if (opcode == NIL_ID && str[0] == 'B') { int len = strlen(str); if (len == 1 || len == 3) { opcode = MKOP(A_B, CL_BR); str++; } else if (str[1] == 'L') { opcode = MKOP(A_BL, CL_BR); str += 2; } } if (opcode == NIL_ID) return opcode; opcode |= read_cc((char const **)&str); switch (INSTRCL(opcode)) { case CL_PSR: case CL_SWI: case CL_BR: case CL_COP: break; case CL_CMP: if (*str == 'P') { str++; opcode |= SET_PSR; if (!(config & CONFIG_26BIT)) cc_warn(asm_err_no_teqp); } break; case CL_MOV: case CL_BIN: case CL_MUL: case CL_MULL: if (*str == 'S') { str++; opcode |= SET_CC; } break; case CL_LDM: opcode |= read_substring((char const **)&str, arm_mm_tab, SizeofArr(arm_mm_tab), Str_Opcode); if (opcode & MM_STACK) { if (OPCODE(opcode) == A_STM) opcode ^= MM_IB; opcode ^= MM_STACK; } break; case CL_MEM: if (OPCODE(opcode) == A_LDR && *str == 'S') { str++; opcode |= M_SIGNED; } if (*str == 'B') { str++; opcode |= M_BYTE; } else if (*str == 'H') { str++; opcode |= M_HALF; } if (*str == 'T' && !(opcode & (M_SIGNED | M_HALF))) { str++; opcode |= M_TRANS; } break; case CL_SWP: if (*str == 'B') { str++; opcode |= M_BYTE; } break; case CL_CMEM: if (*str == 'L') { str++; opcode |= M_LONG; } break; case CL_NOP: break; default: return NIL_ID; } return (*str == '\0') ? opcode : NIL_ID; } static ID thumb_opcode(char const *opcode_str) { ID opcode; char str_arr[32]; char *str = str_arr; toupper_str(str, opcode_str, sizeof(str_arr)); opcode = read_substring((char const **)&str, thumb_opcode_tab, SizeofArr(thumb_opcode_tab), Str_Opcode); /* special case for B and BL since BLS/BLO conflicts with BL */ if (opcode == NIL_ID && str[0] == 'B') { int len = strlen(str); if (len == 1 || len == 3) { opcode = MKOP(A_B, CL_BR); str++; opcode |= read_cc((char const **)&str); } else if (str[1] == 'L') { opcode = MKOP(A_BL, CL_BR); str += 2; opcode |= CC_AL; } } else opcode |= CC_AL; return (*str == '\0') ? opcode : NIL_ID; } static void NoteFileLine(FileLine *fl) { *fl = curlex.fl; fl->p = dbg_notefileline(*fl); } static ID rd_arm_phys_reg(void) { ID reg; if (curlex.sym != s_identifier) { checkfor_ket(s_identifier); return NIL_ID; } reg = read_string(symname_(curlex.a1.sv), register_tab, SizeofArr(register_tab), Str_Register); #ifdef THUMB_INLINE_ASSEMBLER if (reg & R_ARMONLY) reg = NIL_ID; #endif if (reg == NIL_ID) cc_err(asm_err_bad_physreg, symname_(curlex.a1.sv)); nextsym(); return reg & 15; } static Expr *rd_arm_opnd(OpndType opnd_type) { Expr *e; if (opnd_type != CONSTVALUE && curlex.sym == s_identifier) /* TODO: C++ */ { ID reg = read_string(symname_(curlex.a1.sv), register_tab, SizeofArr(register_tab), Str_Register); #ifdef THUMB_INLINE_ASSEMBLER if (reg & R_ARMONLY) reg = NIL_ID; #endif if (reg != NIL_ID) { nextsym(); e = mkintconst(te_uint, reg & 15, 0); h0_(e) = s_register; return e; } } e = rd_expr(UPTOCOMMA); if (e == 0) return errornode; if (opnd_type == LVALUE) { e = ensurelvalue(e, s_asm); if (h0_(e) == s_error) return errornode; } else e = coerceunary(e); e = optimise0(e); if (e == 0) return errornode; if (opnd_type == CONSTVALUE && h0_(e) != s_integer) { moan_nonconst(e, asm_non_const, asm_nonconst1, asm_nonconst2); return errornode; } return e; } static Expr *rd_thumb_opnd(OpndType opnd_type) { if (opnd_type == OPND_RN) { if (curlex.sym == s_hash) { nextsym(); opnd_type = CONSTVALUE; } else opnd_type = RVALUE; } return rd_arm_opnd(opnd_type); } static Expr *rd_coproc_reg(void) { ID reg; if (curlex.sym != s_identifier) { checkfor_ket(s_identifier); return errornode; } reg = read_string(symname_(curlex.a1.sv), coproc_reg_tab, SizeofArr(coproc_reg_tab), Str_Register); if (reg == NIL_ID) { cc_err(asm_err_bad_physreg, symname_(curlex.a1.sv)); nextsym(); return errornode; } nextsym(); return mkintconst(te_uint, reg, 0); } static void rd_opnd_rn(AsmInstr *a, ShiftType shift_type) { ID shift; if (curlex.sym == s_hash) { nextsym(); asmopnd3_(a) = rd_arm_opnd(CONSTVALUE); asmopcode_(a) |= RN_CONST; } else { asmopnd3_(a) = rd_arm_opnd(RVALUE); if (shift_type == NO_SHIFT || curlex.sym != s_comma) { if (h0_(asmopnd3_(a)) == s_integer) asmopcode_(a) |= RN_CONST; else asmopcode_(a) |= RN_REG; return; } nextsym(); if (curlex.sym != s_identifier) { cc_err(asm_err_expected_shift); asmopnd4_(a) = errornode; return; } shift = read_string(symname_(curlex.a1.sv), arm_shift_tab, SizeofArr(arm_shift_tab), Str_ShiftOp); if (shift == NIL_ID) { cc_err(asm_err_bad_shift, symname_(curlex.a1.sv)); asmopnd4_(a) = errornode; return; } nextsym(); if (shift == SH_RRX) { asmopcode_(a) |= shift; asmopnd4_(a) = mkintconst(te_uint, 0, 0); asmopcode_(a) |= RN_SHIFT; return; } if (curlex.sym == s_hash) { nextsym(); shift_type = CONST_SHIFT; } asmopnd4_(a) = rd_arm_opnd(shift_type == REG_SHIFT ? RVALUE : CONSTVALUE); if (h0_(asmopnd4_(a)) == s_integer) { int shiftval = intval_(asmopnd4_(a)); /* Convert LSL, LSR, ASR, ROR #0 to no shift */ if (shiftval == 0) { asmopcode_(a) |= RN_REG; return; } /* LSR #32 and ASR #32 allowed, otherwise complain */ if (shiftval == 32 && (shift == SH_LSR || shift == SH_ASR)) shiftval = 0; if (shiftval < 0 || shiftval >= 32) { cc_err(asm_err_bad_shiftval, shiftval); asmopnd4_(a) = errornode; } asmopcode_(a) |= shift | RN_SHIFT; } else asmopcode_(a) |= shift | RN_SHIFT_REG; } return; } static void rd_binary_instr(AsmInstr *a) { asmopnd1_(a) = rd_arm_opnd(LVALUE); checkfor_ket(s_comma); asmopnd2_(a) = rd_arm_opnd(RVALUE); checkfor_ket(s_comma); rd_opnd_rn(a, REG_SHIFT); } static void rd_compare_instr(AsmInstr *a) { asmopnd2_(a) = rd_arm_opnd(RVALUE); checkfor_ket(s_comma); rd_opnd_rn(a, REG_SHIFT); } static void rd_move_instr(AsmInstr *a) { asmopnd1_(a) = rd_arm_opnd(RVALUE); checkfor_ket(s_comma); rd_opnd_rn(a, REG_SHIFT); } static void rd_mem_instr(AsmInstr *a) { bool is_half_or_signed = asmopcode_(a) & (M_SIGNED | M_HALF); if (is_half_or_signed && !(config & CONFIG_HALFWORD_SPT)) cc_err(asm_err_no_halfword); asmopnd1_(a) = rd_arm_opnd(OPCODE (asmopcode_(a)) == A_LDR ? LVALUE : RVALUE); checkfor_ket(s_comma); checkfor_ket(s_lbracket); asmopnd2_(a) = rd_arm_opnd(RVALUE); if (curlex.sym == s_comma) { nextsym(); asmopcode_(a) |= M_PREIDX; if (curlex.sym == s_minus) nextsym(); else asmopcode_(a) |= M_UPIDX; rd_opnd_rn(a, is_half_or_signed ? NO_SHIFT : CONST_SHIFT); checkfor_ket(s_rbracket); if (curlex.sym == s_boolnot) { nextsym(); asmopcode_(a) |= M_WB; } if (asmopcode_(a) & M_TRANS) { cc_err(asm_err_ldrt_adrmode); asmopnd1_(a) = errornode; } } else { checkfor_ket(s_rbracket); if (curlex.sym != s_comma) { /* no RN, so default to LDR r0, [r1, #0] or LDRT r0, [r1], #0 */ asmopcode_(a) |= RN_CONST; asmopnd3_(a) = mkintconst(te_uint, 0, 0); if (!(asmopcode_(a) & M_TRANS)) asmopcode_(a) |= M_PREIDX; else asmopcode_(a) |= M_WB; return; } asmopcode_(a) |= M_WB; nextsym(); if (curlex.sym == s_minus) nextsym(); else asmopcode_(a) |= M_UPIDX; rd_opnd_rn(a, is_half_or_signed ? NO_SHIFT : CONST_SHIFT); } } static uint32 rd_reglist(void) { uint32 regmask = 0; checkfor_ket(s_lbrace); while (curlex.sym != s_rbrace) { ID reg1, reg2; reg1 = rd_arm_phys_reg(); if (curlex.sym == s_minus) { nextsym(); reg2 = rd_arm_phys_reg(); if ((reg1 | reg2 | regmask) == NIL_ID) regmask = NIL_ID; else if (reg2 > reg1) regmask |= (2 << reg2) - (1 << reg1); else regmask |= (2 << reg1) - (1 << reg2); } else if (reg1 != NIL_ID) regmask |= 1 << reg1; else regmask = NIL_ID; if (curlex.sym != s_comma) break; nextsym(); } checkfor_ket(s_rbrace); return regmask; } static void rd_ldm_instr(AsmInstr *a) { uint32 regmask; asmopnd1_(a) = rd_arm_opnd(LVALUE); if (curlex.sym == s_boolnot) { nextsym(); asmopcode_(a) |= M_WB; } checkfor_ket(s_comma); regmask = rd_reglist(); if (curlex.sym == s_xor) { asmopcode_(a) |= SET_CC; /* is this a good idea? */ nextsym(); } if (regmask == NIL_ID) asmopnd3_(a) = errornode; else asmopnd3_(a) = mkintconst(te_uint, regmask, 0); } static void rd_mul_instr(AsmInstr *a) { uint32 op = OPCODE(asmopcode_(a)); if (!(config & CONFIG_LONG_MULTIPLY) && (op == A_MULL || op == A_MLAL)) cc_err(asm_err_no_longmul); asmopnd1_(a) = rd_arm_opnd(LVALUE); checkfor_ket(s_comma); asmopnd2_(a) = rd_arm_opnd(INSTRCL (asmopcode_(a)) == CL_MULL ? LVALUE : RVALUE); checkfor_ket(s_comma); if (OPCODE(asmopcode_(a)) == A_MUL) { if (curlex.sym == s_hash) { nextsym(); asmopnd3_(a) = rd_arm_opnd(CONSTVALUE); } else asmopnd3_(a) = rd_arm_opnd(RVALUE); } else { asmopnd3_(a) = rd_arm_opnd(RVALUE); checkfor_ket(s_comma); asmopnd4_(a) = rd_arm_opnd(RVALUE); } } static void rd_psr_field(AsmInstr *a, bool flags_only) { const char *str = symname_(curlex.a1.sv); ID psr; if (curlex.sym != s_identifier) { cc_err(asm_err_expected_psr); asmopnd2_(a) = errornode; nextsym(); return; } psr = read_substring(&str, psr_tab, SizeofArr (psr_tab), Str_PSR); if (flags_only && (psr & PSR_FLAGS) != PSR_CF) psr = NIL_ID; if ((psr & PSR_FLAGS) == 0) /* read: CSPR_ or SPSR_ */ { if (StrEq(str, "flg")) { str += 3; psr |= PSR_F; } else if (StrEq(str, "ctl")) { str += 3; psr |= PSR_C; } else if (StrEq(str, "all")) { str += 3; psr |= PSR_CF; } else while (1) { /* read the cxsf flags in any order */ if (~psr & PSR_C && *str == 'c') { str++; psr |= PSR_C; continue; } if (~psr & PSR_X && *str == 'x') { str++; psr |= PSR_X; continue; } if (~psr & PSR_S && *str == 's') { str++, psr |= PSR_S; continue; } if (~psr & PSR_F && *str == 'f') { str++; psr |= PSR_F; continue; } break; } } if (psr == NIL_ID || *str != '\0') { cc_err(asm_err_bad_psrfield, symname_(curlex.a1.sv)); asmopnd2_(a) = errornode; return; } nextsym(); asmopnd2_(a) = mkintconst(te_uint, psr, 0); } static void rd_psr_instr(AsmInstr *a) { if (!(config & CONFIG_32BIT)) cc_err(asm_err_no_mrs); if (OPCODE(asmopcode_(a)) == A_MRS) { asmopnd1_(a) = rd_arm_opnd(LVALUE); checkfor_ket(s_comma); rd_psr_field(a, YES); } else /* MSR */ { rd_psr_field(a, NO); checkfor_ket(s_comma); rd_opnd_rn(a, NO_SHIFT); } } static void rd_swi_instr(AsmInstr *a) { uint32 in = 0, out = 0, corrupt = 0; asmopnd1_(a) = rd_arm_opnd(CONSTVALUE); if (curlex.sym == s_comma) { nextsym(); in = rd_reglist(); } if (curlex.sym == s_comma) { nextsym(); out = rd_reglist(); } if (curlex.sym == s_comma) { nextsym(); corrupt = rd_reglist(); } if ((in | out | corrupt) == NIL_ID) { asmopnd1_(a) = errornode; return; } asmopnd2_(a) = mkintconst(te_uint, in, 0); asmopnd3_(a) = mkintconst(te_uint, out, 0); asmopnd4_(a) = mkintconst(te_uint, corrupt, 0); if ((out | corrupt) & regbit(R_PSR)) asmopcode_(a) |= SET_CC; } static void rd_swp_instr(AsmInstr *a) { asmopnd1_(a) = rd_arm_opnd(LVALUE); checkfor_ket(s_comma); asmopnd3_(a) = rd_arm_opnd(RVALUE); checkfor_ket(s_comma); checkfor_ket(s_lbracket); asmopnd2_(a) = rd_arm_opnd(RVALUE); checkfor_ket(s_rbracket); } static void rd_branch_instr(AsmInstr *a) { if (OPCODE(asmopcode_(a)) == A_B) { if (curlex.sym != s_identifier) { cc_err(syn_err_no_label); return; } asmopnd1_(a) = (Expr*) label_reference(curlex.a1.sv); nextsym(); } else { uint32 in = 0, out = 0, corrupt = reglist(R_A1, 4) | regbit(R_IP);; if (curlex.sym != s_identifier) { cc_err(asm_err_fn_id); asmopnd1_(a) = errornode; } else { Expr *fn = (Expr *) findbinding(curlex.a1.sv, NULL, ALLSCOPES); if (fn != NULL) { /* generate mangled name for C++ if possible */ fn = mkunary(s_addrof, fn); fn = coerceunary(fn); asmopnd1_(a) = arg1_(fn); } } if (asmopnd1_(a) == 0) { cc_err(asm_err_fn_notfound, symname_(curlex.a1.sv)); asmopnd1_(a) = errornode; } nextsym(); if (curlex.sym == s_comma) { nextsym(); in = rd_reglist(); } if (curlex.sym == s_comma) { nextsym(); out = rd_reglist(); } if (curlex.sym == s_comma) { nextsym(); corrupt = rd_reglist(); } if ((in | out | corrupt) == NIL_ID) { asmopnd1_(a) = errornode; return; } corrupt |= regbit(R_LR); /* BL always corrupts LR */ corrupt &= ~out; /* result registers cannot be corrupted */ asmopnd2_(a) = mkintconst(te_uint, in, 0); asmopnd3_(a) = mkintconst(te_uint, out, 0); asmopnd4_(a) = mkintconst(te_uint, corrupt, 0); if ((out | corrupt) & regbit(R_PSR)) asmopcode_(a) |= SET_CC; } } static int rd_coproc_id(void) { ID coproc; if (curlex.sym != s_identifier) { cc_err(asm_err_expected_coproc); nextsym(); return NIL_ID; } coproc = read_string(symname_(curlex.a1.sv), coproc_id_tab, SizeofArr (coproc_id_tab), Str_Coproc); if (coproc == NIL_ID) cc_err(asm_err_unknown_coproc, symname_(curlex.a1.sv)); else coproc <<= 8; nextsym(); return coproc; } static int rd_coproc_op(uint32 max) { Expr *op = rd_arm_opnd(CONSTVALUE); uint32 opcode; if (op == errornode) return NIL_ID; opcode = intval_(op); if (opcode >= max) { cc_err(asm_err_coproc_op_range, opcode); return NIL_ID; } return opcode; } static void rd_coproc_dataop(AsmInstr *a) { uint32 coproc, op; coproc = rd_coproc_id(); checkfor_ket(s_comma); if (OPCODE(asmopcode_(a)) == A_CDP) { op = rd_coproc_op(16); coproc |= (op == NIL_ID) ? NIL_ID : op << 20; checkfor_ket(s_comma); asmopnd1_(a) = rd_coproc_reg(); } else { op = rd_coproc_op(8); coproc |= (op == NIL_ID) ? NIL_ID : op << 21; checkfor_ket(s_comma); asmopnd1_(a) = rd_arm_opnd(OPCODE(asmopcode_(a)) == A_MRC ? LVALUE : RVALUE); } checkfor_ket(s_comma); asmopnd2_(a) = rd_coproc_reg(); checkfor_ket(s_comma); asmopnd3_(a) = rd_coproc_reg(); if (curlex.sym == s_comma) { nextsym(); op = rd_coproc_op(8); } else op = 0; coproc |= (op == NIL_ID) ? NIL_ID : op << 5; if (coproc == NIL_ID) asmopnd4_(a) = errornode; else asmopnd4_(a) = mkintconst(te_uint, coproc, 0); } static void rd_coproc_memop(AsmInstr *a) { uint32 coproc; coproc = rd_coproc_id(); checkfor_ket(s_comma); asmopnd1_(a) = rd_coproc_reg(); checkfor_ket(s_comma); checkfor_ket(s_lbracket); asmopcode_(a) |= RN_CONST; asmopnd2_(a) = rd_arm_opnd(RVALUE); if (curlex.sym == s_comma) { nextsym(); if (curlex.sym == s_hash) nextsym(); asmopcode_(a) |= M_PREIDX; asmopnd3_(a) = rd_arm_opnd(CONSTVALUE); checkfor_ket(s_rbracket); if (curlex.sym == s_boolnot) { nextsym(); asmopcode_(a) |= M_WB; } } else { checkfor_ket(s_rbracket); if (curlex.sym != s_comma) /* no offset, so default to [rx, #0] */ { asmopcode_(a) |= M_PREIDX; asmopnd3_(a) = mkintconst(te_uint, 0, 0); } else { asmopcode_(a) |= M_WB; nextsym(); if (curlex.sym == s_hash) nextsym(); asmopnd3_(a) = rd_arm_opnd(CONSTVALUE); } } if (coproc == NIL_ID) asmopnd4_(a) = errornode; else asmopnd4_(a) = mkintconst(te_uint, coproc, 0); } static void rd_thumb_binary(AsmInstr *a) { asmopnd1_(a) = asmopnd2_(a) = rd_thumb_opnd(LVALUE); checkfor_ket(s_comma); if (curlex.sym == s_hash) { nextsym(); asmopnd3_(a) = rd_thumb_opnd(CONSTVALUE); } else { asmopnd3_(a) = rd_thumb_opnd(RVALUE); if (curlex.sym == s_comma) { nextsym(); asmopnd2_(a) = asmopnd3_(a); asmopnd3_(a) = rd_thumb_opnd(OPND_RN); } } } static void rd_thumb_move(AsmInstr *a) { asmopnd1_(a) = rd_thumb_opnd(LVALUE); checkfor_ket(s_comma); asmopnd3_(a) = rd_thumb_opnd(OPND_RN); } static void rd_thumb_compare(AsmInstr *a) { asmopnd2_(a) = rd_thumb_opnd(RVALUE); checkfor_ket(s_comma); asmopnd3_(a) = rd_thumb_opnd(OPND_RN); } static void rd_thumb_mem(AsmInstr *a) { asmopnd1_(a) = rd_thumb_opnd(OPCODE(asmopcode_(a)) == A_LDR ? LVALUE : RVALUE); checkfor_ket(s_comma); checkfor_ket(s_lbracket); asmopnd2_(a) = rd_thumb_opnd(RVALUE); if (curlex.sym == s_comma) { nextsym(); asmopnd3_(a) = rd_thumb_opnd(OPND_RN); } else asmopnd3_(a) = mkintconst(te_uint, 0, 0); checkfor_ket(s_rbracket); } static void rd_thumb_ldm(AsmInstr *a) { uint32 regmask; if (asmopcode_(a) & MM_STACK) { asmopnd1_(a) = mkintconst(te_uint, R_SP, 0); h0_(asmopnd1_(a)) = s_register; } else { asmopnd1_(a) = rd_thumb_opnd(LVALUE); checkfor_ket(s_boolnot); checkfor_ket(s_comma); } regmask = rd_reglist(); asmopnd3_(a) = errornode; if (regmask != NIL_ID) { uint32 mask_allowed = 0xFF; if (asmopcode_(a) & MM_STACK) mask_allowed |= OPCODE(asmopcode_(a)) == A_LDM ? 0x8000 : 0x4000; if (regmask & ~mask_allowed) cc_err(asm_err_ldm_badlist); else asmopnd3_(a) = mkintconst(te_uint, regmask, 0); } asmopcode_(a) &= ~MM_STACK; } static void rd_thumb_swi(AsmInstr *a) { rd_swi_instr(a); } static void rd_thumb_branch(AsmInstr *a) { rd_branch_instr(a); } static AsmInstr *rd_arm_instr(void) { ID op; AsmInstr *a; a = mk_asminstr(); NoteFileLine(&asmfl_(a)); if (peepsym() == s_colon) /* found a label */ { LabBind *lab = label_define(curlex.a1.sv); /* if (lab != 0) syn_setlab(lab, synscope); */ op = A_LABEL + CC_NOT; asmopnd1_(a) = (Expr*) lab; nextsym(); } else op = arm_opcode(symname_(curlex.a1.sv)); asmopcode_(a) = op; if (op == NIL_ID) { cc_err(asm_err_bad_opcode, symname_(curlex.a1.sv)); nextsym(); return 0; } nextsym(); switch (INSTRCL(op)) { case CL_MOV: rd_move_instr(a); break; case CL_CMP: rd_compare_instr(a); break; case CL_BIN: rd_binary_instr(a); break; case CL_MEM: rd_mem_instr(a); break; case CL_LDM: rd_ldm_instr(a); break; case CL_MUL: case CL_MULL: rd_mul_instr(a); break; case CL_PSR: rd_psr_instr(a); break; case CL_SWI: rd_swi_instr(a); break; case CL_SWP: rd_swp_instr(a); break; case CL_BR: rd_branch_instr(a); break; case CL_COP: rd_coproc_dataop(a); break; case CL_CMEM: rd_coproc_memop(a); break; default: break; } if (asmopnd1_(a) == errornode || asmopnd2_(a) == errornode || asmopnd3_(a) == errornode || asmopnd4_(a) == errornode) return 0; return a; } static AsmInstr *rd_thumb_instr(void) { ID op; AsmInstr *a; a = mk_asminstr(); NoteFileLine(&asmfl_(a)); if (peepsym() == s_colon) /* found a label */ { LabBind *lab = label_define(curlex.a1.sv); /* if (lab != 0) syn_setlab(lab, synscope); */ op = A_LABEL + CC_NOT; asmopnd1_(a) = (Expr*) lab; nextsym(); } else op = thumb_opcode(symname_(curlex.a1.sv)); asmopcode_(a) = op; if (op == NIL_ID) { cc_err(asm_err_bad_opcode, symname_(curlex.a1.sv)); nextsym(); return 0; } nextsym(); switch (INSTRCL(op)) { case CL_MOV: rd_thumb_move(a); break; case CL_CMP: rd_thumb_compare(a); break; case CL_BIN: case CL_MUL: case CL_SH: rd_thumb_binary(a); break; case CL_MEM: rd_thumb_mem(a); break; case CL_LDM: rd_thumb_ldm(a); break; case CL_SWI: rd_thumb_swi(a); break; case CL_BR: rd_branch_instr(a); break; default: break; } if (asmopnd1_(a) == errornode || asmopnd2_(a) == errornode || asmopnd3_(a) == errornode || asmopnd4_(a) == errornode) return 0; return a; } static AsmInstr *rd_asm_instr_list(bool quoted) { AsmInstr *ls = 0, *le = 0, *a; AEop endsym = quoted ? s_quote : s_rbrace; if (quoted) checkfor_ket(s_quote); for (;;) { if (curlex.sym == s_identifier) { #ifdef ARM_INLINE_ASSEMBLER a = rd_arm_instr(); #endif #ifdef THUMB_INLINE_ASSEMBLER a = rd_thumb_instr(); #endif if (a != 0) { if (le) le->cdr = a; else ls = a; le = a; if (OPCODE(asmopcode_(a)) == A_LABEL) continue; } else /* syntax error: read till a save point */ while (curlex.sym != endsym && curlex.sym != s_semicolon && curlex.sym != s_eol && curlex.sym != s_eof) nextsym(); } if (curlex.sym == endsym || curlex.sym == s_eof) break; if (curlex.sym == s_eol || curlex.sym == s_semicolon) nextsym(); else checkfor_2ket(s_semicolon, quoted ? s_quote : s_eol); } if (quoted) checkfor_ket(s_quote); return ls; } Cmd *rd_asm_block(void) { FileLine fl; AsmInstr *asmlist = 0; NoteFileLine(&fl); nextsym(); asm_mode = ASM_BLOCK; checkfor_ket(s_lbrace); asmlist = rd_asm_instr_list(NO); asm_mode = ASM_NONE; while (curlex.sym == s_eol) nextsym(); checkfor_ket(s_rbrace); return mk_cmd_e(s_asm, fl, (Expr *)asmlist); } #endif Expr *rd_asm_decl(void) { #ifdef TARGET_HAS_INLINE_ASSEMBLER FileLine fl; AsmInstr *asmlist = 0; NoteFileLine(&fl); nextsym(); asm_mode = ASM_STRING; checkfor_ket(s_lpar); while (curlex.sym == s_eol) nextsym(); asmlist = rd_asm_instr_list(YES); asm_mode = ASM_NONE; while (curlex.sym == s_eol) nextsym(); checkfor_ket(s_rpar); checkfor_ket(s_semicolon); return (Expr*) mk_cmd_e(s_asm, fl, (Expr *)asmlist); #else { Expr *s = 0; nextsym(); checkfor_ket(s_lpar); if (curlex.sym == s_string) s = rd_ANSIstring(); else checkfor_ket(s_string); checkfor_ket(s_rpar); checkfor_delimiter_ket(s_semicolon, "", ""); cc_warn(syn_warn_ineffective_asm_decl); return s; } #endif }
stardot/ncc
tests/2277.c
<reponame>stardot/ncc /* * ARM C compiler regression test $RCSfile$ * Copyright (C) 1997 Advanced Risc Machines Ltd. All rights reserved. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include "testutil.h" /********************* 2277 ***********************/ /* may syserr */ __inline double f1_2277(double x) { return x + 1; } void g1_2277() { f1_2277(1); } double h1_2277() { return f1_2277(1); } __inline float f2_2277(float x) { return x + 1; } void g2_2277() { f2_2277(1); } float h2_2277() { return f2_2277(1); } void t_2277(void) { EQD(h1_2277(), 2.0); EQD(h2_2277(), 2.0); } /********************* ***********************/ int main(void) { BeginTest(); t_2277(); EndTest(); return 0; }
stardot/ncc
mip/arm_version.c
/* * mip/version.c * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Advanced RISC Machines Limited, 1991-1992. * Copyright (C) Codemist Ltd, 1987-1994. * SPDX-Licence-Identifier: Apache-2.0 * Defines the version string and banner for the Codemist or OEM compiler. */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifdef __STDC__ # include <string.h> #else # include <strings.h> #endif #include "globals.h" /* for TARGET_MACHINE */ #include "version.h" #include "fevsn.h" #include "mipvsn.h" #include "mcvsn.h" #ifndef __DATE__ # include "datenow.h" #endif #ifndef __TIME__ # define __TIME__ "" #endif #ifdef __STDC__ # ifndef NO_STATIC_BANNER # define STATIC_BANNER 1 /* no string concatenation. */ # endif #endif /* AM: company-specific version strings should appear in options.h. */ #undef VERSION_STRING #ifdef RELEASE_VSN # define VERSION_STRING RELEASE_VSN #else # ifdef NON_RELEASE_VSN # define VERSION_STRING NON_RELEASE_VSN # else # ifdef __STDC__ # define VERSION_STRING FE_VERSION "/" MIP_VERSION "/" MC_VERSION # else # define VERSION_STRING "<unspecified>" # endif # endif #endif /* Note the comment in mip/version.h re the 4 nulls at end of string. */ #ifdef STATIC_BANNER static char cc_banner[] = "Norcroft " \ TARGET_SYSTEM " " TARGET_MACHINE " " LANGUAGE \ " vsn " VERSION_STRING " [" __DATE__ "]\0\0\0"; char *version_banner(void) { return cc_banner; } #else /* ! STATIC_BANNER */ /* * Can't build the banner using ANSI string concatenation, * so build it dynamically instead. */ static char cc_banner[128] = ""; /* expression instead of 128? */ char *version_banner(void) { if (cc_banner[0]=='\0') { sprintf(cc_banner, "Norcroft %s %s %s vsn %s [%s]\0\0\0", TARGET_SYSTEM, TARGET_MACHINE, LANGUAGE, VERSION_STRING, __DATE__); } return(cc_banner); } #endif /* STATIC_BANNER */ /* end of mip/version.c */
stardot/ncc
clbcomp/clbcomp.c
<gh_stars>0 /* * ccomp/ccomp.c: callable compiler * Copyright (C) Advanced RISC Machines Limited, 1996. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <signal.h> #include "globals.h" /* for errstate_init() */ #include "aetree.h" /* aetree_init() */ #include "store.h" /* alloc_initialise(); store for AEtree */ #include "bind.h" /* bind_init(); namelookup */ #include "lex.h" /* lex_init() */ #include "syn.h" /* syn_init() */ #include "sem.h" /* sem_init() */ #include "builtin.h" /* built_init */ #include "compiler.h" /* compiler_exit() */ #include "backchat.h" /* BC_DIAGMSG, */ #include "simplify.h" #include "aeops.h" #include "defs.h" #include "dump.h" #include "clbcomp.h" BackChatHandler backchat; /* defined in arm/mcdep.c etc but really should be guarded by NO_CONFIG in the rest of the compiler */ int32 config; /* Dummy definitions */ unsigned dump_state; char *expr_string; char *phasename; struct CurrentFnDetails currentfunction; Dump_LoadState dump_loadstate; /* Hacked until the debug toolbox decided what to do with err msgs. */ static void clb_ErrorMessage(backchat_Diagnostic *diag) { char const *msg = diag->msgtext; unsigned line = diag->lineno; char b[256]; cc_announce_error(b, diag->severity, diag->filename, line); fputs(b, stderr); fputs(msg, stderr); } static int clb_BC(unsigned code, const void *msg, void *handle) { IGNORE(handle); switch (code) { case BC_DIAGMSG: clb_ErrorMessage((backchat_Diagnostic *)msg); return 0; } return 0; } void clb_init(void) { int i = 0; #ifndef COMPILING_ON_MSDOS /* The signal ignore state can be inherited from the parent... */ if (signal(SIGINT, SIG_IGN) != SIG_IGN) (void) signal(SIGINT, compile_abort); #ifdef SIGHUP if (signal(SIGHUP, SIG_IGN) != SIG_IGN) (void) signal(SIGINT, compile_abort); #endif if (signal(SIGTERM, SIG_IGN) != SIG_IGN) (void) signal(SIGINT, compile_abort); #endif feature |= (FEATURE_CPP|FEATURE_CFRONT); expr_string = NULL; errstate_initialise(); errstate_perfileinit(); aetree_init(); #ifndef USE_PP for (; i <= 'z'-'a'; i++) pp_pragmavec[i] = -1; #else IGNORE(i); pp_init(&curlex.fl); var_cc_private_flags = 0; #endif bind_init(); lex_init(); builtin_init(); sem_init(); syn_init(); backchat.send = clb_BC; backchat.handle = NULL; } Expr *clb_parse_expr(char *s) { Expr *e, *edtor; SynBindList *bl; lex_reinit(); expr_string = s; push_saved_temps(0); push_exprtemp_scope(); nextsym(); e = rd_expr(10/*PASTCOMMA*/); bl = pop_saved_temps(NULL); if ((edtor = killexprtemp()) != NULL) { TypeExpr *t = typeofexpr(e); Binder *b = gentempbinder(t); e = mkbinary(s_init, (Expr *)b, e); e = mkbinary(s_comma, e, edtor); e = mkbinary(s_comma, e, (Expr *)b); e = mk_exprlet(s_let, t, reverse_SynBindList(mkSynBindList(bl, b)), e); } else if (bl != NULL) e = mk_exprlet(s_let, typeofexpr(e), reverse_SynBindList(bl), e); return optimise0(e); } void compiler_exit(int status) { IGNORE(status); }
stardot/ncc
cppfe/xlex.c
/* * C++ compiler file xlex.c * Copyright (C) Codemist Ltd., 1988-1992 * Copyright (C) Acorn Computers Ltd., 1988-1990 * Copyright (C) Advanced RISC Machines Ltd., 1990-1992, 1994 * SPDX-Licence-Identifier: Apache-2.0 * All rights reserved. */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifdef __STDC__ # include <stddef.h> # include <string.h> #else # include "stddef.h" # include <strings.h> #endif #include <ctype.h> #include "globals.h" #include "lex.h" #include "bind.h" #include "pp.h" #include "store.h" #include "util.h" #include "aeops.h" #include "errors.h" #ifdef TARGET_HAS_INLINE_ASSEMBLER # include "inlnasm.h" #endif #define _LEX_H static void lex_getbodysym(void); static void lex_putbodysym(void); static Symstr *template_old_sv, *template_new_sv; static SymInfo old_nextlex = {s_nothing}; typedef struct { Symstr *old, *new; SymInfo next; } Restorable_Names; static List *restorable_names_list; static void save_names(bool glob); static void restore_names(void); #include "lex.c" static const SymBuf lexbuf_empty = { 0, { s_eof }, (SymInfo *)DUFF_ADDR, 0, /*pos*/ -1, 0, NO, /* old_put_handle */ -1 }; #define INIT_NLEXBUFS 8 /* initially max 8 member fn defs. */ #define INIT_LEXBUFSIZE 32 /* initially max 32 tokens per def. */ /* C++ requires function definitions within class definitions to be */ /* lexed, but not parsed (typedefs) nor typechecked [ES, p178]. */ /* We save them as as token streams until we are ready -- the end */ /* is observable by counting {}'s. */ /* Note there is a complication about reading such a saved token stream */ /* since such a fn body may contain embedded fns within yet other */ /* (local) class definitions. */ /* Globalise everything to be buffered for now (very little to do). */ static int lex_findsavebuf(void) { int i; for (i = 0; i<lexbuf_max; i++) if (lexbuf_vec[i].pos < 0) return i; { int nmax = (lexbuf_max == 0 ? INIT_NLEXBUFS : 2*lexbuf_max); SymBuf *nvec = (SymBuf *)GlobAlloc(SU_Other, (int32)nmax * sizeof(SymBuf)); memcpy(nvec, lexbuf_vec, lexbuf_max * sizeof(SymBuf)); for (i = lexbuf_max; i < nmax; i++) nvec[i] = lexbuf_empty; lexbuf_max = nmax, lexbuf_vec = nvec; return lex_findsavebuf(); /* retry */ } } static void lex_ensurebuf(SymBuf *p) { int nsize = (p->size == 0 ? INIT_LEXBUFSIZE : p->size*2); SymInfo *nbuf = (SymInfo *)GlobAlloc(SU_Other, (int32)nsize * sizeof(SymInfo)); memcpy(nbuf, p->buf, p->size * sizeof(SymInfo)); p->size = nsize, p->buf = nbuf; } static void lex_putbodysym() { SymBuf *p = &lexbuf_vec[nextsym_put_handle]; int put_handle = nextsym_put_handle; bool is_lbrace = (curlex.sym == s_lbrace); /* write back to every Symbuf we're a nested defn of. */ for (;;) { int k = p->pos; /* save the tokens in p->buf, followed by a s_eof token.*/ if (k >= p->size) lex_ensurebuf(p); lex_beware_reinit(); /* globalise curlex */ if (debugging(DEBUG_LEX)) cc_msg("lex_putbodysym: saving $l in [%d]\n", put_handle); p->buf[k++] = curlex; p->pos = k; /* skip s_lbrace between its already recorded */ if (!is_lbrace && (p->old_put_handle >= 0)) { put_handle = p->old_put_handle; p = &lexbuf_vec[p->old_put_handle]; } else break; } } /* lex_bodybegin() and lex_bodyend() deal with saving templates. */ int lex_bodybegin() { int olde_put_handle = nextsym_put_handle; nextsym_put_handle = lex_findsavebuf(); lexbuf_vec[nextsym_put_handle].old_put_handle = olde_put_handle; if (debugging(DEBUG_LEX)) { if (olde_put_handle >= 0) cc_msg("lex_bodybegin: new nested level [%d] %d\n", nextsym_put_handle, olde_put_handle); else cc_msg("lex_bodybegin: [%d]\n", nextsym_put_handle); } lexbuf_vec[nextsym_put_handle].pos = 0; /* inuse/ready to write */ lex_putbodysym(); /* first token ':' or '{'. */ return nextsym_put_handle; } static void lex_dumpbuf(const SymBuf *p) { if (p->pos < 0) cc_msg("unused lexbuf\n"); else { int i = 0; cc_msg(" "); for (;;) { cc_msg("$k ", p->buf[i]); ++i; if (0 < p->count && p->count <= i) break; else if (p->buf[i].sym == s_eof) break; if (i % 8 == 0) cc_msg("\n "); } cc_msg("\n"); } } int lex_bodyend() { int h = nextsym_put_handle; SymBuf *p; p = &lexbuf_vec[h]; if (p->pos >= p->size) lex_ensurebuf(p); p->buf[p->pos].sym = s_eof; /* the token after '}' or ';' */ p->buf[p->pos].fl = p->pos < 0 ? p->buf[p->pos - 1].fl : curlex.fl; p->pos = 0; /* inuse/ready to read. */ nextsym_put_handle = p->old_put_handle; if (debugging(DEBUG_LEX)) { cc_msg("lex_bodyend: [%d]\n", h); lex_dumpbuf(p); } return h; } /* lex_savebody() reads and saves (on the fly) a member fn body. */ /* maybe should be called lex_saveblock */ int lex_savebody(void) { int h = lex_findsavebuf(); SymBuf *p = &lexbuf_vec[h]; int k = 0, braces = 0; if (debugging(DEBUG_LEX)) cc_msg("lex_savebody: [%d]\n", h); p->pos = 0; /* inuse + ready for reader. */ /* save all the tokens in p->buf, followed by a s_eof token. */ for (;;) { if (k >= p->size) lex_ensurebuf(p); lex_beware_reinit(); /* globalise curlex */ if (debugging(DEBUG_LEX)) cc_msg("lex_savebody: saving $l in [%d]\n", h); p->buf[k++] = curlex; switch (curlex.sym) { case s_lbrace: braces++; default: nextsym(); break; case s_rbrace: if (--braces == 0) curlex.sym = s_eof; else nextsym(); break; case s_eof: p->count = k; if (debugging(DEBUG_LEX)) { cc_msg("lex_savebody: [%d] is\n", h); lex_dumpbuf(p); } return h; } } } int lex_saveexpr(void) { int h = lex_findsavebuf(); SymBuf *p = &lexbuf_vec[h]; int k = 0, parens = 0; if (debugging(DEBUG_LEX)) cc_msg("lex_saveexpr: [%d]\n", h); p->pos = 0; /* inuse + ready for reader. */ /* save all the tokens of expr(UPTOCOMMA) in p->buf. */ for (;;) { if (k >= p->size) lex_ensurebuf(p); lex_beware_reinit(); /* globalise curlex */ if (debugging(DEBUG_LEX)) cc_msg("lex_saveexpr: saving $l in [%d]\n", h); p->buf[k++] = curlex; switch (curlex.sym) { case s_lpar: parens++; default: break; case s_rpar: if (parens > 0) { --parens; break; } case s_comma: if (parens == 0) { case s_eof: p->buf[k-1].sym = s_comma; p->count = k; if (debugging(DEBUG_LEX)) { cc_msg("lex_saveexpr: [%d] is\n", h); lex_dumpbuf(p); } return h; } break; } nextsym(); } } static void save_names(bool glob) { Restorable_Names *tmp = (Restorable_Names *) ((glob) ? GlobAlloc(SU_Other, sizeof(Restorable_Names)) : SynAlloc(sizeof(Restorable_Names))); tmp->old = template_old_sv; tmp->new = template_new_sv; tmp->next = old_nextlex; old_nextlex.sym = s_nothing; restorable_names_list = (glob) ? global_cons2(SU_Other, restorable_names_list, (IPtr)tmp) : syn_cons2(restorable_names_list, (IPtr)tmp); } static void restore_names(void) { /* getbodysym() does an implicit lex_closebody(). Perhaps we should do a save_names() in doe. Done, but not in doe. */ if (!restorable_names_list) syserr("Lost restoreable names"); { Restorable_Names *tmp = (Restorable_Names *)restorable_names_list->car; restorable_names_list = restorable_names_list->cdr; template_old_sv = tmp->old; template_new_sv = tmp->new; old_nextlex = tmp->next; } } void lex_openbody(int h, bool dup, bool record, Symstr *old_sv, Symstr *new_sv) { if (dup) { int h2 = lex_findsavebuf(); SymBuf *p = &lexbuf_vec[h], *p2 = &lexbuf_vec[h2]; if (debugging(DEBUG_LEX)) { cc_msg("lex_openbody: dup [%d] -> [%d]\n", h, h2); lex_dumpbuf(p); } /* The memcpy of symbols is a bit wasteful when we could share the */ /* the buffer vectors, but this would make (re-)allocation harder. */ /* @@@ maybe not, let's do it soon. */ if (p2->size < p->size) { int nsize = p->size; SymInfo *nbuf = (SymInfo *)GlobAlloc(SU_Other, (int32)nsize * sizeof(SymInfo)); p2->size = nsize, p2->buf = nbuf; } memcpy(p2->buf, p->buf, p->size * sizeof(SymInfo)); p2->pos = 0; p2->dup_hack = YES; h = h2; } lexbuf_vec[h].prev = nextsym_lookaside; if (record) lexbuf_vec[h].old_put_handle = -1; else { lexbuf_vec[h].old_put_handle = nextsym_put_handle; nextsym_put_handle = -1; } lex_beware_reinit(); /* globalise curlex */ lexbuf_vec[h].prevsym = curlex; nextsym_lookaside = &lexbuf_vec[h]; if (debugging(DEBUG_LEX)) cc_msg("lex_openbody: [%d]\n", h); save_names(NO); template_old_sv = old_sv, template_new_sv = new_sv; old_nextlex = nextlex; nextlex.sym = s_nothing; nextsym(); /* currently always '{' (or ':'?) */ } void lex_closebody(void) { if (debugging(DEBUG_LEX)) cc_msg("lex_closebody: [%d]\n", (int)(nextsym_lookaside - lexbuf_vec)); nextsym_lookaside->pos = -1; nextsym_lookaside->count = 0; nextsym_lookaside->dup_hack = NO; template_new_sv = template_old_sv = NULL; curlex = nextsym_lookaside->prevsym; if (nextsym_lookaside->old_put_handle != -1) nextsym_put_handle = nextsym_lookaside->old_put_handle; nextsym_lookaside = nextsym_lookaside->prev; nextlex = old_nextlex; /*old_nextlex.sym = s_nothing;*/ restore_names(); } static void lex_getbodysym(void) { /* The first test is needed for d-or-e code, but breaks template */ /* code. In fact the whole 're-lex' edifice is tottering. */ /* (Another victim of absent specification.) */ /* Template end is marked with s_eof, doe with a count. */ /* Fix with a special hack flag. */ Symstr *changed = NULL; if (nextsym_lookaside->pos >= nextsym_lookaside->count && !nextsym_lookaside->dup_hack) { /* syserr("lex_getbodysym overflow"); */ /* should we really do implicit 'close' here? */ save_names(NO); lex_closebody(); } else { curlex = nextsym_lookaside->buf[nextsym_lookaside->pos]; if (curlex.sym == s_identifier && curlex.a1.sv == template_old_sv) { AE_op pre = nextsym_lookaside->buf[nextsym_lookaside->pos-1].sym, post = nextsym_lookaside->buf[nextsym_lookaside->pos+1].sym; if (pre != s_class && pre != s_comma && pre != s_lpar && post != s_less) { changed = curlex.a1.sv; curlex.a1.sv = template_new_sv; } } if (curlex.sym != s_eof) nextsym_lookaside->pos++; } if (debugging(DEBUG_TEMPLATE)) (changed) ? cc_msg("lex_getbodysym replacing $r -> $l\n", changed): cc_msg("lex_getbodysym $l\n"); } static bool had_nextlex; static int save_nextsym_put_handle; AEop lex_buffersym(void) { int h = buffersym_bufidx; SymBuf *p; if (h < 0) { buffersym_bufidx = h = lex_findsavebuf(); lexbuf_vec[h].pos = 0; /* claim it */ /* stop any recording while we're peeking ahead but curlex and nextlex will already have been recorded */ save_nextsym_put_handle = nextsym_put_handle; /* we don't use lexbuf_vec[h].old_put_handle because that's for preventing recording during playback, which we want */ lexbuf_vec[h].old_put_handle = -1; nextsym_put_handle = -1; had_nextlex = nextlex.sym != s_nothing; if (debugging(DEBUG_LEX)) cc_msg("lex_buffersym: open [%d]\n", h); } p = &lexbuf_vec[h]; if (p->count >= p->size) lex_ensurebuf(p); if (debugging(DEBUG_LEX)) cc_msg("lex_buffersym: saving $l in [%d]\n", h); p->buf[p->count++] = curlex; nextsym(); return curlex.sym; } void lex_endbuffering(void) { int h = buffersym_bufidx; if (h < 0) return; lexbuf_vec[h].prev = nextsym_lookaside; lexbuf_vec[h].prevsym = curlex; nextsym_lookaside = &lexbuf_vec[h]; if (debugging(DEBUG_LEX)) { cc_msg("lex_endbuffering: begin reading from [%d]\n", h); lex_dumpbuf(nextsym_lookaside); } buffersym_bufidx = -1; nextsym(); /* was curlex when buffering started */ if (had_nextlex) { nextsym(); /* was nextlex when buffering started */ ungetsym(); } /* resume any recording */ nextsym_put_handle = save_nextsym_put_handle; } Symstr *lex_replaceable_template_sym(Symstr *s) { if (template_old_sv == s) { if (debugging(DEBUG_TEMPLATE)) cc_msg("lex_replaceable_sym replacing $r -> $r\n", s, template_new_sv); return template_new_sv; } else return s; } /* check nextsym_for_hashif uses consistent!. */
stardot/ncc
tests/packed.c
<gh_stars>0 /* * ARM C compiler regression test $RCSfile$ * Copyright (C) 1995 Advanced Risc Machines Ltd. All rights reserved. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <string.h> #include "testutil.h" typedef __packed struct { int (*f)(int, int, int, int); } S_667; int g_667(int a, int b, int c, int d) { return a*b + c*d; } int f_667(S_667 *s) { return s->f(1,2,3,4); } void t_667(void) { S_667 s; s.f = g_667; EQI(f_667(&s), 14); } typedef __packed struct { unsigned short p1; unsigned short p2; unsigned short p3; } S_931; static void f_931(S_931 s, int a, int b, int c) { EQI(s.p1, a); EQI(s.p2, b); EQI(s.p3, c); } static S_931 ss = { 1, 2, 3 }; void t_931(void) { S_931 s = { 0, 0, 0 }; f_931(s, 0, 0, 0); s = ss; f_931(ss, 1, 2, 3); } typedef __packed struct { int a; char pad1; int b; char pad2; int c; char pad3; int d; char pad4; short e; char pad5; short f; char pad6[3]; } S_xxx; void test1_xxx_unaligned(S_xxx *t) { EQI(t->a, 0x12345678); /* Not BaseAligned: Offset 0 */ EQI(t->b, 0x12345678); /* Not BaseAligned: Offset 1 */ EQI(t->c, 0x12345678); /* Not BaseAligned: Offset 2 */ EQI(t->d, 0x12345678); /* Not BaseAligned: Offset 3 */ EQI(t->e, 0x1234); /* Not BaseAligned (halfword): Offset 0 */ EQI(t->f, 0x1234); /* Not BaseAligned (halfword): Offset 1 */ } void test1_xxx_aligned(S_xxx t) { EQI(t.a, 0x12345678); /* BaseAligned: Offset 0 */ EQI(t.b, 0x12345678); /* BaseAligned: Offset 1 */ EQI(t.c, 0x12345678); /* BaseAligned: Offset 2 */ EQI(t.d, 0x12345678); /* BaseAligned: Offset 3 */ EQI(t.e, 0x1234); /* BaseAligned (halfword): Offset 0 */ EQI(t.f, 0x1234); /* BaseAligned (halfword): Offset 1 */ } void test_xxx_args(int a, int b, int c, int d) { EQI(a, 0x12345678); EQI(b, 0x12345678); EQI(c, 0x12345678); EQI(d, 0x12345678); } void test2_xxx_unaligned(S_xxx *t) { test_xxx_args(t->a, t->b, t->c, t->d); /* Not BaseAligned: fnargs */ } void test2_xxx_aligned(S_xxx t) { test_xxx_args(t.a, t.b, t.c, t.d); /* BaseAligned: fnargs */ } S_xxx s1_xxx = { 0x12345678, 0, 0x12345678, 0, 0x12345678, 0, 0x12345678, 0, 0x1234, 0, 0x1234, }; S_xxx s2_xxx; typedef __packed struct { char c; unsigned short l, r, t, b; unsigned short tl, tr, tt, tb; } S_1093; int f_1093(S_1093 *a, S_1093 *b) { return (a->tt >= b->tt && a->tt < b->tb) || (a->tb <= b->tb && a->tb > b->tt) || (b->tt >= a->tt && b->tt < a->tb) || (b->tb <= a->tb && b->tb > a->tt); } void t_1093() { S_1093 a = {0, 0,0,0,0, 0,0,260,261}, b = {0, 0,0,0,0, 0,512,256,257}; EQI(f_1093(&a, &b), 0); } /********************* 1574 ***********************/ void f_1574(char *a, int b, int c, char *d, int e, int f, int g) { EQI(b, 0); EQI(c, 3); EQI(e, 5); EQI(f, 0); EQI(g, 1); } void g_1574(int __packed *p) { f_1574("xxx", 0, 3, "yyy", *p, 0, 1); } __packed struct { char a; int b; } s_1574; void t_1574(void) { s_1574.b = 5; g_1574(&s_1574.b); } /********************* 1590 ***********************/ __packed struct { char x; short y; int z; } px_1590; void f_1590(char const *s, int a, int b, int c) { EQI(a, 0); EQI(b, 1); EQI(c, 2); } void t_1590(void) { px_1590.x = 0; px_1590.y = 1; px_1590.z = 2; f_1590("s", px_1590.x, px_1590.y, px_1590.z); } /********************* 1603 ***********************/ __packed struct { char x; short y; int z; } s_1603 = {0, 1, 2}; void f_1603(char const *s, int a, int b, int c) { EQI(a, 0); EQI(b, 1); EQI(c, 2); } void t_1603(void) { f_1603("s", s_1603.x, s_1603.y, s_1603.z); } /********************* 1982 ***********************/ /* failed or gave compiletime error */ typedef struct { int (*f)(int, int, int, int); } t0_1982_vtable; typedef __packed struct { t0_1982_vtable *q; } t0_1982_mystr; int t1_1982(t0_1982_mystr *p) { p->q->f(0, 1, 2, 3); } int t2_1982(int a, int b, int c, int d) { return a + b + c + d; } void t_1982() { t0_1982_vtable v; t0_1982_mystr str; str.q = &v; v.f = t2_1982; EQI(t1_1982(&str), 6); } /********************* 2297 ***********************/ int (*fv)(int, int, int, int); typedef __packed struct { int x; } S; int t0_2297(S *s) { return fv(3, 0, 1, s->x); } int t1_2297(int a, int b, int c, int d) { return a + b + c + d; } void t_2297() { S s = { 2 }; fv = t1_2297; EQI(t0_2297(&s), 0+1+3+2); } /********************* ***********************/ void t_xxx(void) { /* Performing tests on static initialised packed struct */ test1_xxx_aligned(s1_xxx); test1_xxx_unaligned(&s1_xxx); test2_xxx_aligned(s1_xxx); test2_xxx_unaligned(&s1_xxx); /* Performing tests on dynamically initialised packed struct */ s2_xxx.a = 0x12345678; s2_xxx.b = 0x12345678; s2_xxx.c = 0x12345678; s2_xxx.d = 0x12345678; s2_xxx.e = 0x1234; s2_xxx.f = 0x1234; test1_xxx_aligned(s2_xxx); test1_xxx_unaligned(&s2_xxx); test2_xxx_aligned(s2_xxx); test2_xxx_unaligned(&s2_xxx); } int main() { BeginTest(); t_667(); t_931(); t_xxx(); t_1093(); t_1574(); t_1590(); t_1603(); t_1982(); t_2297(); EndTest(); return 0; }
stardot/ncc
arm/ops.h
/* * C compiler file arm/ops.h * Copyright (C) Advanced RISC Machines Limited, 1997 * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ /* This file is not used at all: armthumb/armops.h is. */ /* It is needed to maintain identity in the set of files */ /* needed to build ARM- and Thumb- targetted compilers */ /* end of arm/ops.h */
stardot/ncc
armthumb/aaof.c
<gh_stars>0 /* * C compiler file aaof.c, version 18d * Copyright (C) CodeMist Ltd., 1988 * Copyright (C) Acorn Computers Ltd., 1988 * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifdef __STDC__ #include <string.h> #else #define SEEK_SET 0 #include <strings.h> #include <stddef.h> #endif #include "globals.h" #include "mcdep.h" #include "mcdpriv.h" #include "errors.h" #include "xrefs.h" #include "store.h" #include "codebuf.h" #include "version.h" #include "builtin.h" /* for codesegment... */ #include "bind.h" /* for sym_insert_id() */ #include "errors.h" #include "chunkfmt.h" #include "aof.h" #include "cg.h" /* has_main */ #include "armops.h" #include "vargen.h" #ifdef PUT_FILE_NAME_IN_AREA_NAME # include "fname.h" # include "compiler.h" #endif static int32 obj_fwrite_cnt; static bool byte_reversing = 0; /* byte_reversing == (host_lsbytefirst != target_lsbytefirst). */ /* (But faster to test one static per word than 2 externs per word). */ static void obj_fwrite(void const *buff, int32 n, int32 m, FILE *f) { if (debugging(DEBUG_OBJ)) { int32 i; fprintf(f, "%.6lx:", (long)obj_fwrite_cnt); obj_fwrite_cnt += n*m; for (i=0; i<n*m; i++) fprintf(f, " %.2x", ((uint8 const *)buff)[i]); fprintf(f, "\n"); } else if (n == 4 && byte_reversing) { /* word by word output */ uint32 const *p; for (p = (uint32 const *)buff; m > 0; --m, ++p) { uint32 w, v = *p; /* Amazingly, this generates better code on an ARM than the more */ /* obvious and transparent way to reverse the bytes. A future cse */ /* may turn the simulations of ROR into ROR, giving optimal code. */ /* t = v^(v ROR 16); t &= ~0xff0000; v = v ROR 8; v = v^(t >> 8). */ uint32 t = v ^ ((v << 16) | (v >> 16)); /* ...v ROR 16 */ t &= ~0xff0000; v = (v << 24) | (v >> 8); /* v = v ROR 8 */ w = v ^ (t >> 8); fwrite(&w, 4, 1, f); } } else if (n == 2 && byte_reversing) { uint16 const *p; for (p = (uint16 const *)buff; m > 0; --m, ++p) { uint16 v = *p; v = (v >> 8) | (v << 8); fwrite(&v, 2, 1, f); } } else fwrite(buff, (size_t)n, (size_t)m, f); } #ifdef TARGET_HAS_HALFWORD_INSTRUCTIONS static int32 obj_pad(int32 size) { int buff = 0; if (size & 3) obj_fwrite(&buff, 1, 4 - (size & 3), objstream); size = (size + 3) & ~3; return size; } #endif FILE *objstream; typedef struct DebugAreaDesc DebugAreaDesc; struct DebugAreaDesc { DebugAreaDesc *cdr; Symstr *sym; Symstr *refsym; int32 size, nrelocs; }; static DebugAreaDesc *debugareas, **debugareas_tail; static DebugAreaDesc *curdebugarea; #ifdef TARGET_HAS_DEBUGGER void obj_writedebug(void const *p, int32 n) /* for armdbg.c */ { if (n & DBG_INTFLAG) { obj_fwrite(p, 4, n & ~DBG_INTFLAG, objstream); n *= 4; } else if (n & DBG_SHORTFLAG) { obj_fwrite(p, 2, n & ~DBG_SHORTFLAG, objstream); n = (n & ~DBG_SHORTFLAG) * 2; } else obj_fwrite(p, 1, n, objstream); curdebugarea->size += n; } #endif /* AOF output routines: Note that much of the nastiness here * is due to ACORN's AOF file spec which requires AOF files to * output areas contiguously followed by their relocation directives. * For a better alternative see the IBM 360 object file format in * which they may be mixed at a big saving in store in each compiler * and only marginal cost to the linker. */ #define OBJ_DUMMYSYM xr_objflg #define OBJ_REPLACEBYAREA xr_objflg4 #define OBJ_DELETED xr_objflg5 #define OBJ_MAXCHUNKS 8 #define OBJ_NUMCHUNKS 5 /* imports: codebase, dataloc, bss_size */ static int32 constdatabase, extablebase, exhandlerbase; static int32 ncommonareas, ncodeareas, nareas, codeareasize; static int32 ndatarelocs, nadconrelocs; static int32 obj_stringpos, obj_symcount, aof_hdr_offset; Symstr *data_sym, *bss_sym, *adcon_sym, *ddtor_sym, *extable_sym, *exhandler_sym; ExtRef *obj_symlist; CodeXref *codexrefs; DataXref *dbgxrefs; /* An aof_xarea is an aof_area with a chain field and a Symstr field. */ /* area_size, area_nrelocs, area_attributes are set early and later */ /* area_base and area_name (these shared with asv and anext once). */ typedef struct aof_xarea { aof_area aaxa; struct { Symstr *asv; struct aof_xarea *anext; } aaxb; } aof_xarea; static aof_xarea _areahdr_, *codeareap, *codeareaq; static void obj_end_codearea(void); static void obj_start_codearea(void); static bool thisCodeAreaIsEmpty; void obj_codewrite(Symstr *name) /* (name == 0 && codep == 0) => called from codebuf_reinit1() */ /* bindsym_(codesegment) is the new code segment name. */ /* (name == 0 && codep != 0) => called after string literal... */ /* (name != 0) => called from show_code() for function 'name'. */ /* called after each function or string lit is compiled. */ { if (codep == 0) { if (name == 0) { obj_end_codearea(); obj_start_codearea(); thisCodeAreaIsEmpty = YES; } return; } thisCodeAreaIsEmpty = NO; if (byte_reversing) { int32 i = 0, n = codep, w; while (i < n) { /* ECN: Support for halfword stream */ #ifdef TARGET_HAS_HALFWORD_INSTRUCTIONS int32 f = code_flag_(i); /* If this is a halfword style thing */ if (f == LIT_OPCODE || f == LIT_BB || f == LIT_H) { unsigned16 hw; hw = code_hword_(i); if (f == LIT_BB) hw = (hw >> 8) | (hw << 8); obj_fwrite(&hw, 2, 1, objstream); i += 2; continue; } #endif w = totargetsex(code_inst_(i), code_flag_(i)); obj_fwrite(&w, 4, 1, objstream); i += 4; } } else { int32 i = 0; while ((codep>>2) - CODEVECSEGSIZE*i > CODEVECSEGSIZE) obj_fwrite(code_instvec_(i), 4, CODEVECSEGSIZE, objstream), i++; /* ECN: code block may not be a multiple of 4 */ #ifdef TARGET_HAS_HALFWORD_INSTRUCTIONS obj_fwrite(code_instvec_(i), 2, (codep>>1)-CODEVECSEGSIZE*i*2, objstream); #else obj_fwrite(code_instvec_(i), 4, (codep>>2)-CODEVECSEGSIZE*i, objstream); #endif } if (ferror(objstream)) cc_fatalerr(obj_fatalerr_io_object); } static CommonDef dataarea; CommonDef *commondefs; static CommonDef *curcommon; static void setcurcommon(CommonDef *com) { copy_datadesc(&curcommon->data); restore_datadesc(&com->data); curcommon = com; } static CommonDef *findcommondef(int32 i) { CommonDef *p = commondefs; int32 n; for (n = i; --n > 0; p = p->next) if (p == NULL) syserr(syserr_commondef, (long)i); return p; } void obj_common_start(Symstr *name) { CommonDef *p; CommonDef **q = &commondefs; int i; for (p = commondefs, i = 1; p != NULL; q = &p->next, p = p->next, i++) if (p->name == name) { cc_err(obj_err_common, name); break; } if (p == NULL) { p = (CommonDef *) GlobAlloc(SU_Data, sizeof(CommonDef)); p->next = NULL; p->data.head = p->data.tail = NULL; p->data.size = 0; p->name = name; p->index = i; setcurcommon(p); *q = p; obj_symref(name, xr_data+xr_defext+xr_cblock, 0); } else setcurcommon(p); } void obj_common_end(void) { if (curcommon->refsize != 0 && data_size() < curcommon->refsize) cc_err(obj_err_common1, curcommon->name); setcurcommon(&dataarea); } /* the remaining fns are intended to be internal only */ static int32 obj_checksym_1(Symstr *s) { ExtRef *x = symext_(s); if (x != NULL) { if (x->extflags & OBJ_DUMMYSYM) return x->extoffset; if (!(x->extflags & OBJ_REPLACEBYAREA)) return REL_A + x->extindex; s = x->codesym; x = symext_(s); if (x != NULL) return x->extindex-1; } syserr(syserr_obj_checksym, s); return 0; } static int32 obj_checksym(Symstr *s) { int32 res = obj_checksym_1(s); if (res >= 0) return res; syserr(syserr_obj_checksym, s); return 0; } static void obj_outsymtab(void) { ExtRef *x; int32 stringpos = 4; obj_symlist = (ExtRef *)dreverse((List *)obj_symlist); /* oldest = smallest numbered first */ for (x = obj_symlist; x != NULL; x = x->extcdr) { Symstr *s = x->extsym; if (x->extflags & OBJ_DUMMYSYM) x->extoffset = stringpos; if (!(x->extflags & OBJ_DELETED)) stringpos += (int32) strlen(symname_(s)) + 1; } stringpos = 4; for (x = obj_symlist; x != NULL; x = x->extcdr) { Symstr *s = x->extsym; int32 flags = x->extflags; if (debugging(DEBUG_OBJ)) cc_msg("sym$r%lx ", s, (long)flags); if (!(flags & (OBJ_DUMMYSYM+OBJ_DELETED))) { aof_symbol sym; #ifdef TARGET_IS_THUMB int32 at = flags & xr_defloc ? SYM_LOCALDEFAT + SYM_THUMB : flags & xr_defext ? SYM_GLOBALDEFAT + SYM_THUMB : flags & xr_weak ? SYM_WEAKAT+SYM_REFAT : SYM_REFAT; #ifdef THUMB_CPLUSPLUS if (flags & xr_code_32) at &= ~SYM_THUMB; #endif #else int32 at = flags & xr_defloc ? SYM_LOCALDEFAT : flags & xr_defext ? SYM_GLOBALDEFAT : flags & xr_weak ? SYM_WEAKAT+SYM_REFAT : SYM_REFAT; #endif sym.sym_name = stringpos; /* revision soon to set data if (code & dataincode) ? */ if ((flags & xr_code) && (flags & xr_dataincode)) at |= SYM_DATAAT; /* ECN: constdata must have data bit set too otherwise linker may generate * wrong value (ie address + 1) */ if (flags & xr_constdata) at |= SYM_DATAAT; if (flags & aof_fpreg) at |= SYM_FPREGAT; if (!(flags & aof_usessb) && (flags & aof_leaf)) at |= SYM_LEAFAT; sym.sym_value = x->extoffset; /* always zero unless xr_defloc+xr_defext */ if (xr_flagtoidx_(flags) != 0) { CommonDef *p = findcommondef(xr_flagtoidx_(flags)); if (flags & xr_cblock) p->stringpos = stringpos; sym.sym_areaname = p->stringpos; } /* The next line knows there are no symbols in the dbg segment */ else if (flags & (xr_defloc+xr_defext)) { Symstr *area; if (flags & xr_code) area = x->codesym; else if (flags & xr_data) area = data_sym; else if (flags & xr_constdata) area = codeareaq->aaxb.asv, sym.sym_value += constdatabase; else if (flags & xr_bss) area = bss_sym; else area = adcon_sym; sym.sym_areaname = obj_checksym(area); } else if (x->extoffset != 0) { /* common block */ at = SYM_LOCALDEFAT; sym.sym_value = 0; /* offset MUST be 0... */ sym.sym_areaname = stringpos; /* relative to the common AREA */ /* Hack: place a small int in pointer field x->codesym (find 'IPtr'). */ x->codesym = (Symstr *)(IPtr)stringpos; } else sym.sym_areaname = 0; sym.sym_AT = at; obj_fwrite(&sym, 4, sizeof(sym)/4, objstream); } if (!(x->extflags & OBJ_DELETED)) stringpos += (int32) strlen(symname_(s)) + 1; } obj_stringpos = stringpos; obj_fwrite(&obj_stringpos, 4, 1, objstream); for (x = obj_symlist; x != NULL; x = x->extcdr) { Symstr *s = x->extsym; if (!(x->extflags & OBJ_DELETED)) obj_fwrite(symname_(s), 1, (int32)strlen(symname_(s))+1, objstream); } while (stringpos & 3) {putc(0, objstream); ++stringpos;} obj_stringpos = stringpos; } static void obj_outcommonheaders(bool output) { if (ncommonareas) { ExtRef *x; aof_area a; CommonDef *p; /* got at least one so worth counting properly... */ ncommonareas = 0; a.area_nrelocs = 0; a.area_base = 0; for (p = commondefs; p != NULL; p = p->next) { ++ncommonareas; if (output == NO) continue; a.area_name = p->stringpos; a.area_attributes = 2 + AOF_COMDEFAT; a.area_size = (p->data.size + 3) & ~3; /* must be a multiple of 4 */ obj_fwrite(&a, 4, sizeof(a)/4, objstream); } for (x = obj_symlist; x != NULL; x = x->extcdr) { int32 flags = x->extflags; int32 len = x->extoffset; if (!(flags & (xr_defloc + xr_defext + xr_code + OBJ_DELETED + OBJ_DUMMYSYM + OBJ_REPLACEBYAREA)) && len > 0) { /* common reference ... */ ++ncommonareas; if (output == NO) continue; /* Hack: get a small int from pointer field x->codesym (find 'IPtr'). */ a.area_name = (int32)(IPtr)x->codesym; a.area_attributes = 2 + AOF_COMREFAT + AOF_0INITAT; a.area_size = (len + 3) & ~3; /* must be a multiple of 4 */ obj_fwrite(&a, 4, sizeof(a)/4, objstream); } } } } typedef struct RelocationPatch RelocationPatch; struct RelocationPatch { RelocationPatch *cdr; long fpos; Symstr *sym; int32 flags; }; static RelocationPatch *relocationpatches; static int32 obj_coderelocation(void) { CodeXref *x; int32 n = 0; aof_reloc r; for (x = codexrefs; x!=NULL; x = x->codexrcdr) { Symstr *s = x->codexrsym; int32 ix = obj_checksym_1(s); RelocationPatch *p = NULL; if (ix < 0) { p = (RelocationPatch *)GlobAlloc(SU_Xref, sizeof(RelocationPatch)); ix = 0; } r.rel_offset = x->codexroff & 0xffffff; r.rel_flags = REL_TYPE2 + REL_LONG + ix; switch (x->codexroff & 0xff000000) { #ifdef TARGET_HAS_DATA_VTABLES case X_absreloc: /* DCD <sym> - for vtables */ if (debugging(DEBUG_OBJ)) cc_msg("absreloc$r ", s); break; #endif case X_DataAddr1: /* PC rel ref to external: sequence to be relocated = 2 */ r.rel_flags |= REL_R | REL_INSTR | (2<<29); if (debugging(DEBUG_OBJ)) cc_msg("pcreloc2$r ", s); break; case X_PCreloc: /* PC rel ref to external */ #ifdef TARGET_IS_THUMB /* ECN: disgusting bodge really, bit 0 of offset => Thumb reloc */ r.rel_offset += 1; /* ??? */ #ifdef THUMB_CPLUSPLUS case X_PCreloc_32: #endif #endif r.rel_flags |= REL_R | REL_INSTR; if (debugging(DEBUG_OBJ)) cc_msg("pcreloc$r ", s); break; case X_TailCall: /* as PCreloc, but used in tailcall */ r.rel_flags |= REL_R | REL_B | REL_INSTR; if (debugging(DEBUG_OBJ)) cc_msg("tailcall$r ", s); break; case X_DataVal: r.rel_flags |= REL_B | REL_INSTR; #ifdef TARGET_IS_THUMB r.rel_offset += 1; #endif if (debugging(DEBUG_OBJ)) cc_msg("basereloc$r ", s); break; case X_backaddrlit: /* abs ref to external */ if (debugging(DEBUG_OBJ)) cc_msg("addreloc$r ", s); break; default: syserr(syserr_obj_codereloc, (long)x->codexroff); continue; } if (p != NULL) { obj_fwrite(&r.rel_offset, 4, 1, objstream); cdr_(p) = relocationpatches; p->fpos = ftell(objstream); p->sym = s; p->flags = r.rel_flags; relocationpatches = p; obj_fwrite(&r.rel_flags, 4, 1, objstream); } else obj_fwrite(&r, 4, sizeof(r)/4, objstream); n++; } codexrefs = 0; return n; } /* obj_datarelocation() is now also used for debug table relocation. */ static int32 obj_datarelocation(DataXref *x, int32 offset) { int32 n = 0; aof_reloc r; for (; x!=NULL; x = x->dataxrcdr) { Symstr *s = x->dataxrsym; /* all data relocs are X_backaddrlit (abs ref) so far */ r.rel_offset = x->dataxroff+offset; r.rel_flags = REL_TYPE2 + REL_LONG + obj_checksym(s); obj_fwrite(&r, 4, sizeof(r)/4, objstream); if (debugging(DEBUG_OBJ)) cc_msg("data reloc $r ", s); n++; } return n; } static void obj_writedata(DataInit *p) /* follows gendc exactly! */ { for (; p != NULL; p = p->datacdr) { int32 rpt = p->rpt, sort = p->sort, len = p->len; unsigned32 val = p->val; IPtr ptrval = p->val; switch (sort) { case LIT_LABEL: /* name only present for c.armasm */ break; default: syserr(syserr_obj_gendata, (long)sort); case LIT_BXXX: /* The following are the same as LIT_NUMBER */ case LIT_BBX: /* for cross-sex compilation */ case LIT_BBBX: case LIT_BBBB: case LIT_HX: case LIT_HH: case LIT_BBH: case LIT_HBX: case LIT_HBB: if (byte_reversing) { unsigned32 t; val = totargetsex(val, (int)sort); t = val ^ ((val << 16) | (val >> 16)); /* ...v ROR 16 */ t &= ~0xff0000; val = (val << 24) | (val >> 8); /* v = v ROR 8 */ val = val ^ (t >> 8); } while (rpt-- != 0) obj_fwrite(&val, 1, len, objstream); break; case LIT_NUMBER: if (len != 4) syserr(syserr_obj_datalen, (long)len); /* drop through */ case LIT_ADCON: /* (possibly external) name + offset */ /* beware: sex dependent... */ while (rpt-- != 0) obj_fwrite(&val, 4, 1, objstream); break; case LIT_FPNUM: { FloatCon *fc = (FloatCon *)ptrval; /* do we need 'len' when the length is in fc->floatlen?? */ if (len != 4 && len != 8) syserr(syserr_obj_data1, (long)rpt, (long)len, fc->floatstr); /* The following strage code ensures that doubles are correctly */ /* sex-reversed if required to be - obj_fwrite() only reverses */ /* items of length 4... This is a trap for the unwary. */ while (rpt-- != 0) { obj_fwrite(&(fc->floatbin.db.msd), 4, 1, objstream); if (len == 4) continue; obj_fwrite(&(fc->floatbin.db.lsd), 4, 1, objstream); } } break; } } } static int32 obj_outcommonareas(void) { CommonDef *p; int32 size = 0; for (p = commondefs; p != NULL; p = p->next) { obj_writedata(p->data.head); size += p->data.size; } return size; } /* exported functions... */ int32 obj_symref(Symstr *s, int flags, int32 loc) { ExtRef *x; if ((x = symext_(s)) == NULL) /* saves a quadratic loop */ { if (obj_symcount >= 0x10000) cc_fatalerr(armobj_fatalerr_toomany); x = (ExtRef*) GlobAlloc(SU_Xsym, sizeof(ExtRef)); x->extcdr = obj_symlist, x->extsym = s, x->extflags = 0, x->extoffset = 0, x->codesym = 0; reg_setallused(&x->usedregs); if (flags & OBJ_DUMMYSYM) x->extindex = 0; else if (s == bindsym_(datasegment)) flags |= OBJ_REPLACEBYAREA | OBJ_DELETED, x->extindex = 0, x->codesym = data_sym; else if (s == bindsym_(ddtorsegment)) flags |= OBJ_REPLACEBYAREA | OBJ_DELETED, x->extindex = 0, x->codesym = ddtor_sym; else if (s == bindsym_(bsssegment)) flags |= OBJ_REPLACEBYAREA | OBJ_DELETED, x->extindex = 0, x->codesym = bss_sym; else if (s == bindsym_(codesegment)) flags |= OBJ_REPLACEBYAREA | OBJ_DELETED, x->extindex = 0; /* codesym filled in later */ else if (s == adconpool_lab) flags |= OBJ_REPLACEBYAREA | OBJ_DELETED, x->extindex = 0, x->codesym = adcon_sym; else if (s == extable_sym) flags |= OBJ_REPLACEBYAREA | OBJ_DELETED, x->extindex = 0, x->codesym = extable_sym; else if (s == exhandler_sym) flags |= OBJ_REPLACEBYAREA | OBJ_DELETED, x->extindex = 0, x->codesym = exhandler_sym; else { DebugAreaDesc *p = debugareas; for (; p != NULL; p = cdr_(p)) if (s == p->refsym) { flags |= OBJ_REPLACEBYAREA | OBJ_DELETED, x->extindex = 0, x->codesym = p->sym; break; } if (p == NULL) { #ifdef CONST_DATA_IN_CODE if (s == bindsym_(constdatasegment)) flags |= xr_dataincode; #endif #ifdef THUMB_CPLUSPLUS /* ECN: This is not pretty. What we need is something like * b_constdata in the binder which can be converted to * xr_dataincode when obj_symref is called. Can we use * b_memfns for this??? */ if (strncmp(symname_(s), "__VTABLE", 8) == 0) flags |= xr_dataincode; #endif x->extindex = obj_symcount++; } } obj_symlist = symext_(s) = x; } /* The next few lines cope with further ramifications of the abolition of */ /* xr_refcode/refdata in favour of xr_code/data without xr_defloc/defext */ /* qualification. This reduces the number of bits, but needs more */ /* checking in that a symbol defined as data, and then called via */ /* casting to a code pointer may acquire defloc+data and then get */ /* xr_code or'ed in. Suffice it to say this causes confusion. */ /* AM wonders if gen.c ought to be more careful instead. */ if (flags & (xr_defloc+xr_defext)) { if (x->extflags & (xr_defloc+xr_defext)) { /* can only legitimately happen for a tentatively defined object */ /* in which case both flags and x->extflags should have type */ /* xr_data. Perhaps I should check ? */ } else x->extflags &= ~(xr_code+xr_data); } else if (x->extflags & (xr_defloc+xr_defext)) flags &= ~(xr_code+xr_data); /* end of fix. */ x->extflags |= flags; /* do some checking here */ if (flags & xr_defloc+xr_defext) { /* private or public data/code */ if (flags & xr_code) x->codesym = codeareaq->aaxb.asv; else if (curcommon->index > 0) { x->extflags |= (xr_idxtoflag_(curcommon->index)); if ((flags & xr_cblock) && x->extoffset == 0) ++ncommonareas; else curcommon->refsize = x->extoffset; } x->extoffset = loc; } else if ((loc > 0) && !(flags & xr_code)) { /* common data */ /* * NOTE: 'loc' is the size of the referenced common area. */ if (x->extflags & xr_cblock) { CommonDef *p = findcommondef(xr_flagtoidx_((int32)x->extflags)); if (p->data.size < loc) cc_err(obj_err_common2, s); } else { int32 oldsize = x->extoffset; if (oldsize ==0) ++ncommonareas; /* first occurrence */ if (loc > oldsize) x->extoffset = loc; } } /* The next line returns the offset of a function in the codesegment */ /* if it has been previously defined -- this saves store on the arm */ /* and allows short branches on other machines. Otherwise it */ /* returns -1 for undefined objects or data objects. */ return ((x->extflags & (xr_defloc+xr_defext)) && (x->extflags & xr_code) && (x->codesym == codeareaq->aaxb.asv) ? x->extoffset : -1); } /* Add a symbol even if it already exists */ int32 obj_symdef(Symstr *s, int flags, int32 loc) { symext_(s) = NULL; return obj_symref(s, flags, loc); } static void obj_end_codearea() { aof_area *aa = &codeareaq->aaxa; if (debugging(DEBUG_OBJ)) cc_msg("coderelocation\n"); #ifdef TARGET_HAS_HALFWORD_INSTRUCTIONS /* ECN: Individual code blocks may not be word size but the AREA must be */ codebase = obj_pad(codebase); #endif codeareasize += (aa->area_size = codebase); codeareasize += (aa->area_nrelocs = obj_coderelocation()) * sizeof(aof_reloc); if (aa->area_size != 0) ++ncodeareas; } static void obj_start_codearea() { Symstr *sv; char name[256]; size_t l; aof_xarea *h = (aof_xarea *) GlobAlloc(SU_Other, sizeof(aof_xarea)); codeareaq->aaxb.anext = h; codeareaq = h; memset(&h->aaxa, 0, sizeof(h->aaxa)); h->aaxb.anext = NULL; l = strlen(symname_(bindsym_(codesegment)))+1; if (l > (sizeof(name)-1)) l = sizeof(name)-1; strncpy(name+1, symname_(bindsym_(codesegment)), l); name[l] = 0; name[0] = 'C'; name[1] = '$'; h->aaxb.asv = sv = sym_insert_id(name); h->aaxa.area_attributes |= AOF_CODEAT; if (obj_iscommoncode()) h->aaxa.area_attributes |= AOF_COMDEFAT; #ifdef TARGET_IS_THUMB if (!obj_isvtable()) h->aaxa.area_attributes |= AOF_THUMB; #endif obj_symref(sv, OBJ_DUMMYSYM, 0L); } #ifdef PUT_FILE_NAME_IN_AREA_NAME static void putfilenameinareaname(char *buffer, char *basename, char *sourcefile) { UnparsedName un; int baselen = strlen(basename); /* remember how long the basename is */ fname_parse(sourcefile, FNAME_INCLUDE_SUFFIXES, &un); memcpy(buffer, basename, baselen); /* put it in the buffer */ memcpy(&buffer[baselen], un.root, un.rlen); buffer[baselen+un.rlen] = 0; } #endif static void obj_add_extable_area(void) { if (extable_size() == 0) return; #ifdef PUT_FILE_NAME_IN_AREA_NAME { char name[256]; putfilenameinareaname(name, "x$et_", sourcefile); codebuf_reinit1(name); } #else codebuf_reinit1(symname_(bindsym_(extablesegment))); #endif } static void obj_add_exhandler_area(void) { if (exhandler_size() == 0) return; #ifdef PUT_FILE_NAME_IN_AREA_NAME { char name[256]; putfilenameinareaname(name, "x$et_", sourcefile); codebuf_reinit1(name); } #else codebuf_reinit1(symname_(bindsym_(exhandlersegment))); #endif } #ifdef CONST_DATA_IN_CODE static void obj_add_constdata_area(void) { if (constdata_size() == 0) return; obj_clearcommoncode(); #ifdef PUT_FILE_NAME_IN_AREA_NAME { char name[256]; putfilenameinareaname(name, "x$cd_", sourcefile); codebuf_reinit1(name); } #else codebuf_reinit1(symname_(bindsym_(constdatasegment))); #endif codeareaq->aaxa.area_attributes &= ~(AOF_CODEAT+AOF_THUMB); } #endif void obj_startdebugarea(char const *name) { DebugAreaDesc *p = debugareas; for (; p != NULL; p = cdr_(p)) if (strcmp(name, symname_(p->sym)) == 0) break; if (p == NULL) syserr("obj_startdebugarea %s", name); curdebugarea = p; } void obj_enddebugarea(char const *name, DataXref *relocs) { DebugAreaDesc *p = curdebugarea; if (p == NULL) syserr("obj_enddebugarea %s", name); if (p->size & 3) syserr("area %s size %x", name, p->size); curdebugarea = NULL; p->nrelocs = obj_datarelocation(relocs, 0L); } Symstr *obj_notedebugarea(char const *name) { DebugAreaDesc *p = (DebugAreaDesc *)GlobAlloc(SU_Dbg, sizeof(*p)); *debugareas_tail = p; debugareas_tail = &cdr_(p); cdr_(p) = NULL; p->sym = sym_insert_id(name); p->size = 0; p->nrelocs = 0; obj_symref(p->sym, OBJ_DUMMYSYM, 0L); { char s[64]; s[0] = s[1] = '$'; strcpy(&s[2], name); p->refsym = sym_insert_id(s); obj_symref(p->refsym, xr_data, 0L); } return p->refsym; } void obj_init(void) { debugareas = NULL; debugareas_tail = &debugareas; ncommonareas = ncodeareas = nareas = 0; codeareasize = 0, ndatarelocs = 0, nadconrelocs = 0; obj_stringpos = 0, obj_symcount = 0, aof_hdr_offset = 0; obj_symlist = NULL; codexrefs = NULL, dbgxrefs = NULL; commondefs = NULL; curcommon = &dataarea; dataarea.index = -1; codeareap = codeareaq = &_areahdr_; _areahdr_.aaxb.anext = NULL; memset(&_areahdr_.aaxa, 0, sizeof(_areahdr_.aaxa)); #ifdef TARGET_IS_THUMB _areahdr_.aaxa.area_attributes |= AOF_CODEAT+AOF_THUMB; #else _areahdr_.aaxa.area_attributes |= AOF_CODEAT; #endif relocationpatches = NULL; #ifdef PUT_FILE_NAME_IN_AREA_NAME { /* BJS: Find the leaf name */ char name[256]; putfilenameinareaname(name, "C$$c_", sourcefile); obj_symref(_areahdr_.aaxb.asv = sym_insert_id(name), OBJ_DUMMYSYM, 0L); putfilenameinareaname(name, "C$$data_", sourcefile); obj_symref(data_sym = sym_insert_id(name), OBJ_DUMMYSYM, 0L); putfilenameinareaname(name, "C$$zidata_", sourcefile); obj_symref(bss_sym = sym_insert_id(name), OBJ_DUMMYSYM, 0L); putfilenameinareaname(name, "C$$extable_", sourcefile); obj_symref(extable_sym = sym_insert_id(name), OBJ_DUMMYSYM, 0L); putfilenameinareaname(name, "C$$exhandler_", sourcefile); obj_symref(exhandler_sym = sym_insert_id(name), OBJ_DUMMYSYM, 0L); } #else obj_symref(_areahdr_.aaxb.asv = sym_insert_id("C$$code"), OBJ_DUMMYSYM, 0L); obj_symref(data_sym = sym_insert_id("C$$data"), OBJ_DUMMYSYM, 0L); obj_symref(bss_sym = sym_insert_id("C$$zidata"), OBJ_DUMMYSYM, 0L); obj_symref(extable_sym = sym_insert_id("C$$extable"), OBJ_DUMMYSYM,0L); obj_symref(exhandler_sym = sym_insert_id("C$$exhandler"), OBJ_DUMMYSYM,0L); #endif obj_symref(ddtor_sym = sym_insert_id("C$$ddtorvec"), OBJ_DUMMYSYM, 0L); obj_symref(adcon_sym= sym_insert_id("sb$$adcons"),OBJ_DUMMYSYM, 0L); adconpool_lab = sym_insert_id("x$adcons"); byte_reversing = (target_lsbytefirst != host_lsbytefirst); thisCodeAreaIsEmpty = YES; } static void obj_cf_header(int32 areachunk_size) { char space[sizeof(cf_header) + (OBJ_MAXCHUNKS-1)*sizeof(cf_entry)]; /* Beware alignment problems here (non-portable C). */ cf_header *cfh = (cf_header *)space; cf_entry *cfe = cfh->cf_chunks; int32 i, offset, size; char *chunknames = "OBJ_HEADOBJ_AREAOBJ_IDFNOBJ_SYMTOBJ_STRT"; memset(space, 0, sizeof(space)); cfh->cf_magic = CF_MAGIC; cfh->cf_maxchunks = OBJ_MAXCHUNKS; cfh->cf_numchunks = OBJ_NUMCHUNKS; for (i = 0; i < OBJ_NUMCHUNKS; i++) { memcpy(cfe[i].cfe_key, chunknames + i*8, 8); if (byte_reversing) { int32 *p = (int32 *)(cfe[i].cfe_key); p[0] = totargetsex(p[0], LIT_BBBB); p[1] = totargetsex(p[1], LIT_BBBB); } } cfe[0].cfe_offset = aof_hdr_offset; cfe[0].cfe_size =offsetof(aof_header,aof_areas) + nareas*sizeof(aof_area); offset = sizeof(space); cfe[1].cfe_offset = offset; cfe[1].cfe_size = areachunk_size; offset += areachunk_size; size = CC_BANNERlen; cfe[2].cfe_offset = offset; cfe[2].cfe_size = size; offset += size; size = obj_symcount * sizeof(aof_symbol); cfe[3].cfe_offset = offset; cfe[3].cfe_size = size; offset += size; cfe[4].cfe_offset = offset; cfe[4].cfe_size = obj_stringpos; obj_fwrite_cnt = 0; obj_fwrite(space, 4, sizeof(space)/4, objstream); } void obj_header(void) { obj_cf_header(0); } static int SetExtIndex(int32 size, Symstr *s, int i) { ExtRef *x = symext_(s); if (x == NULL) syserr(syserr_obj_checksym, s); else if (size != 0) x->extindex = i++; else x->extflags |= OBJ_DELETED; return i; } static void number_areas(void) { aof_xarea *a; int i = 1; for (a = codeareap; a != NULL; a = a->aaxb.anext) i = SetExtIndex(a->aaxa.area_size, a->aaxb.asv, i); i = SetExtIndex(data_size(), data_sym, i); i = SetExtIndex(bss_size, bss_sym, i); i = SetExtIndex(adconpool.size, adcon_sym, i); i = SetExtIndex(ddtor_vecsize(), ddtor_sym, i); i = SetExtIndex(extable_size(), extable_sym, i); i = SetExtIndex(exhandler_size(), exhandler_sym, i); { DebugAreaDesc *p = debugareas; for (; p != NULL; p = cdr_(p)) i = SetExtIndex(dbg_debugareaexists(symname_(p->sym)), p->sym, i); } } static void obj_aof_header(void) { aof_header h; aof_area d; aof_xarea *a; obj_outcommonheaders(NO); /* to count ncommonareas reliably */ nareas = ncodeareas + ncommonareas; if (data_size() != 0) ++nareas; if (bss_size != 0) ++nareas; if (adconpool.size != 0) ++nareas; if (ddtor_vecsize() != 0) ++nareas; { DebugAreaDesc *p = debugareas; for (; p != NULL; p = cdr_(p)) if (dbg_debugareaexists(symname_(p->sym))) ++nareas; } h.aof_type = AOF_RELOC; /* relocatable object file */ h.aof_vsn = AOF_VERSION; /* version */ h.aof_nareas = nareas; h.aof_nsyms = obj_symcount; h.aof_entryarea = 0; h.aof_entryoffset = 0; /* start address offset */ obj_fwrite(&h, 4, offsetof(aof_header,aof_areas)/4, objstream); /* now the code area decls */ { int32 attributes = 2 + AOF_CODEAT + AOF_RONLYAT; if (pcs_flags & PCS_CALLCHANGESPSR) attributes |= AOF_32bitAT; if (pcs_flags & PCS_REENTRANT) attributes |= AOF_REENTAT | AOF_PICAT; if (pcs_flags & PCS_FPE3) attributes |= AOF_FP3AT; if (pcs_flags & PCS_NOSTACKCHECK) attributes |= AOF_NOSWSTKCK; if (pcs_flags & PCS_INTERWORK) attributes |= AOF_INTERWORK; for (a = codeareap; a != NULL; a = a->aaxb.anext) { aof_area *aa = &a->aaxa; aa->area_base = 0; aa->area_name = obj_checksym(a->aaxb.asv); if (aa->area_attributes & AOF_CODEAT) aa->area_attributes |= attributes; else aa->area_attributes |= 2 + AOF_RONLYAT; if (aa->area_size == 0) continue; /* ALPHA: dodgy size -- find all aof_area's */ obj_fwrite(aa, 4, sizeof(aof_area)/4, objstream); } } /* ... and the data */ if (data_size() != 0) { memset(&d, 0, sizeof(d)); d.area_name = obj_checksym(data_sym); d.area_attributes = 2; /* 4-align */ d.area_size = data_size(); d.area_nrelocs = ndatarelocs; obj_fwrite(&d, 4, sizeof(aof_area)/4, objstream); } /* ... and the data */ if (bss_size != 0) { memset(&d, 0, sizeof(d)); d.area_name = obj_checksym(bss_sym); d.area_attributes = 2 + AOF_0INITAT; d.area_size = bss_size; /*d.area_nrelocs = 0;*/ obj_fwrite(&d, 4, sizeof(aof_area)/4, objstream); } /* ... and the adcon table (if apcs_flags & REENTRANT) */ if (adconpool.size != 0) { memset(&d, 0, sizeof(d)); d.area_name = obj_checksym(adcon_sym); d.area_attributes = 2 + AOF_RONLYAT+AOF_BASEDAT+(R_SB<<AOF_BASESHIFT); d.area_size = adconpool.size; d.area_nrelocs = nadconrelocs; obj_fwrite(&d, 4, sizeof(aof_area)/4, objstream); } /* ... and the ddtorvec */ memset(&d, 0, sizeof(d)); if ((d.area_size = ddtor_vecsize()) != 0) { d.area_name = obj_checksym(ddtor_sym); d.area_attributes = 2 + AOF_0INITAT; obj_fwrite(&d, 4, sizeof(aof_area)/4, objstream); } /* ... and the extable */ memset(&d, 0, sizeof(d)); if ((d.area_size = extable_size()) != 0) { d.area_name = obj_checksym(extable_sym); d.area_attributes = 2 + AOF_RONLYAT; obj_fwrite(&d, 4, sizeof(aof_area)/4, objstream); } /* ... and the exhandler */ memset(&d, 0, sizeof(d)); if ((d.area_size = exhandler_size()) != 0) { d.area_name = obj_checksym(exhandler_sym); d.area_attributes = 2 + AOF_RONLYAT; obj_fwrite(&d, 4, sizeof(aof_area)/4, objstream); } /* ... and the debug areas */ { DebugAreaDesc *p = debugareas; for (; p != NULL; p = cdr_(p)) if (dbg_debugareaexists(symname_(p->sym))) { memset(&d, 0, sizeof(d)); d.area_size = p->size; d.area_name = obj_checksym(p->sym); d.area_attributes = 2 + AOF_RONLYAT + AOF_DEBUGAT; d.area_nrelocs = p->nrelocs; obj_fwrite(&d, 4, sizeof(aof_area)/4, objstream); } } obj_outcommonheaders(YES); } void obj_trailer(void) { int32 area_siz; char b[64]; if (has_main) obj_symref(libentrypoint, xr_code, 0); strcpy(b, "Lib$$Request$$armlib$$"); target_lib_variant(&b[22]); obj_symref(sym_insert_id(b), xr_code+xr_weak, 0); /* just a reference to __main is enough to cause the library module */ /* containing it to be loaded. */ localcg_endcode(); #ifdef CONST_DATA_IN_CODE obj_add_constdata_area(); { int32 n; constdatabase = codebase; if (constdata_size() != 0) { obj_symref(bindsym_(constdatasegment), xr_code+xr_defloc, constdatabase); obj_writedata(constdata_head()); codebase += constdata_size(); } #endif obj_end_codearea(); number_areas(); #ifdef CONST_DATA_IN_CODE n = obj_datarelocation(constdata_xrefs(), constdatabase); codeareaq->aaxa.area_nrelocs += n; codeareasize += n * sizeof(aof_reloc); } #endif if (relocationpatches != NULL) { long fpos = ftell(objstream); RelocationPatch *p; for (p = relocationpatches; p != NULL; p = cdr_(p)) { fseek(objstream, p->fpos, SEEK_SET); p->flags |= obj_checksym(p->sym); obj_fwrite(&p->flags, 4, 1, objstream); } fseek(objstream, fpos, SEEK_SET); } area_siz = codeareasize; if (debugging(DEBUG_OBJ)) cc_msg("writedata\n"); obj_writedata(data_head()); if (debugging(DEBUG_OBJ)) cc_msg("datarelocation\n"); ndatarelocs = obj_datarelocation(data_xrefs(), 0L); area_siz += data_size() + ndatarelocs*sizeof(aof_reloc); if (adconpool.size != 0) { if (debugging(DEBUG_OBJ)) cc_msg("writeadcons\n"); adconpool_flush(); if (debugging(DEBUG_OBJ)) cc_msg("adconrelocation\n"); nadconrelocs = obj_datarelocation(adconpool.xrefs, 0L); area_siz += adconpool.size + nadconrelocs*sizeof(aof_reloc); } if (extable_size() != 0) { obj_add_extable_area(); obj_symref(bindsym_(extablesegment), xr_constdata, extablebase); obj_writedata(extable_head()); area_siz += extable_size(); } /*extable and exhandler segments will both be present or both absent.*/ if (exhandler_size() != 0) { obj_add_exhandler_area(); obj_symref(bindsym_(exhandlersegment), xr_constdata, exhandlerbase); obj_writedata(exhandler_head()); area_siz += exhandler_size(); } #ifdef TARGET_HAS_DEBUGGER if (debugging(DEBUG_OBJ)) cc_msg("writedebug\n"); dbg_writedebug(); { DebugAreaDesc *p = debugareas; for (; p != NULL; p = cdr_(p)) area_siz += p->size + p->nrelocs * sizeof(aof_reloc); } #endif area_siz += obj_outcommonareas(); if (debugging(DEBUG_OBJ)) cc_msg("symtab\n"); obj_fwrite(CC_BANNER, 1, CC_BANNERlen, objstream); obj_outsymtab(); aof_hdr_offset = ftell(objstream); obj_aof_header(); if (debugging(DEBUG_OBJ)) cc_msg("rewind\n"); /* It is (unexpectedly) vital to use fseek here rather than rewind, since */ /* rewind clears error flags. Note further that if there is a partially */ /* full buffer just before the rewind & flushing that data causes an error */ /* (e.g. because there is no room on disc for it) this error seems to get */ /* lost. This looks to me like a shambles in the October 1986 ANSI draft! */ fseek(objstream, 0L, SEEK_SET); /* works for hex format too */ /* The next line represents a balance between neurotic overchecking and */ /* the fact that it would be nice to detect I/O errors before the end of */ /* compilation. */ if (ferror(objstream)) cc_fatalerr(obj_fatalerr_io_object); if (debugging(DEBUG_OBJ)) cc_msg("rewriting header\n"); obj_cf_header(area_siz);/* re-write header at top of file */ /* file now closed in main() where opened */ } /* end of armobj.c */ DataDesc adconpool; Symstr *adconpool_lab; int adconpool_find(int32 w, int32 flavour, Symstr *sym) { int i; DataInit *p; if (adconpool.size == 0) obj_symref(adconpool_lab, xr_defloc+xr_adcon, 0); else for (i = 0, p = adconpool.head; p != 0; p = p->datacdr) { if (p->sort == flavour && p->val == w && (Symstr *)p->len == sym) return i; /* allow for label as first item */ if (p->sort != LIT_LABEL) i += 4; } { int32 offset = adconpool.size; adconpool.xrefs = (DataXref *)global_list3(SU_Xref, adconpool.xrefs, offset, sym); p = (DataInit *)global_list5(SU_Other, NULL, 1, flavour, sym, w); adconpool.tail->datacdr = p; adconpool.tail = p; adconpool.size += 4; return (int)offset; } } void adconpool_flush(void) { obj_writedata(adconpool.head); } void adconpool_init(void) { adconpool.head = adconpool.tail = (DataInit *)global_list3(SU_Other, NULL, adconpool_lab, LIT_LABEL); adconpool.size = 0; adconpool.xrefs = NULL; adconpool.xrarea = 0; }
stardot/ncc
mip/sr.h
<gh_stars>0 /* * sr.h: binder live range splitting * Copyright (C) Advanced Risc Machines Ltd., 1993 * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _sr_h #define _sr_h struct SuperBinder { SuperBinder *cdr; Binder *binder; int32 spillcount; }; extern SuperBinder *superbinders; extern BindList *splitranges(BindList *local_binders, BindList *regvar_binders); extern void splitrange_init(void); #endif
stardot/ncc
tests/1929.c
<filename>tests/1929.c /* * ARM C compiler regression test $RCSfile$ * Copyright (C) 1995 Advanced Risc Machines Ltd. All rights reserved. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include "testutil.h" /********************* 1929 ***********************/ int __global_reg(1) x0; int __global_reg(2) x1; int __global_reg(3) x2; int __global_reg(4) x3; int __global_reg(5) x4; int __global_reg(6) x5; typedef struct { int a[1000]; signed char b; } S_1929; int f_1929(S_1929 *p, int a, int b, int c) { int corrupted; corrupted = p->a[0]; a += p->b; return corrupted + a + b + c; } void t_1929(void) { S_1929 s; s.b = -4; s.a[0] = 98; EQI(f_1929(&s, 1, 2, 3), 100); } /********************* main ***********************/ int main(void) { BeginTest(); t_1929(); EndTest(); }
stardot/ncc
mip/builtin.h
/* * mip/builtin.h: * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Codemist Ltd., 1987-1992. * Copyright (C) Advanced RISC Machines Limited, 1991-1992. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _builtin_h #define _builtin_h #ifndef _defs_LOADED # include "defs.h" #endif extern FloatCon *fc_two_31; /* floating point constant 2^31 */ typedef struct { FloatCon *s; /* short version */ FloatCon *d; /* double version */ } FPConst; extern FPConst fc_zero; /* floating point constants 0.0 */ #ifdef PASCAL /*ECN*/ extern FPConst fc_half; /* 0.5 */ extern FPConst fc_big; /* FLT or DBL MAX */ #endif extern FPConst fc_one; /* 1.0 */ extern FPConst fc_two; /* 2.0 */ extern FPConst fc_minusone; /* -1.0 */ extern TypeExpr *te_boolean; /* == te_int in C */ extern Expr *lit_false; /* (int)0 in C */ extern Expr *lit_true; /* (int)1 in C */ extern Expr *lit_zero; extern Expr *lit_one; extern TypeExpr *te_char; /* = (global)primtype_(bitoftype_(s_char)) */ extern TypeExpr *te_int; /* = (global)primtype_(bitoftype_(s_int)) */ extern TypeExpr *te_ushort, *te_uint, *te_lint, *te_ulint; /* and friends */ extern TypeExpr *te_llint, *te_ullint; extern TypeExpr *te_stringchar, *te_wstringchar, *te_wchar; #ifdef EXTENSION_UNSIGNED_STRINGS extern TypeExpr *te_ustringchar; #endif extern TypeExpr *te_double; /* = (global)primtype_(bitoftype_(s_double)) */ extern TypeExpr *te_float; /* its short friend */ extern TypeExpr *te_ldble; /* and its long one */ extern TypeExpr *te_void; /* = (global)primtype_(bitoftype_(s_void)) */ extern TypeExpr *te_charptr; /* = (global)ptrtotype_(te_char))) */ extern TypeExpr *te_intptr; /* = (global)ptrtotype_(te_int))) */ extern TypeExpr *te_voidptr; /* = (global)ptrtotype_(te_void))) */ extern TypeExpr *te_fntype(TypeExpr *res, TypeExpr *a1, TypeExpr *a2, TypeExpr *a3, TypeExpr *a4, TypeExpr *a5); extern TypeExpr *g_te_fntype(TypeExpr *res, TypeExpr *a1, TypeExpr *a2, TypeExpr *a3, TypeExpr *a4, TypeExpr *a5); #define te_size_t (feature & FEATURE_PCC ? te_int : te_uint) extern Binder *datasegment, *codesegment, *constdatasegment, *ddtorsegment; #ifdef TARGET_HAS_BSS extern Binder *bsssegment; #endif Binder *extablesegment, *exhandlersegment; extern Symstr *mainsym, *setjmpsym, *assertsym, *first_arg_sym, *last_arg_sym; #define DUFF_SYMSTR ((Symstr*)DUFF_ADDR) #ifdef CPLUSPLUS extern Symstr *thissym, *ctorsym, *dtorsym, *assignsym, *vtabsym, *deletesym, *dtorgenlabsym; #else #define thissym DUFF_SYMSTR #define ctorsym DUFF_SYMSTR #define dtorsym DUFF_SYMSTR #define assignsym DUFF_SYMSTR #define vtabsym DUFF_SYMSTR #define deletesym DUFF_SYMSTR #define dtorgenlabsym DUFF_SYMSTR #endif extern Symstr *libentrypoint, *stackoverflow, *stack1overflow, *countroutine, *count1routine; extern Symstr *traproutine, *targeterrno; typedef struct op_simulation { Expr *mulfn, *divfn, *udivfn, *divtestfn, *remfn, *uremfn; #ifdef TARGET_HAS_DIV_10_FUNCTION Expr *div10fn, *udiv10fn, *rem10fn, *urem10fn; #endif Expr *fdivfn, *ddivfn; Expr *memcpyfn, *memsetfn; Expr *inserted_word; Expr *readcheck1, *readcheck2, *readcheck4, *writecheck1, *writecheck2, *writecheck4; Expr *xprintf, *xfprintf, *xsprintf; Expr *realmemcpyfn, *realmemsetfn; Symstr *strcpysym, *strlensym; Symstr *yprintf, *yfprintf, *ysprintf; #ifdef STRING_COMPRESSION Expr *xprintf_z, *xfprintf_z, *xsprintf_z, *yprintf_z, *yfprintf_z, *ysprintf_z; #endif #ifdef RANGECHECK_SUPPORTED Symstr *abcfault, *valfault; #endif Expr *dadd, *dsubtract, *dmultiply, *ddivide, *dnegate, *dgreater, *dgeq, *dless, *dleq, *dequal, *dneq, *dfloat, *dfloatu, *dfix, *dfixu, *drsb, *drdiv; Expr *fadd, *fsubtract, *fmultiply, *fdivide, *fnegate, *fgreater, *fgeq, *fless, *fleq, *fequal, *fneq, *ffloat, *ffloatu, *ffix, *ffixu, *frsb, *frdiv; Expr *fnarrow, *dwiden; Expr *llnot, *llneg; Expr *lladd, *llrsb, *llsub, *llmul; Expr *llurdv, *lludiv, *llsrdv, *llsdiv; Expr *llurrem, *llurem, *llsrrem, *llsrem; Expr *lland, *llor, *lleor; Expr *llshiftl, *llushiftr, *llsshiftr; Expr *llcmpeq, *llcmpne; Expr *llucmpgt, *llucmplt, *llucmpge, *llucmple; Expr *llscmpgt, *llscmplt, *llscmpge, *llscmple; Expr *llfroml, *llfromu, *llsfromf, *llsfromd, *llufromf, *llufromd; Expr *lltol, *llstof, *llstod, *llutof, *llutod; Expr *proc_entry, *proc_exit; Symstr *dpow, *dfloor, *dceil, *dmod, *dabs; } op_simulation; extern op_simulation sim; #ifdef CPLUSPLUS typedef struct cpp_op_simulation { Symstr *xnew, *xdel; Binder *xpvfn; Expr *xpush_ddtor; Expr *x__throw; Expr *x__ex_pop; Expr *x__ex_push; Expr *x__ex_top; Expr *xnewvec, *xdelvec; Expr *xmapvec1, *xmapvec1c, *xmapvec1ci, *xmapvec2; } cpp_op_simulation; extern cpp_op_simulation cppsim; #endif extern bool returnsheapptr(Symstr *fn); extern void builtin_init(void); #endif /* end of mip/builtin.h */
stardot/ncc
mip/mcdep.h
/* * C compiler file mcdep.h * Copyright (C) Acorn Computers Ltd., 1988. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 4 * Checkin $Date$ * Revising $Author$ */ /* * (Interface for target-dependent part of local code generation). */ #ifndef _mcdep_h #define _mcdep_h 1 #ifndef _globals_LOADED #error include "mcdep.h" out of place /* We need globals.h loaded first (host/options/target/defaults). */ #endif #ifndef _cgdefs_LOADED # include "cgdefs.h" #endif #ifndef _jopcode_LOADED # include "jopcode.h" #endif #include "toolenv.h" /***************************************************************************/ /* Interface to the target code generator */ /***************************************************************************/ #ifdef TARGET_HAS_FP_LITERALS # ifndef fpliteral extern bool fpliteral(FloatCon const *val, J_OPCODE op); /* Returns true if the argument value can be represented as a literal operand * in the expansion of the argument operation (passing this allows for the * possibility of changing the operation, eg ADD to SUB, to allow use of a * literal). */ # endif #endif #ifndef immed_cmp extern bool immed_cmp(int32 n); /* False if this integer is to be a candidate to be held in a register through * loop optimisation. */ #endif #ifndef immed_op /* target.h may define this otherwise, to return 1 if n may be an immediate * operand in the expansion of J_OPCODE op. If the value is 0, CSE is more * enthusiastic about making a load of the value into a CSE or hoisting it * out of loops. * immed_cmp is a special case, sensibly defined as immed_op(n, J_CMPK) where * immed_op has a non-default value. */ # define immed_op(n, op) 1 #endif #ifndef TARGET_DOESNT_CHECK_SWIS int32 CheckSWIValue(int32); #else #define CheckSWIValue(n) (n) #endif #ifdef TARGET_INLINES_MONADS extern int32 target_inlinable(Binder const *b, int32 nargs); #endif #ifndef alterscc #define alterscc(ic) (sets_psr(ic) || corrupts_psr(ic)) #endif extern bool sets_psr(Icode const *ic); extern bool reads_psr(Icode const *ic); extern bool uses_psr(Icode const *ic); extern bool corrupts_psr(Icode const *ic); extern bool corrupts_r1(Icode const* ic); extern bool corrupts_r2(Icode const* ic); extern bool has_side_effects(Icode const *ic); extern void remove_writeback(Icode *ic); extern RealRegister local_base(Binder const *b); /* Returns the base register to be used in accessing the object b (must be * local). */ extern int32 local_address(Binder const *b); /* Returns the offset from local_base(b) to be used in accessing object b. */ extern void setlabel(LabelNumber *l); /* Sets the argument label at the current code position. * Although the idea of setlabel is target independent, it is in the mc-dep * interface because it back-patches code. * In the long term it should be in codebuf.c and call a target dependent * backpatch routine. */ extern void branch_round_literals(LabelNumber *m); /* Encouraged by a comment that only ARM used mustlitby, it has been removed from the codebuf interface, and the initialisations of it which used to happen in codebuf.c turned into calls of the following function. Targets which don't care will just refrain from setting localcg_newliteralpool_exists */ #ifdef localcg_newliteralpool_exists extern void localcg_newliteralpool(void); #else #define localcg_newliteralpool() 0 #endif #ifdef TARGET_HAS_MULTIPLE_CODE_AREAS void localcg_endcode(void); #endif extern void show_instruction(Icode const *const ic); extern void localcg_reinit(void); /* under threat (use J_ENTER) */ extern void localcg_tidy(void); /* ditto (use J_ENDPROC) */ typedef struct { RealRegSet use, /* registers read */ def, /* registers written */ c_in, /* registers corrupted on entry (clash with input regs) */ c_out; /* registers corrupted on exit (clash with output regs) */ } RealRegUse; /* returns the physical register usage of ic */ extern void RealRegisterUse(Icode const *ic, RealRegUse *u); #ifdef TARGET_IS_ARM_OR_THUMB bool UnalignedLoadMayUse(RealRegister r); /* A special purpose version of RealRegisterUse, but called before it's */ /* known what Icode the load is going to expand into. */ #endif /* Return the minimum/maximum offset a certain load/store can have (inclusive). Larger offsets require either IP to be reserved or a seperate base pointer. */ extern int32 MinMemOffset(J_OPCODE op); extern int32 MaxMemOffset(J_OPCODE op); /* Return the granularity of memory addresses for op. */ extern int32 MemQuantum(J_OPCODE op); typedef enum { JCHK_MEM = 1, JCHK_REGS = 2, JCHK_SYSERR = 256 } CheckJopcode_flags; extern char *CheckJopcode(const Icode *ic, CheckJopcode_flags flags); extern int multiply_cycles(int val, bool accumulate); /* return #cycles for a multiply */ /***************************************************************************/ /* Interface to the object code formatter */ /***************************************************************************/ extern void obj_codewrite(Symstr *name); /* (name == 0 && codep == 0) => called from just after the creation of a */ /* new code segment. bindsym_(codesegment) is the name of */ /* a symbol to be set at the base of the area (not */ /* the area name) */ /* (name == 0 && codep != 0) => called generation of a string literal */ /* (name != 0) => called after generation of code for a function */ extern void obj_init(void); extern void obj_header(void); extern void obj_trailer(void); extern void obj_common_start(Symstr *name); extern void obj_common_end(void); #define obj_setcommoncode() (var_cc_private_flags |= 0x40000000) /* set COMDEF attribute */ #define obj_clearcommoncode() (var_cc_private_flags &= ~0x40000000) #define obj_iscommoncode() (var_cc_private_flags & 0x40000000) #define obj_setvtable() (var_cc_private_flags |= 0x20000000) /* set COMDEF attribute */ #define obj_clearvtable() (var_cc_private_flags &= ~0x20000000) #define obj_isvtable() (var_cc_private_flags & 0x20000000) #ifdef TARGET_HAS_AOUT extern void obj_stabentry(struct nlist const *p); #endif #ifndef NO_ASSEMBLER_OUTPUT /***************************************************************************/ /* Interface to the assembly code generator */ /***************************************************************************/ extern void asm_header(void); extern void asm_trailer(void); extern void asm_setregname(int regno, char const *name); extern void display_assembly_code(Symstr const *); /* Entry conditions as for obj_codewrite. */ #endif /***************************************************************************/ /* Interface to the debug table generator */ /***************************************************************************/ #define DBG_LINE 1 /* line info -- reduces peepholing */ #define DBG_PROC 2 /* top level info -- no change to code */ #define DBG_VAR 4 /* local var info -- no leaf procs */ #define DBG_PP 8 #define DBG_OPT_CSE 0x10 #define DBG_OPT_REG 0x20 #define DBG_OPT_DEAD 0x40 #define DBG_OPT_ALL (DBG_OPT_CSE|DBG_OPT_REG|DBG_OPT_DEAD) #ifdef TARGET_DEBUGGER_WANTS_MACROS # define DBG_ANY (DBG_LINE|DBG_PROC|DBG_VAR|DBG_PP) #else # define DBG_ANY (DBG_LINE|DBG_PROC|DBG_VAR) #endif #ifdef TARGET_HAS_DEBUGGER /* Language independent type number, to be passed to dbg_tableindex */ #define DT_QINT 1 #define DT_HINT 2 #define DT_INT 3 #define DT_LINT 4 #define DT_UQINT 5 #define DT_UHINT 6 #define DT_UINT 7 #define DT_ULINT 8 #define DT_FLOAT 9 #define DT_DOUBLE 10 #define DT_EXTENDED 11 #define DT_COMPLEX 12 #define DT_LCOMPLEX 13 #define DT_QBOOL 14 #define DT_HBOOL 15 #define DT_BOOL 16 #define DT_LBOOL 17 #define DT_CHAR 18 #define DT_UCHAR 19 #define DT_MAX 19 extern char dbg_name[]; extern int usrdbgmask; # define usrdbg(DBG_WHAT) (usrdbgmask & (DBG_WHAT)) extern int32 dbg_tablesize(void); extern int32 dbg_tableindex(int32 dt_number); extern void *dbg_notefileline(FileLine fl); extern void dbg_addcodep(void *debaddr, int32 codeaddr); extern bool dbg_scope(BindListList *, BindListList *); extern void dbg_final_src_codeaddr(int32, int32); # ifdef DEBUGGER_NEEDS_NO_FRAMEPOINTER extern bool dbg_needsframepointer(void); # else # define dbg_needsframepointer() 1 # endif # ifdef TARGET_HAS_BSS # define DS_EXT 1 /* bits in stgclass argument of dbg_topvar */ # define DS_BSS 2 # define DS_CODE 4 # define DS_REG 8 # define DS_UNDEF 16 extern void dbg_topvar(Symstr *name, int32 addr, TypeExpr *t, int stgclass, FileLine fl); # else extern void dbg_topvar(Symstr *name, int32 addr, TypeExpr *t, bool ext, FileLine fl); # endif extern void dbg_type(Symstr *name, TypeExpr *t, FileLine fl); #ifndef NEW_DBG_PROC_INTERFACE extern void dbg_proc(Symstr *name, TypeExpr *t, bool ext, FileLine fl); #else extern void dbg_proc(Binder *b, TagBinder *parent, bool ext, FileLine fl); #endif extern void dbg_locvar(Binder *name, FileLine fl); extern void dbg_locvar1(Binder *name); /* used by F77 front-end */ extern void dbg_commblock(Binder *name, SynBindList *members, FileLine fl); extern void dbg_enterproc(void); extern void dbg_bodyproc(void); extern void dbg_return(int32 addr); extern void dbg_xendproc(FileLine fl); # ifdef TARGET_DEBUGGER_WANTS_MACROS typedef struct dbg_ArgList dbg_ArgList; struct dbg_ArgList { char const *name; dbg_ArgList *next; }; extern void dbg_define(char const *name, bool objectmacro, char const *body, dbg_ArgList const *args, FileLine fl); extern void dbg_undef(char const *name, FileLine fl); extern void dbg_include(char const *filename, char const *path, FileLine fl); extern void dbg_notepath(char const *pathname); # else # define dbg_undef(a, b) # define dbg_define(a, b, c, d, e) # define dbg_include(a, b, c) # define dbg_notepath(a) # endif extern void dbg_init(void); #else # define usrdbg(DBG_WHAT) ((int)0) # define dbg_tablesize() ((int32)0) # define dbg_tableindex(a) ((int32)0) # define dbg_notefileline(a) ((void *)0) # define dbg_init() ((void)0) # define dbg_scope(a,b) ((bool)0) # define dbg_addcodep(debaddr,codeaddr) ((void)0) # define dbg_enterproc() ((void)0) # define dbg_bodyproc() ((void)0) # define dbg_return(a) ((void)0) # define dbg_xendproc(a) ((void)0) # define dbg_type(a,b,c) ((void)0) # define dbg_proc(a,b,c,d) ((void)0) # define dbg_topvar(a,b,c,d,e) ((void)0) # define dbg_locvar(a,b) ((void)0) # define dbg_locvar1(a) ((void)0) # define dbg_commblock(a, b, c) ((void)0) # define dbg_undef(a, b) ((void)0) # define dbg_define(a, b, c, d, e) ((void)0) # define dbg_include(a, b,c) ((void)0) # define dbg_notepath(a) ((void)0) # define dbg_finalise() ((void)0) # define dbg_setformat(a) ((void)0) # define dbg_debugareaexists(a) ((bool)0) # define dbg_final_src_codeaddr(a, b) ((void)0) # define dbg_needsframepointer() 0 #endif /***************************************************************************/ /* Interface between debug table generator, object formatter and target */ /* code generator */ /***************************************************************************/ #ifdef TARGET_HAS_DEBUGGER #include "xrefs.h" int32 local_fpaddress(Binder const *b); /* Returns the offset of the object from the fp (assuming that fp and sp * have not been split in the frame containing the object ...). */ #define R_NOFPREG ((RealRegister)-1) RealRegister local_fpbase(Binder const *b); void dbg_writedebug(void); /* Call from the object formatter to the debug table generator to * cause tables to be output */ void obj_writedebug(void const *, int32); #define DBG_INTFLAG 0x80000000L /* flag in the size argument to obj_writedebug indicating that the things * being written are 4-byte ints (to be byte reversed if appropriate); */ #define DBG_SHORTFLAG 0x40000000L /* flag in the size argument to obj_writedebug indicating that the things * being written are 2-byte ints (to be byte reversed if appropriate); * If neither flag is present, they are byte strings to be written as * presented. */ void dbg_finalise(void); # ifdef TARGET_HAS_FP_OFFSET_TABLES typedef struct FPList FPList; typedef struct { FPList *fplist; int32 startaddr, endaddr, saveaddr; Symstr *codeseg; int32 initoffset; } ProcFPDesc; struct FPList { FPList *cdr; int32 addr; int32 change; }; void obj_notefpdesc(ProcFPDesc const *); # endif void dbg_setformat(char const *format); bool dbg_debugareaexists(char const *name); Symstr *obj_notedebugarea(char const *name); void obj_startdebugarea(char const *name); void obj_enddebugarea(char const *name, DataXref *relocs); #endif /***************************************************************************/ /* Target-dependent argument processing */ /***************************************************************************/ typedef enum { KW_NONE, KW_OK, KW_MISSINGARG, KW_BADARG, KW_OKNEXT, KW_BADNEXT } KW_Status; void mcdep_init(void); #ifdef TARGET_HAS_DATA_VTABLES bool mcdep_data_vtables(void); #endif #ifdef TARGET_SUPPORTS_TOOLENVS int mcdep_toolenv_insertdefaults(ToolEnv *t); extern KW_Status mcdep_keyword(char const *key, char const *nextarg, ToolEnv *t); void config_init(ToolEnv *t); void mcdep_set_options(ToolEnv *); #ifdef CALLABLE_COMPILER #define mcdep_config_option(n,t,e) ((bool)0) #else bool mcdep_config_option(char name, char const tail[], ToolEnv *t); #endif #else extern KW_Status mcdep_keyword(char const *key, int *argp, char **argv); void config_init(void); # ifdef CALLABLE_COMPILER #define mcdep_config_option(n,t) ((bool)0) # else bool mcdep_config_option(char name, char tail[]); void mcdep_debug_option(char name, char tail[]); # endif #endif #endif /* end of mcdep.h */
stardot/ncc
armthumb/mcerrs.h
/* * arm/mcerrs.h - prototype for machine-specific error messages file * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef NLS /* if NLS, miperrs will have included tags */ %O /* Ordinary error messages - mapped onto numeric codes */ /* * The following message is always machine specific since it may include * information about the source of support for the product. */ #define misc_disaster_banner "\n\ Internal inconsistency: either resource shortage or compiler fault. If you\n\ cannot alter your program to avoid this failure, please contact your supplier\n" #define mcdep_warn_fpinconsistent \ "Software floating point inconsistent with FPE2/3 and FPREGARGS" #define gen_warn_Lisp "Lisp-support stack push needed %ld" #define gen_err_swi "SWI number 0x%x too large" #define gen_err_irq "%s cannot handle __irq functions" #define obj_err_common "repeated common block $r" #define obj_err_common1 "common block $r too small" #define obj_err_common2 "common block $r too large" #define armobj_fatalerr_toomany "Too many symbols for ACORN linker" #define armdbg_fatalerr_toobig \ "Debug table size exceeds space in Acorn AOF format" #define asm_non_const "illegal constant (ignored): <unknown>" #define asm_nonconst1 "illegal constant expression (ignored): non constant $b" #define asm_nonconst2 "illegal constant expression (ignored): $s" #define asm_err_bad_shift "illegal shift specifier: %s" #define asm_err_expected_shift "shift specifier expected" #define asm_err_bad_opcode "illegal instruction opcode: %s" #define asm_err_bad_physreg "physical registername expected, but found %s instead" #define asm_err_bad_psrfield "illegal PSR field: %s" #define asm_err_expected_psr "PSR field expected" #define asm_err_bad_shiftval "shift value %d out of range" #define asm_err_expected_coproc "coprocessor identifier expected" #define asm_err_unknown_coproc "illegal coprocessor identifier: %s" #define asm_err_coproc_op_range "coprocessor operation out of range: %d" #define asm_err_ldrt_adrmode "preindexed addressing not available for LDRT/STRT" #define asm_err_no_mrs "MRS & MSR are not available on this architecture" #define asm_err_no_teqp "TEQP/TSTP/CMPP/CMNP are not available on this architecture" #define asm_err_no_longmul "long multiply is not available on this architecture" #define asm_err_no_halfword "halfword support is not available on this architecture" #define asm_err_corrupted_reg "R%d corrupted but possibly reused later. This code may not work correctly" #define asm_err_ldm_base_list "LDM/STM base with writeback in register list" #define asm_err_ldm_empty "LDM/STM with empty register list" #define asm_err_ldm_badlist "LDM/STM with illegal register list" #define asm_err_ldr_base_wb "LDR/STR base, [base] with writeback" #define asm_err_mul_conflict "MUL/MLA with Rd = Rm" #define asm_err_mull_conflict "MULL/MLAL with Rhi = Rlo, Rhi = Rm or Rlo = Rm" #define asm_err_swp_conflict "SWP with Rd = Rm, Rm = Rn or Rd = Rn" #define asm_err_pc "illegal use of PC as operand" #define asm_err_write_pc "illegal write to PC" #define asm_err_branch_pc "a branch by writing to PC is not supported" #define asm_err_fn_id "function identifier expected" #define asm_err_fn_notfound "function %s undefined" #define asm_err_thumb_highreg "illegal access to high register R%d" #endif /* ndef NLS - syserrs are not tags */ %S /* System failure messages - error text not preserved */ #define syserr_interwork "Cannot compile this code with interworking, recompile without interworking" #define syserr_commondef "commondef %ld" #define syserr_obj_checksym "obj_checksym($r)" #define syserr_obj_codereloc "obj_coderelocation %.8lx" #define syserr_obj_gendata "obj_gendata(%ld)" #define syserr_obj_datalen "obj_data len=%ld" #define syserr_obj_data1 "obj_data %ldEL%ld'%s'" #define syserr_find_extsym "find_extsym" #define syserr_duff_lab "asm_trailer(duff lab)" #define syserr_asm_trailer "asm_trailer(%ld)" #define syserr_asm_data "asm_data len=%ld" #define syserr_asm_trailer1 "asm_trailer(%ldF%ld)" #define syserr_asm_hdata "asm_hdata len=%ld" #define syserr_module_reloc "Unsupported Arthur module relocation mode %d" #define syserr_outinstr "outinstr(%lx)" #define syserr_datasymb "Unable to find another data symbol at %ld" #define syserr_shifts "Register & constant shift together" #define syserr_remove_noop "remove_noops(MOVR r,r) failed" #define syserr_silly_shift "Silly shift value %ld" #define syserr_inline1 "armgen(J_INLINE1)" #define syserr_jop_mode "Illegal JOP mode(%lx,%lx)" #define syserr_gen_freg "freg %ld" #define syserr_remove_fp_noop "remove_noops(MOVD/FR r,r) failed" #define syserr_fp_const "%lx not an immediate fp constant" #define syserr_show_inst_dir "show_inst_dir(%#lX)" #define syserr_local_base "local_base %lx" #define syserr_local_addr "local_address %lx" #define syserr_bad_regpair "bad register pair" /* #define syserr_neg_addr "negative local address %ld/%lx for $b" */ #define syserr_local_addr1 "local_addr" #define syserr_debug_addr "debugger local_fpaddr confused" #define syserr_displacement "displacement out of range %ld" #define syserr_unknown_label "unknown label reference type %.8lx" #define syserr_enter "emit(J_ENTER %ld)" #define syserr_gen_eval "gen_eval %ld" #define syserr_pendingstack_overflow "pending stack overflow" #define syserr_setsp_confused "SETSP confused %ld!=%ld %ld" #define syserr_callingstandard "Callingstandard %c" #define syserr_peep_bad_field "bad peephole op field" #define syserr_peep_cant_swap "peephole: can't swap" #define syserr_peep_bad_optype "bad peephole op type" #define syserr_bad_maxinst "peephole MAXINST inconsistent with peephole definitions" #define syserr_bad_useconstraint "bad peephole use constraint" #ifndef TARGET_HAS_AOUT #define syserr_debugger_line "debugger #line confused" #define syserr_addcodep "dbg_addcodep(twice)" #define syserr_filetooffset "dbg_filetooffset(%s)" #define syserr_dbg_bitfield "dbg_typerep(BITFIELD)" #define syserr_dbg_typerep "dbg_typerep(%p,0x%lx)" #define syserr_dbg_proc "dbg_proc" #define syserr_dbg_proc1 "dbg_proc confused" #define syserr_dbg_table "debugger table confusion(local variable $r %lx %lx)" #define syserr_dbg_scope "dbg_scope" #define syserr_dbg_write "dbg_write(%lx)" #define syserr_dbg_struct "dbg_STRUCT confused" #define syserr_dbg_fileinfobase "dbg_fileinfobase %ld != %ld" #define syserr_dbgloc "dbgloc %ld != %ld" #endif #define syserr_leaf_fn "Leaf function %s too big" #define syserr_stm_freeregs "STM free register conflict (regmask %d, free regs %d)" /* end of arm/mcerrs.h */
stardot/ncc
cppfe/xvargen.c
/* * xvargen.c: static initialised variable extensions for C++ compiler * Copyright (C) Codemist Ltd, 1992 * Copyright (C) Advanced RISC Machines Ltd., 1992, 1994 * SPDX-Licence-Identifier: Apache-2.0 * All rights reserved. */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include "globals.h" #include "vargen.h" #include "lex.h" /* for curlex */ #include "syn.h" #include "sem.h" #include "simplify.h" #include "bind.h" #include "builtin.h" #include "aetree.h" #include "codebuf.h" #ifndef NON_CODEMIST_MIDDLE_END #include "regalloc.h" /* to handle global register variables */ #endif #include "mcdep.h" /* for dbg_xxx */ #include "store.h" #include "aeops.h" #include "util.h" /* for padsize */ #include "xrefs.h" #include "inline.h" #include "errors.h" #define _VARGEN_H static void dynamic_init(Expr *e, bool full); static void vg_note_topdtor(Binder *b, bool toplevel); static Expr *vg_get_dyninit(bool toplevel); static Expr *vg_currentdecl_inits; #ifndef NO_DUMP_STATE static void Vargen_cpp_LoadState(FILE *f); static void Vargen_cpp_DumpState(FILE *f); #endif #include "vargen.c" #include <string.h> static CmdList **dyninitq; static CmdList *dyninitp; static CmdList *dtorlist; static Symstr *filectorname, *filedtorname; static int32 vg_dyn_count; static Expr *forge_initlhs(void) { int32 boff = initboffset; if (target_lsbitfirst) boff = MAXBITSIZE - initbsize - boff; /* It seems a shame we can't invent names instead of dataseg+offset. */ #if 0 #ifdef CONST_DATA_IN_CODE if (is_constdata()) { /* The following line will one day be a syserr, but is currently no */ /* more harmless than recovering from "static int c = 1; c = 2; */ /* @@@ However, it does mean that the constdatasegment detection code */ /* is wrong for, e.g., static const int a = f(); */ cc_rerr(vargen_rerr_compiler_confused); return mk_exprbdot(s_dot, inittype, (Expr *)constdatasegment, constdata.size, initbsize, boff); } else #endif #endif return (cur_initlhs == 0) ? mk_exprbdot(s_dot, inittype, (Expr *)datasegment, /*/* should really be struct, but int OK. */ data_size(), initbsize, boff) : mk_exprbdot(s_dot, inittype, (Expr *)cur_initlhs, initwoffset, initbsize, boff); /* AM has changed this code to the more obvious code (for reasons */ /* see comment containing 'x.a = x.b = nn' in sem.c). However, */ /* the absence of globalize_expr(s_let) is a pain! */ /* However, we need this to be there (or perhaps use global store for */ /* all allocations during static initialisers) for things like */ /* int *f(); static int a = (*f())++; */ } /* For local statics (see [ES, p92]) we map static T x = e; to */ /* static T x; static int f; if (!f) (f=1, x=e, atexit(x.dtor)); */ /* where "x=e" above might well be a call x.ctor(e). */ /* Better: test 'f' from the top-level dtor code. */ /* Strategy: change this code into one which accumulates these */ /* "dynamic inits to statics" separately from those to auto vars. */ /* At the end of a declaration (sequence), if at top-level add to */ /* dyninitp/q (after globalising), if local guard with if-firsttime. */ /* The initialisations are probably best stored in a field like */ /* declinit_(), but note that */ /* void f(int x) { auto a[100] = { 1,x,2,3,... }; ... } */ /* is a little ambiguous (i.e. does 'x' get stored FIRST/EACH call?) */ /* and therefore may need two fields. */ static void dynamic_init(Expr *e, bool full) { if (!full) e = mkbinary(s_init, forge_initlhs(), e); vg_currentdecl_inits = vg_currentdecl_inits ? mkbinary(s_comma, vg_currentdecl_inits, e) : e; } static void vg_note_topctor(Expr *e) { if (e) e = optimise0(e); if (e) { CmdList *cmds; Cmd *p = (Cmd *) GlobAlloc(SU_Other, (int32)offsetof(Cmd,cmd2)); p->fileline = init_fl; /* @@@ beware dataflow */ h0_(p) = s_semicolon; cmd1e_(p) = globalize_expr(e); cmds = (CmdList *)global_cons2(SU_Other, NULL, p); *dyninitq = cmds; dyninitq = &cdr_(cmds); } } static Expr *vg_get_dyninit(bool toplevel) { Expr *e = vg_currentdecl_inits; vg_currentdecl_inits = 0; if (toplevel) { vg_note_topctor(e); e = 0; } return e; } typedef struct DdtorList { struct DdtorList *ddtorcdr; Symstr *fnname; Cmd *fnbody; } DdtorList; static DdtorList *ddtorlist; static int32 ddtor_size; int32 ddtor_vecsize(void) { return ddtor_size * sizeof_ptr; } static void vg_note_topdtor(Binder *b, bool toplevel) { Cmd *p; Expr *e; e = mkdtor_v((Expr *)b); if (e) e = optimise0(e); if (e == 0) return; p = (Cmd *) GlobAlloc(SU_Other, (int32)offsetof(Cmd,cmd2)); p->fileline = init_fl; /* @@@ beware dataflow */ h0_(p) = s_semicolon; if (toplevel) { cmd1e_(p) = globalize_expr(e); dtorlist = (CmdList *)global_cons2(SU_Other, dtorlist, p); /* save dtors in reverse order of ctors. */ } else { /*cc_rerr(vargen_rerr_local_static_with_dtor, b);*/ DeclRhsList *d; Binder *fn, *gen; TypeExpr* t = princtype(bindtype_(b)); t = globalize_typeexpr(ptrtotype_(t)); d = mkDeclRhsList(gensymval(YES), t, bitofstg_(s_static)); gen = instate_declaration(d, TOPLEVEL); bindaddr_(gen) = get_datadesc_size(); (void)obj_symref(bindsym_(gen),get_datadesc_xrarea()+xr_defloc, get_datadesc_size()); gendcI(sizeof_ptr, TARGET_NULL_BITPATTERN); binduses_(gen) |= u_referenced; e = mkdtor_v(mkunary(s_content, (Expr *)gen)); e = optimise0(e); cmd1e_(p) = globalize_expr(e); d = mkDeclRhsList(gensymval(YES), te_fntype(te_void, 0, 0, 0, 0, 0), bitofstg_(s_static) | b_fnconst | b_undef); fn = instate_declaration(d, TOPLEVEL); ddtor_size++; ddtorlist = (DdtorList *)global_list3(SU_Other, ddtorlist, bindsym_(fn), p); dynamic_init(mkfnap(cppsim.xpush_ddtor, mkExprList1(mkunary(s_addrof, (Expr *)fn))), 1); dynamic_init(mkbinary(s_init, (Expr *)gen, mkunary(s_addrof, (Expr *)b)), 1); } } static TopDecl *vg_mk_initfn(Symstr *fn, bool ext, Cmd *c) { TypeExprFnAux s; DeclRhsList *d = mkDeclRhsList( /* declname = */ currentfunction.symstr = fn, /* decltype = */ mkTypeExprfn(t_fnap, te_void, 0, 0, packTypeExprFnAux(s, 0,0,0,0,0)), /* declstg = */ ext ? bitofstg_(s_extern) | b_fnconst | b_memfns : bitofstg_(s_static) | b_fnconst | b_memfns); Binder *b = instate_declaration(d , TOPLEVEL); binduses_(b) |= u_referenced; bindstg_(b) |= b_generated; /* compiler generated fn */ if (usrdbg(DBG_PROC+DBG_VAR)) { #if 0 c->fileline.p = dbg_notefileline(c->fileline); #endif #ifndef NEW_DBG_PROC_INTERFACE dbg_proc(bindsym_(b), bindtype_(b), (bindstg_(b) & bitofstg_(s_extern)) != 0, c->fileline); #else dbg_proc(b, bindparent_(b), (bindstg_(b) & bitofstg_(s_extern)) != 0, c->fileline); #endif } return mkTopDeclFnDef(s_fndef, b, 0, c, 0); } typedef struct VtabList { struct VtabList *vtcdr; TagBinder *vtclass; int32 vtsize; Symstr *vtname; } VtabList; static VtabList *vtablist; void vg_note_vtable(TagBinder *cl, int32 sz, Symstr *name) { /* assert: cl is not local store (local classes can't have vfns?). */ /* name is the top-level name for the vtable (get from cl later?). */ VtabList *p; if (debugging(DEBUG_BIND)) cc_msg("Need $r [%ld] for $c\n", name, (long)sz, cl); for (p = vtablist; p != NULL; p = p->vtcdr) if (cl == p->vtclass) { if (!(sz == p->vtsize && name == p->vtname)) syserr("vg_note_vtab $c", cl); return; } vtablist = (VtabList *)global_list4(SU_Other, vtablist, cl, sz, name); } typedef struct WrapperList { struct WrapperList *wcdr; Binder *wrapper, *fnbind; } WrapperList; static WrapperList *wrapperlist; static TopDecl *vg_generate_wrapper_def(Binder *wrapper, Binder *fnbind) { TypeExpr *fntype = bindtype_(wrapper); FormTypeList *ft; SynBindList *argbinders = 0; Binder *temp = 0, *thisb = 0; ExprList *l = 0; Cmd *p; Expr *e; for (ft = typefnargs_(fntype); ft != NULL; ft = ft->ftcdr) { TypeExpr *t = princtype(ft->fttype); Expr *ee; Symstr *sv = ft->ftname; sv = sym_insert_id(symname_((sv) ? sv : gensymval(NO))); if (temp != 0) temp = bindcdr_(temp) = mk_binder(sv, bitofstg_(s_auto), ft->fttype); else thisb = temp = mk_binder(sv, bitofstg_(s_auto), ft->fttype); ee = (Expr *)temp; if (h0_(t) == t_ref) ee = mk_expr1(s_content, typearg_(t), ee); if (ft != typefnargs_(fntype)) l = mkExprList(l, ee); binduses_(temp) |= u_referenced; argbinders = mkSynBindList(argbinders, temp); } p = (Cmd *) GlobAlloc(SU_Other, (int32)offsetof(Cmd, cmd2)); p->fileline = init_fl; /* @@@ beware dataflow */ e = optimise0(mkfnap(mkfieldselector(s_arrow, (Expr *)thisb, (ClassMember *)fnbind), dreverse(l))); if (!isvoidtype(typearg_(fntype))) { h0_(p) = s_return; e = optimise0(mk_expr1(s_return, typearg_(fntype), e)); } else h0_(p) = s_semicolon; cmd1e_(p) = e; return mkTopDeclFnDef(s_fndef, wrapper, (SynBindList *)dreverse((List *)argbinders), mk_cmd_block(curlex.fl, 0, mkCmdList(0, p)), 0); } static void vg_note_wrapper(Binder *wrapper, Binder *fnbind) { wrapperlist = (WrapperList *)global_list3(SU_Other, wrapperlist, wrapper, fnbind); } Binder *generate_wrapper(Binder *a) { TypeExpr *fntype = bindtype_(realbinder_(a)); DeclRhsList *d; Binder *fn; FormTypeList *ft, *ftp = 0, *ftq = 0; for (ft = typefnargs_(fntype); ft != NULL; ft = ft->ftcdr) { FormTypeList *f = (FormTypeList *) BindAlloc(sizeof(FormTypeList)); TypeExpr *t = princtype(ft->fttype); f->ftcdr = NULL; if (isclasstype_(t)) f->fttype = mk_typeexpr1(t_ref, t, 0); else f->fttype = ft->fttype; f->ftdefault = ft->ftdefault; if (ftp == NULL) { ftp = (ftq = f); f->ftname = sym_insert_id("__pseudo_this"); } else { ftq = (ftq->ftcdr = f); f->ftname = ft->ftname; } } fntype = g_mkTypeExprfn(t_fnap, typearg_(fntype), 0, ftp, &typefnaux_(fntype)); d = mkDeclRhsList(sym_insert_id(symname_(gensymval(YES))), fntype, bitofstg_(s_static)|b_fnconst); fn = instate_declaration(d, TOPLEVEL); binduses_(fn) |= u_referenced; bindstg_(fn) |= b_generated; /* compiler generated function */ vg_note_wrapper(fn, a); return fn; } static Cmd *vg_vtabcmd(TagBinder *cl, int32 sz) { VfnList *x = vfn_list(cl); #if 0 curlex.fl.p = dbg_notefileline(curlex.fl); #endif x = (VfnList *)dreverse((List *)x); return mk_cmd_e(s_thunkentry, curlex.fl, (Expr *)x); if (debugging(DEBUG_DATA)) { for (; x; x = x->vfcdr) cc_msg("$b ", x->vfmem); cc_msg("\n"); } /* NOTREACHED */ return NULL; } static bool hackrefdataseg; #ifdef TARGET_HAS_DEBUGGER static int saved_usrdbgmask; #endif static int need_finalise; TopDecl *vg_dynamic_init(void) { TopDecl *d; if (!hackrefdataseg && (dyninitp != NULL || dtorlist != NULL)) { /* reference the datasegment from the codesegment to ensure */ /* that C$$ctorvec is loaded if any routine is referenced as */ /* well as if any static datum is externally referenced. */ codebuf_reinit1(0); codebuf_reinit2(); lit_findword(0, LIT_ADCON, bindsym_(datasegment), LITF_INCODE|LITF_FIRST|LITF_LAST); codeseg_flush(NULL); hackrefdataseg = YES; } #if 0 curlex.fl.p = dbg_notefileline(curlex.fl); #endif obj_clearcommoncode(); obj_clearvtable(); #ifdef TARGET_HAS_DEBUGGER if (saved_usrdbgmask == -1) { saved_usrdbgmask = (usrdbgmask & DBG_ANY); usrdbgmask &= ~DBG_ANY; } #endif if (vtablist != NULL) { char v[128+3]; strcpy(v, "x$"); strcpy(v+2, symname_(vtablist->vtname)); obj_setcommoncode(); obj_setvtable(); codebuf_reinit1(v); d = vg_mk_initfn(vtablist->vtname, 1, vg_vtabcmd(vtablist->vtclass, vtablist->vtsize)); vtablist = vtablist->vtcdr; return d; } if (dyninitp != NULL) { codebuf_reinit1("x$ctor"); d = vg_mk_initfn(sym_insert_id("__C"), 0, mk_cmd_block(curlex.fl, 0, dyninitp)); filectorname = bindsym_(d->v_f.fn.name); dyninitp = NULL; dyninitq = &dyninitp; obj_symref(sym_insert_id("__cpp_initialise"), xr_code, 0); return d; } if (dtorlist != NULL) { codebuf_reinit1("x$dtor"); d = vg_mk_initfn(sym_insert_id("__D"), 0, mk_cmd_block(curlex.fl, 0, dtorlist)); filedtorname = bindsym_(d->v_f.fn.name); dtorlist = NULL; if (need_finalise == 0) { need_finalise = 1; obj_symref(sym_insert_id("__cpp_finalise"), xr_code, 0); } return d; } if (ddtorlist != NULL) { char v[128+3]; strcpy(v, "x$"); strcpy(v+2, symname_(ddtorlist->fnname)); obj_setcommoncode(); codebuf_reinit1(v); d = vg_mk_initfn(ddtorlist->fnname, 0, mk_cmd_block(curlex.fl, 0, mkCmdList(0, ddtorlist->fnbody))); ddtorlist = ddtorlist->ddtorcdr; if (need_finalise == 0) obj_symref(sym_insert_id("__cpp_finalise"), xr_code, 0); need_finalise |= 4; return d; } if (wrapperlist != NULL) { char v[128+3]; strcpy(v, "x$"); strcpy(v+2, symname_(bindsym_(wrapperlist->wrapper))); obj_setcommoncode(); codebuf_reinit1(v); d = vg_generate_wrapper_def(wrapperlist->wrapper, wrapperlist->fnbind); wrapperlist = wrapperlist->wcdr; return d; } #ifdef TARGET_HAS_DEBUGGER usrdbgmask = saved_usrdbgmask; /* to ensure dbg_writedebug works */ saved_usrdbgmask = -1; #endif return NULL; } static void vg_ctordtor_table(Symstr *fnname, char *segname) { /* Beware this routine which uses a routine intended for a named */ /* code segment to generate data... */ /* -- maybe add a new 'LIT_SETSEG' opcode (codebuf/adddata). */ /* -- maybe unify code and data generation. */ /* @@@ make this take no data space */ if (fnname != NULL) { codebuf_reinit1(segname); codebuf_reinit2(); lit_findword(0, LIT_ADCON, fnname, LITF_INCODE|LITF_FIRST|LITF_LAST); codeseg_flush(NULL); gendcAX(bindsym_(codesegment), 0, xr_data); } } void vg_ref_dynamic_init(void) { vg_ctordtor_table(filectorname, "x$ctorvec"); vg_ctordtor_table(filedtorname, "x$dtorvec"); if (need_finalise & 4) { Symstr *sv = bindsym_(ddtorsegment); obj_symref(sv, xr_data, 0); /* @@@ make this take no data space */ gendcAX(sv, 0, xr_data); } } #ifndef NO_DUMP_STATE #include "dump.h" static Cmd *LoadCmd(FILE *f) { Cmd *c = (Cmd *)GlobAlloc(SU_Other, (int32)offsetof(Cmd,cmd2)); h0_(c) = s_semicolon; cmd1e_(c) = Dump_LoadExpr(f); return c; } static void Vargen_cpp_LoadState(FILE *f) { int32 w[3]; int32 n; fread(&n, 1, sizeof(int32), f); if (n != 0) { VtabList *p, **q = &vtablist; for (; --n >= 0; q = &p->vtcdr) { fread(w, 3, sizeof(int32), f); p = (VtabList *)GlobAlloc(SU_Other, sizeof(VtabList)); p->vtcdr = NULL; p->vtclass = Dump_LoadedTag(w[0]); p->vtsize = w[1]; p->vtname = Dump_LoadedSym(w[2]); *q = p; } } fread(&n, 1, sizeof(int32), f); if (n != 0) { WrapperList *p, **q = &wrapperlist; for (; --n >= 0; q = &p->wcdr) { fread(w, 2, sizeof(int32), f); p = (WrapperList *)GlobAlloc(SU_Other, sizeof(WrapperList)); p->wcdr = NULL; p->wrapper = Dump_LoadedBinder(w[0]); p->fnbind = Dump_LoadedBinder(w[1]); *q = p; } } fread(&n, 1, sizeof(int32), f); if (n != 0) { CmdList *p, **q = &dtorlist; for (; --n >= 0; q = &cdr_(p)) { p = (CmdList *)GlobAlloc(SU_Other, sizeof(CmdList)); cdr_(p) = NULL; cmdcar_(p) = LoadCmd(f); *q = p; } } fread(&n, 1, sizeof(int32), f); if (n != 0) { DdtorList *p, **q = &ddtorlist; for (; --n >= 0; q = &p->ddtorcdr) { p = (DdtorList *)GlobAlloc(SU_Other, sizeof(DdtorList)); p->ddtorcdr = NULL; fread(w, 1, sizeof(int32), f); p->fnname = Dump_LoadedSym(w[0]); p->fnbody = LoadCmd(f); *q = p; } } fread(&n, 1, sizeof(int32), f); if (n != 0) { CmdList *p; for (; --n >= 0; dyninitq = &cdr_(p)) { p = (CmdList *)GlobAlloc(SU_Other, sizeof(CmdList)); cdr_(p) = NULL; cmdcar_(p) = LoadCmd(f); *dyninitq = p; } } } static void DumpCmd(Cmd *c, FILE *f) { if (h0_(c) != s_semicolon) syserr("Vargen_cpp_DumpState %ld", (long)h0_(c)); Dump_Expr(cmd1e_(c), f); } static void Vargen_cpp_DumpState(FILE *f) { int32 w[3]; int32 n = length((List *)vtablist); fwrite(&n, 1, sizeof(int32), f); if (vtablist != NULL) { VtabList *p = vtablist; for (; p != NULL; p = p->vtcdr) { w[0] = Dump_TagRef(p->vtclass); w[1] = p->vtsize; w[2] = Dump_SymRef(p->vtname); fwrite(w, 3, sizeof(int32), f); } } n = length((List *)wrapperlist); fwrite(&n, 1, sizeof(int32), f); if (wrapperlist != NULL) { WrapperList *p = wrapperlist; for (; p != NULL; p = p->wcdr) { w[0] = Dump_BinderRef(p->wrapper); w[1] = Dump_BinderRef(p->fnbind); fwrite(w, 2, sizeof(int32), f); } } n = length((List *)dtorlist); fwrite(&n, 1, sizeof(int32), f); if (dtorlist != NULL) { CmdList *p = dtorlist; for (; p != NULL; p = cdr_(p)) DumpCmd(cmdcar_(p), f); } n = length((List *)ddtorlist); fwrite(&n, 1, sizeof(int32), f); if (ddtorlist != NULL) { DdtorList *p = ddtorlist; for (; p != NULL; p = p->ddtorcdr) { w[0] = Dump_SymRef(p->fnname); fwrite(w, 1, sizeof(int32), f); DumpCmd(p->fnbody, f); } } n = length((List *)dyninitp); fwrite(&n, 1, sizeof(int32), f); if (dyninitp != NULL) { CmdList *p = dyninitp; for (; p != NULL; p = cdr_(p)) DumpCmd(cmdcar_(p), f); } } #endif void vargen_init(void) { hackrefdataseg = NO; #ifdef TARGET_HAS_DEBUGGER saved_usrdbgmask = -1; #endif need_finalise = 0; dyninitp = NULL; dyninitq = &dyninitp; dtorlist = NULL; vtablist = NULL; filectorname = NULL; filedtorname = NULL; vg_dyn_count = 0; vg_currentdecl_inits = NULL; ddtorlist = NULL; ddtor_size = 0; wrapperlist = NULL; } /* end of cppfe/vargen.c */
stardot/ncc
thumb/ops.h
<reponame>stardot/ncc /* * C compiler file thumb/ops.h, version 1 * Copyright (C) Codemist Ltd., 1994 * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _thumbops_LOADED #define _thumbops_LOADED 1 /* ARM opcodes used by Thumb */ #define ARM_AL 0xe0000000L #define ARM_B 0x0a000000L #define ARM_BX 0x012fff10L #define ARM_LDR_IP_PC_0 0x059fc000L #define ARM_ADDI3 0x02800000L #define ARM_SUBI3 0x02400000L /* Thumb opcodes... */ /* Condition fields are defined relative to the default C_ALWAYS value */ #define C_CC 0x300L #define C_LO 0x300L #define C_CS 0x200L #define C_HS 0x200L #define C_EQ 0x000L #define C_GE 0xa00L #define C_GT 0xc00L #define C_HI 0x800L #define C_LE 0xd00L #define C_LS 0x900L #define C_LT 0xb00L #define C_MI 0x400L #define C_NE 0x100L #define C_PL 0x500L #define C_VC 0x700L #define C_VS 0x600L #define C_AL 0xe00L #define C_of_Q(a) c_of_q(a) /* F1, F2 and F3 opcodes */ #define F_ADDI3 0x1c00L #define F_SUBI3 0x1e00L #define F_ADD3R 0x1800L #define F_SUB3R 0x1a00L #define F_STRHADDR 0x5200L #define F_LDRHADDR 0x5a00L #define F_LDSBADDR 0x5600L #define F_LDSHADDR 0x5e00L #define F_STRHI5 0x8000L #define F_LDRHI5 0x8800L /* F4 opcodes */ #define F_LSLK 0x0000L #define F_LSRK 0x0800L #define F_ASRK 0x1000L /* F5 opcodes */ #define F_AND 0x4000L #define F_EOR 0x4040L #define F_LSL 0x4080L #define F_LSR 0x40c0L #define F_ASR 0x4100L #define F_ADC 0x4140L #define F_SBC 0x4180L #define F_ROR 0x41c0L #define F_TST 0x4200L #define F_NEG 0x4240L #define F_CMP 0x4280L #define F_CMN 0x42c0L #define F_OR 0x4300L #define F_MUL 0x4340L #define F_BIC 0x4380L #define F_MVN 0x43c0L #define IS_DATAPROC(op) (((op) & 0xfc00) == 0x4000) #define F_ADDHL 0x4440L #define F_ADDLH 0x4480L #define F_ADDHH 0x44c0L #define F_CMPHL 0x4540L #define F_CMPLH 0x4580L #define F_CMPHH 0x45c0L #define F_MOVHL 0x4640L #define F_MOVLH 0x4680L #define F_MOVHH 0x46c0L #define F_BX_L 0x4700L #define F_BX_H 0x4740L /* F6 opcodes */ #define F_MOV8 0x2000L #define F_CMP8 0x2800L #define F_ADDI8 0x3000L #define F_SUBI8 0x3800L /* F12 opcodes */ #define F_LDRLIT 0x4800L /* address is PC relative */ /* F8 opcodes */ #define F_STRSP 0x9000L #define F_LDRSP 0x9800L /* F9 opcodes */ #define F_B 0xe000L /* F10 opcodes */ #define F_PUSH 0xb400L /* LR is 0x100 bit */ #define F_POP 0xbc00L /* PC is 0x100 bit */ /* F13 opcodes (pre-index with register offset) */ #define F_STRADDR 0x5000L #define F_STRBADDR 0x5400L #define F_LDRADDR 0x5800L #define F_LDRBADDR 0x5c00L /* F14 opcodes */ #define F_STRI5 0x6000L #define F_LDRI5 0x6800L #define F_STRBI5 0x7000L #define F_LDRBI5 0x7800L /* F15 opcodes */ #define F_STM 0xc000L #define F_LDM 0xc800L /* F16 opcodes */ #define F_ADDRPC 0xa000L #define F_ADDRSP 0xa800L /* F17 opcodes */ #define F_BC 0xd000L /* must have branch condition included */ /* F18 opcodes */ #define F_ADDSP 0xb000L /* Note ... now sign & magnitude */ #define F_SUBSP 0xb080L /* F19 opcodes */ #define F_SWI 0xdf00L /* F20, F21 opcodes */ #define F_CALL1 0xf000L /* prefix for a F_CALL */ #define F_CALL 0xf800L /* * Register names - some defined in target.h. */ /* #define R_A1 0x0L * arg 1 & main result register */ #define R_A2 0x1L /* arg 2 */ #define R_A3 0x2L /* arg 3 */ #define R_A4 0x3L /* arg 4 */ /* #define R_V1 0x4L * register variable 1 */ #define R_V2 0x5L /* register variable 2 */ #define R_V3 0x6L /* register variable 3 */ #define R_V4 0x7L /* register variable 4 */ #define R_V5 0x8L /* register variable 5 (not allocated) */ #define R_V6 0x9L /* register variable 6 (not allocated) */ /* define R_IP 0x7L */ # define R_SB 0x9L # define R_FP 0xbL /* Frame pointer */ /* # define R_SP 0xdL main stack pointer */ # define R_SL 0xaL /* stack limit (usually not checked) */ /* # define R_LR 0xeL * link address in function calls + workspace */ #define R_PC 0xfL /* program counter */ /* #define R_PSR R_PC program status register (register allocation)*/ /* Calling a function can disturb r_a1 to r_a4, r_ip, r_lk but must */ /* preserve r_v1 to r_v3, r_fp and r_sp. r_sl must always be a valid */ /* stack limit value - it may be changed during a call is a stack */ /* has its size changed. */ /* LDM/STM masks for real registers. */ /* **** $$$$$ BEWARE: on arm these are used in general register fields and to show reg usage in ldm/stm. In thumb, ldm and stm only allow 8 regs + lr or pc. Don't use these in thumb ldm and stm. */ #define M_LR regbit(R_LR) #define M_PC regbit(R_PC) #define M_ARGREGS (regbit(R_A1+NARGREGS)-regbit(R_A1)) #define M_VARREGS (regbit(R_V1+NVARREGS)-regbit(R_V1)) #define M_FARGREGS 0 #define M_FVARREGS 0 #define PC_OFFSET 4 #endif /* end of thumb/ops.h */
stardot/ncc
util/peepgen.c
<reponame>stardot/ncc /* * peepgen.c: Peephole table generator * Copyright (C) Advanced Risc Machines Ltd., 1991 * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <stdlib.h> #include <ctype.h> #include <string.h> #include <stdio.h> #ifdef __STDC__ # include <stdarg.h> #else # include <varargs.h> #endif #include "host.h" #include "globals.h" static int peephole_index; #define deadbit(f) (1<<(f)) typedef enum P_OpType { pot_none, pot_and, pot_or, pot_andnot, pot_prop, pot_peep, pot_peep_m, pot_op, pot_op_m, pot_opinset, pot_opinset_m } P_OpType; static char const * const pot_name[] = { "pot_none", "pot_and", "pot_or", "pot_andnot", "pot_prop", "pot_peep", "pot_peep_m", "pot_op", "pot_op_m", "pot_opinset", "pot_opinset_m" }; typedef enum { p_loads_r1, p_uses_r1, p_uses_r2, p_uses_r3, p_uses_r4, p_loads_r2 } P_OpPred; static char const * const opr_name[] = { "p_loads_r1", "p_uses_r1", "p_uses_r2", "p_uses_r3", "p_uses_r4", "p_loads_r2" }; typedef enum { pf_none, pf_op, pf_peep, pf_r1, pf_r2, pf_r3, pf_r4, pf_dataflow, pf_cond, pf_dead_r1, pf_dead_r2, pf_dead_r3, pf_dead_r4 } P_Field; static char const * const field_name[] = { "pf_none", "pf_op", "pf_peep", "pf_r1", "pf_r2", "pf_r3", "pf_r4", "pf_dataflow", "pf_cond", "pf_dead_r1", "pf_dead_r2", "pf_dead_r3", "pf_dead_r4" }; static char const * const dead_name[] = { /* nb: indexed by P_Field (thus the null entries) */ 0, 0, 0, "p_dead_r1", "p_dead_r2", "p_dead_r3", "p_dead_r4" }; typedef enum { pu_r1, pu_r2, pu_r3, pu_r4, pu_r3mask } P_Use; static char const * const use_name[] = { "pu_r1", "pu_r2", "pu_r3", "pu_r4", "pu_r3mask" }; typedef enum { prt_none, prt_kill, prt_swapr2r3, prt_set, prt_asr, prt_reverse_fn, prt_proc } P_ReplaceType; static char const * const rt_name[] = { "prt_none", "prt_kill", "prt_swapr2r3", "prt_set", "prt_asr", "prt_reverse_fn", "prt_proc" }; typedef enum { pft_none, pft_int, pft_exprn, pft_field, pft_inst, pft_constraint /* last, with no name */ } P_FieldType; static char const * const ft_name[] = { "pft_none", "pft_val", "pft_exprn", "pft_field", "pft_inst", "pft_val" }; typedef enum { peo_proc1, peo_proc2, peo_add, peo_sub, peo_or, peo_and, peo_eor, peo_shl, peo_shr, peo_div, peo_mul } P_ExprnOp; static char const * const peo_name[] = { "peo_proc1", "peo_proc2", "peo_add", "peo_sub", "peo_or", "peo_and", "peo_eor", "peo_shl", "peo_shr", "peo_div", "peo_mul" }; typedef enum { pct_proc0, pct_proc1, pct_proc2, pct_ne, pct_eq, pct_lt, pct_le, pct_gt, pct_ge, pct_ltu, pct_leu, pct_gtu, pct_geu, pct_neg, pct_or } P_ConstraintOp; static char const * const ct_name[] = { "pct_proc0", "pct_proc1", "pct_proc2", "pct_ne", "pct_eq", "pct_lt", "pct_le", "pct_gt", "pct_ge", "pct_ltu", "pct_leu", "pct_gtu", "pct_geu", "pct_negate", "pct_or" }; #define MaxOps 10 #define MaxConstraints 32 #define MaxReplace 32 typedef struct ProcDef { struct ProcDef *next; int n; char *arg; char *line[1]; } ProcDef; typedef struct PeepExprn PeepExprn; typedef struct { int inst; P_Field field; } P_InstField; typedef struct PeepConstraint PeepConstraint; typedef struct PeepField { P_FieldType type; union { union { PeepConstraint *c; int i; } c; char *val; P_InstField f; union { PeepExprn *ex; int i; } ex; } f; } PeepField; struct PeepExprn { PeepExprn *next; P_ExprnOp op; char *fn; PeepField f1, f2; }; typedef struct PeepReplace { P_ReplaceType type; int procno; PeepField f1, f2; } PeepReplace; typedef struct PeepOpDef { P_OpType type; int setcount; union { struct { union { struct PeepOpDef *p; int i; } op1; union { struct PeepOpDef *p; int i; } op2; } sub; struct { union { char *c; int i; } val; union { char *c; int i; } mask; } op; struct { unsigned val; union { char *c; int i; } mask; } prop; struct { union { char **cp; int i; } ops; union { char *c; int i; } mask; } set; } p; } PeepOpDef; typedef struct PeepReplaceDef PeepReplaceDef; typedef struct { int use; int kill; } RegisterUsage; typedef struct PeepOp { char *label; int index; PeepOpDef op; int debugix; int replacecount; union { PeepReplaceDef *r; int i; } replace; int dead; RegisterUsage maynot; } PeepOp; struct PeepReplaceDef { PeepReplaceDef *next; PeepOp *op; PeepReplace *replace[1]; }; struct PeepConstraint { P_ConstraintOp ctype; char *proc; PeepField f1, f2; }; typedef struct PeepHole { struct PeepHole *next; int trace; int index; int opcount; int constraintcount; PeepOp **ops; PeepConstraint **constraints; char *gapconstraint; } PeepHole; typedef struct { const char *name; int val; } KeyTable; typedef struct { const char *name; int val; int args; } KeyFnTable; static KeyTable const op_predicates[] = { {"loads_r1", p_loads_r1}, {"uses_r1", p_uses_r1}, {"uses_r2", p_uses_r2}, {"uses_r3", p_uses_r3}, {"uses_r4", p_uses_r4}, {"loads_r2", p_loads_r2}, {"sets_r1", p_loads_r1}, {0,0} }; static KeyTable const op_dead[] = { {"dead_r1", deadbit(pf_r1)}, {"dead_r2", deadbit(pf_r2)}, {"dead_r3", deadbit(pf_r3)}, {"dead_r4", deadbit(pf_r4)}, {0,0} }; static KeyTable const eop_table[] = { {"+", peo_add}, {"-", peo_sub}, {"|", peo_or}, {"&", peo_and}, {"^", peo_eor}, {">>", peo_shr}, {"<<", peo_shl}, {"/", peo_div}, {"*", peo_mul}, {0,0} }; static KeyTable const constraint_ops[] = { {"!=", pct_ne}, {"==", pct_eq}, {"<", pct_lt}, {"<=", pct_le}, {">", pct_gt}, {">=", pct_ge}, {"<u", pct_ltu}, {"<=u",pct_leu}, {">u", pct_gtu}, {">=u",pct_geu}, {"!", pct_neg}, {"||", pct_or}, {0,0} }; static KeyTable const replace_ops[] = { {"=", prt_set}, {0,0} }; static KeyFnTable const replace_keys[] = { {"kill", prt_kill, 1}, {"swapr2r3", prt_swapr2r3, 1}, {"adjuststackrefs", prt_asr, 2}, {"reverse_fn", prt_reverse_fn, 1}, {0,0} }; static KeyTable const field_table[] = { {"op", pf_op}, {"r1", pf_r1}, {"r2", pf_r2}, {"r3", pf_r3}, {"r4", pf_r4}, {"peep", pf_peep}, {"dataflow", pf_dataflow}, {"cond", pf_cond}, {"dead_r1", pf_dead_r1}, {"dead_r2", pf_dead_r2}, {"dead_r3", pf_dead_r3}, {"dead_r4", pf_dead_r4}, {0,0} }; #define Id_MaxLen 255 typedef struct { int len; char b[Id_MaxLen+1]; } Id; typedef struct ProcDefList { ProcDef *list; ProcDef **end; int count; } ProcDefList; typedef struct FnArgList { struct FnArgList *next; const char *fn; int args; } FnArgList; static ProcDefList rproc; static FnArgList *constraintfns, *exprnfns; const char *pcp_regset_unused, *pcp_regset_unkilled, *pcp_nointervening, *pep_bit; static FILE *debug; static char *debugbuf; static int debugix; #define DebugSize 2048 static void InitProcDefList(ProcDefList *p) { p->list = 0; p->end = &p->list; p->count = 0; } static KeyTable const *LookUp(const Id *id, const KeyTable *t) { for (; t->name != 0; t++) if (StrEq(id->b, t->name)) return t; return NULL; } static KeyFnTable const *LookUpFn(const Id *id, const KeyFnTable *t) { for (; t->name != 0; t++) if (StrEq(id->b, t->name)) return t; return 0; } static char *outputfile; static FILE *input, *output; static int line_number; static int bracket_nesting; static void die(void) { fclose(output); if (outputfile != 0) remove(outputfile); exit(1); } static void Message(const char *format, const char *s1, va_list ap) { fprintf(stderr, "%s at line %d: ", s1, line_number); vfprintf(stderr, format, ap); fprintf(stderr, "\n\n"); } static void FatalError(const char *s, ...) { va_list ap; va_start(ap, s); Message(s, "fatal error", ap); va_end(ap); die(); } static void SyntaxError(const char *s, ...) { va_list ap; va_start(ap, s); Message(s, "syntax error", ap); va_end(ap); die(); } static void Warn(const char *s, ...) { va_list ap; va_start(ap, s); Message(s, "warning", ap); va_end(ap); } static int NextCh(void) { int ch = fgetc(input); if (debug) debugbuf[debugix++] = ch; if (ch == '\n') line_number++; else if (ch == '(') bracket_nesting++; else if (ch == ')') bracket_nesting--; return ch; } static int SigCh(int ch) { for (;;) { while (isspace(ch)) ch = NextCh(); if (ch != ';') return ch; do ch = NextCh(); while (ch != '\n'); } } static int WantCh(char want, int ch, const char *whence) { ch = SigCh(ch); if (ch != want) SyntaxError("%s: need '%c'", whence, want); return SigCh(NextCh()); } typedef struct StringList { struct StringList *next; char string[1]; } StringList; static StringList *syms; static char *NewHeapString(const char *s, int len) { StringList *sym = (StringList *) malloc(sizeof(*sym)+len); if (sym == 0) FatalError("out of store"); memcpy(sym->string, s, len+1); sym->next = syms; syms = sym; return sym->string; } static char *HeapString(const Id *i) { StringList *sym; for (sym = syms; sym != NULL; sym = sym->next) if (StrEq(i->b, sym->string)) return sym->string; return NewHeapString(i->b, i->len); } static void AddFn(FnArgList **pp, const char *fn, int args) { FnArgList *p; for (; (p = *pp) != NULL; pp = &(p->next)) if (StrEq(fn, p->fn)) { if (p->args != args) SyntaxError("Inconsistent argument count for %s", fn); return; } p = (FnArgList *) malloc(sizeof(*p)); p->next = NULL; p->fn = fn; p->args = args; *pp = p; } static void StuffId(Id *id, int ch) { if (id->len >= Id_MaxLen) FatalError("Overlong id %s", id->b); id->b[id->len++] = ch; id->b[id->len] = 0; } static int ReadId(Id *id, int ch) { id->len = 0; while (!isspace(ch) && ch != '.' && ch != '(' && ch != ')') { StuffId(id, ch); ch = NextCh(); } return SigCh(ch); } static int ReadOpSpec(int ch, PeepOpDef *p) { Id id; char *mask = 0; ch = SigCh(ch); if (ch == '&') { id.len = 0; ch = SigCh(NextCh()); while (ch != '=' && ch != '<' && ch != '\n') { if (!isspace(ch)) StuffId(&id, ch); ch = NextCh(); } if (id.len == 0 || ch == '\n') SyntaxError("bad %s mask", p->type == pot_op ? "op" : "peep"); mask = HeapString(&id); } if (ch == '=' && (ch = NextCh()) == '=') { ch = ReadId(&id, SigCh(NextCh())); p->setcount = 0; p->p.op.val.c = HeapString(&id); p->p.op.mask.c = mask; } else if (p->type == pot_op && ch == '<' && (ch = NextCh()) == '-') { int n = 0; typedef struct strlist { struct strlist *next; char *p; } strlist; strlist *strl = 0, **strp = &strl; ch = WantCh('(', NextCh(), "opset"); while (ch != ')') { strlist *s; ch = ReadId(&id, ch); if (id.len == 0) SyntaxError("unexpected %c in op set", ch); n++; s = (strlist *) malloc(sizeof(*s)); *strp = s; strp = &s->next; s->next = 0; s->p = HeapString(&id); if (ch == ',') ch = SigCh(NextCh()); } ch = WantCh(')', ch, "opset"); { char **v = (char **) malloc(n * sizeof(char *)); int i; for (i = 0; i < n; i++, strl = strl->next) v[i] = strl->p; p->type = pot_opinset; p->setcount = n; p->p.set.ops.cp = v; p->p.set.mask.c = mask; } } else SyntaxError("unexpected '%c' in %s specification", ch, p->type == pot_op ? "op" : "peep"); return ch; } static PeepOp *NextOp(int *chp) { Id id; int ch = SigCh(*chp); PeepOp *res; PeepOpDef op; PeepOpDef *opp = &op; KeyTable const *i; P_OpType andor = pot_op; memset(opp, 0, sizeof(*opp)); if (ch == ')') { *chp = ch; return 0; } res = (PeepOp *) malloc(sizeof(*res)); res->replacecount = 0; res->replace.r = NULL; res->dead = 0; res->maynot.use = res->maynot.kill = 0; ch = ReadId(&id, ch); res->label = HeapString(&id); ch = WantCh('(', ch, "NextOp"); for (;;) { ch = SigCh(ch); if (ch == ')') { op.type = pot_none; break; } ch = ReadId(&id, ch); if ((i = LookUp(&id, op_dead)) != 0) { if (andor != pot_op && andor != pot_and) SyntaxError("Bad boolean operator for dead_xx"); res->dead |= i->val; } else { if (andor != pot_op) { PeepOpDef *p1, *p2; p1 = (PeepOpDef *) malloc(sizeof(*p1)); p2 = (PeepOpDef *) calloc(sizeof(*p2), 1); *p1 = *opp; opp->type = andor; opp->setcount = 0; opp->p.sub.op1.p = p1; opp->p.sub.op2.p = p2; opp = p2; } if (StrEq("op", id.b)) { opp->type = pot_op; ch = ReadOpSpec(ch, opp); } else if (StrEq("peep", id.b)) { opp->type = pot_peep; ch = ReadOpSpec(ch, opp); } else if ((i = LookUp(&id, op_predicates)) != 0) { opp->type = pot_prop; opp->setcount = 0; opp->p.prop.val = i->val; opp->p.op.mask.c = 0; } else SyntaxError("Unknown op predicate '%s'", id.b); } if (ch == '&') { if ((ch = NextCh()) == '&') andor = pot_and; else if (ch == '!') andor = pot_andnot; else break; } else if (ch == '|' && (ch = NextCh()) == '|') andor = pot_or; else break; ch = SigCh(NextCh()); } if (debug) { res->debugix = debugix; } *chp = WantCh(')', ch, "NextOp"); res->op = op; return res; } static int opMax; static PeepOp **ReadOps(int *chp, int *np) { int ch = WantCh('(', *chp, "ReadOps"); int count = 0; PeepOp *ops[MaxOps]; PeepOp *op = NextOp(&ch); for (; op != NULL; count++) { if (count >= MaxOps) SyntaxError("Too many ops"); ops[count] = op; op = NextOp(&ch); } if (count < 1) SyntaxError("Too few ops"); if (opMax < count) opMax = count; *chp = WantCh(')', ch, "ReadOps"); { PeepOp **r = (PeepOp **) malloc(count*sizeof(*r)); int i; for (i = 0; i < count; i++) { r[i] = ops[count-i-1]; r[i]->index = i; } *np = count; return r; } } static int FindOp(char *label, PeepOp **p, int n) { for (; --n >= 0; ) if (StrEq(label, p[n]->label)) break; return n; } #define rf_rid 1 #define rf_lab 2 static int ReadField(Id *id, PeepHole const *ph, PeepField *f, int ch, int flags) { int i; if (flags & rf_rid) { ch = SigCh(ch); if (ch == '(') { PeepExprn *pex = (PeepExprn *) malloc(sizeof(*pex)); int operands = 2; char *fn = NULL; KeyTable const *kp; ch = ReadId(id, SigCh(NextCh())); kp = LookUp(id, eop_table); if (kp != NULL) pex->op = (P_ExprnOp)kp->val; else fn = HeapString(id); ch = ReadField(id, ph, &pex->f1, ch, rf_rid); if (fn != 0) { if (ch == ')') operands = 1, pex->op = peo_proc1; else pex->op = peo_proc2; AddFn(&exprnfns, fn, operands); } pex->fn = fn; if (operands == 2) ch = ReadField(id, ph, &pex->f2, ch, rf_rid); else pex->f2.type = pft_none; f->type = pft_exprn; f->f.ex.ex = pex; return WantCh(')', ch, "ReadExp"); } ch = ReadId(id, SigCh(ch)); } if (ch == '.') { KeyTable const *fn; i = FindOp(id->b, ph->ops, ph->opcount); if (i < 0) SyntaxError("Bad op label %s", id->b); ch = ReadId(id, NextCh()); fn = LookUp(id, field_table); if (fn == 0) SyntaxError("Bad field %s", id->b); f->type = pft_field; f->f.f.inst = i; f->f.f.field = (P_Field)fn->val; } else if ((flags & rf_lab) && (i = FindOp(id->b, ph->ops, ph->opcount)) >= 0) { f->type = pft_inst; f->f.f.inst = i; f->f.f.field = pf_none; } else { f->type = pft_int; f->f.val = HeapString(id); } return SigCh(ch); } static PeepConstraint *ReadConstraint(PeepHole const *ph, int *chp) { int ch = WantCh('(', *chp, "ReadConstraint"); Id id; PeepConstraint *res = (PeepConstraint *)malloc(sizeof(*res)); KeyTable const *op; res->f1.type = res->f2.type = pft_none; ch = ReadId(&id, ch); op = LookUp(&id, constraint_ops); if (op == 0) { int args = pct_proc0; res->proc = HeapString(&id); if (ch != ')') { args++; ch = ReadField(&id, ph, &res->f1, ch, rf_rid+rf_lab); } if (ch != ')') { args++; ch = ReadField(&id, ph, &res->f2, ch, rf_rid+rf_lab); } res->ctype = (P_ConstraintOp)args; if (res->proc != pcp_nointervening) AddFn(&constraintfns, res->proc, args); *chp = WantCh(')', ch, "ReadConstraint"); return res; } { if (op->val == pct_neg || op->val == pct_or) { *chp = ch; res->f1.type = pft_constraint; res->f1.f.c.c = ReadConstraint(ph, chp); if (op->val == pct_or) { res->f2.type = pft_constraint; res->f2.f.c.c = ReadConstraint(ph, chp); } ch = *chp; } else { ch = ReadField(&id, ph, &res->f1, ch, rf_rid); ch = ReadField(&id, ph, &res->f2, ch, rf_rid); } res->proc = NULL; res->ctype = (P_ConstraintOp)op->val; } *chp = WantCh(')', ch, "ReadConstraint"); return res; } #define MayNotKill(p, i, f) ((p)->ops[i]->maynot.kill |= (1 << ((f) - pf_r1))) #define MayNotUse(p, i, f) ((p)->ops[i]->maynot.use |= (1 << ((f) - pf_r1))) static PeepConstraint **ReadConstraints(PeepHole *ph, int *chp, int *np) { PeepConstraint *pcs[MaxConstraints]; int i = 0; for (; *chp == '('; ) { PeepConstraint *pc = ReadConstraint(ph, chp); if (pc->ctype == pct_proc1 && pc->proc != 0 && (pc->proc == pcp_regset_unused || pc->proc == pcp_regset_unkilled) && pc->f1.type == pft_exprn && pc->f1.f.ex.ex->op == peo_proc1 && pc->f1.f.ex.ex->fn == pep_bit && pc->f1.f.ex.ex->f1.type == pft_field) { int inst = pc->f1.f.ex.ex->f1.f.f.inst; P_Field f = pc->f1.f.ex.ex->f1.f.f.field; if (pc->proc == pcp_regset_unused) MayNotUse(ph, inst, f); MayNotKill(ph, inst, f); } else if (pc->ctype == pct_proc1 && pc->proc == pcp_nointervening) { if (pc->f1.type != pft_int) SyntaxError("Bad gap constraint"); ph->gapconstraint = pc->f1.f.val; } else { pcs[i++] = pc; } } *chp = WantCh(')', *chp, "ReadConstraints"); { PeepConstraint **res = (PeepConstraint **) malloc(i * sizeof(*res)); memcpy(res, pcs, i * sizeof(res)); *np = i; return res; } } #define BSize 80 static PeepReplace *ReadReplacement(PeepHole const *ph, int *chp) { int ch = WantCh('(', *chp, "ReadReplacement"); Id id; PeepReplace *res = (PeepReplace *) malloc(sizeof(*res)); if (ch == '{') { int count = 0; int depth = 0; char *p[32]; int i = 0; char b[BSize]; for (;; ch = NextCh()) { if (ch == EOF) FatalError("EOF in replacement proc"); if (i == BSize-1) { char *q = (char *)malloc(BSize); b[BSize-1] = 0; memcpy(q, b, BSize); p[count++] = q; i = 0; } b[i++] = ch; if (ch == '}') { if (--depth == 0) break; } else if (ch == '{') { depth++; } } if (i > 0) { char *q = (char *)malloc(i+1); b[i] = 0; memcpy(q, b, i+1); p[count++] = q; } { ProcDef *d = (ProcDef *) malloc(sizeof(ProcDef)+count * sizeof(char *)); d->n = count; memcpy(d->line, p, count * sizeof(char *)); d->next = 0; *(rproc.end) = d; rproc.end = &d->next; res->procno = rproc.count++; ch = ReadId(&id, SigCh(NextCh())); i = FindOp(id.b, ph->ops, ph->opcount); if (i < 0) SyntaxError("Bad op label %s", id.b); d->arg = HeapString(&id); } res->type = prt_proc; res->f1.type = pft_inst; res->f1.f.f.inst = i; res->f2.type = pft_none; } else { KeyFnTable const *fn; int args = 2; int rflag = rf_rid; res->procno = -1; ch = ReadId(&id, ch); fn = LookUpFn(&id, replace_keys); if (fn != 0) { res->type = (P_ReplaceType)fn->val; rflag = rf_rid+rf_lab; args = fn->args; } else { KeyTable const *k; k = LookUp(&id, replace_ops); if (k == 0) SyntaxError("Bad replace operator %s", id.b); res->type = (P_ReplaceType)k->val; } ch = ReadField(&id, ph, &res->f1, ch, rflag); if (args > 1) ch = ReadField(&id, ph, &res->f2, ch, rf_rid); else res->f2.type = pft_none; } *chp = WantCh(')', ch, "ReadReplacement"); return res; } static int TargetInst(PeepReplace *pr) { return (pr->f1.type != pft_field && pr->f1.type != pft_inst) ? 0 : pr->f1.f.f.inst; } static void ReadReplacements(PeepHole *ph, int *chp) { PeepReplace *pr[MaxReplace]; int n = 0, i; int ch = SigCh(*chp); for (; ch == '('; n++) { pr[n] = ReadReplacement(ph, &ch); } for (i = 0; i < n; i++) ph->ops[TargetInst(pr[i])]->replacecount++; for (i = 0; i < ph->opcount; i++) { PeepOp *op = ph->ops[i]; PeepReplaceDef *prd = (PeepReplaceDef *) malloc(sizeof(*prd) + (op->replacecount-1) * sizeof(PeepReplace *)); op->replace.r = prd; prd->next = 0; prd->op = op; op->replacecount = 0; } for (i = 0; i < n; i++) { PeepOp *op = ph->ops[TargetInst(pr[i])]; op->replace.r->replace[op->replacecount++] = pr[i]; } for (i = 0; i < ph->opcount; i++) { PeepOp *op = ph->ops[i]; if (op->replacecount > 1) { int j; bool hadnonkill = NO, hadkill = NO; PeepReplace **r = op->replace.r->replace; for (j = 0; j < op->replacecount; j++) if (r[j]->type == prt_kill) hadkill = YES; else if (r[j]->type != prt_asr) hadnonkill = YES; if (hadkill && hadnonkill) Warn("kill together with field write probably mistaken"); } } *chp = WantCh(')', ch, "ReadReplacements"); } #define DEFINE_JOPTABLE 1 #define DEFINE_A_JOPTABLE 1 #define ENABLE_CG 1 /* bodge - get JOPCODE tables to include names */ #define JOPCODEDEF_ONLY #define _defs_LOADED 1 #include "options.h" #include "jopcode.h" #include "mcdpriv.h" static int32 u_bit[] = { /* this table is indexed with P_OpPred! */ _J_SET_R1, _J_READ_R1, _J_READ_R2, _J_READ_R3, _J_READ_R4, _J_SET_R2 }; static int32 a_u_bit[] = { /* this table is indexed with P_OpPred! */ _a_set_r1, _a_read_r1, _a_read_r2, _a_read_r3, _a_read_r4, _a_set_r2 }; #define JOPNAME(op) ((op)<=J_LAST_JOPCODE ? joptable[op].name :\ a_joptable[(op)-(J_LAST_JOPCODE+1)].name) static bool MatchOp(char const *opplus, const char *op) { char justop[16]; if (opplus[0] == 'J' && opplus[1] == '_') { int len = strcspn(opplus, " +"); memcpy(justop, &opplus[2], len-2); justop[len-2] = 0; opplus = &justop[0]; } return StrEq(opplus, op); } static bool OpSatisfies(J_OPCODE op, PeepOpDef const *p) { switch(p->type) { case pot_and: return OpSatisfies(op, p->p.sub.op1.p) && OpSatisfies(op, p->p.sub.op2.p); case pot_or: return OpSatisfies(op, p->p.sub.op1.p) || OpSatisfies(op, p->p.sub.op2.p); case pot_andnot: return OpSatisfies(op, p->p.sub.op1.p) && !OpSatisfies(op, p->p.sub.op2.p); case pot_prop: if (op <= J_LAST_JOPCODE) return (_joptable(op) & u_bit[p->p.prop.val]) != 0; else return (a_attributes(op) & a_u_bit[p->p.prop.val]) != 0; case pot_op_m: case pot_op: return MatchOp(p->p.op.val.c, JOPNAME(op)); case pot_opinset_m: case pot_opinset: { char const *opname = JOPNAME(op); int i = 0; for (i = 0; i < p->setcount; i++) if (MatchOp(p->p.set.ops.cp[i], opname)) return YES; return NO; } default: return YES; } } static unsigned32 a_opuse(char const *op, P_OpPred u) { int n = 0; char justop[16]; if (op[0] == 'J' && op[1] == '_') { int len = strcspn(op, " +"); memcpy(justop, &op[2], len-2); justop[len-2] = 0; op = &justop[0]; } for (n = 0; joptable[n].name != 0; n++) if (StrEq(op, joptable[n].name)) return _joptable(n) & u_bit[u]; for (n = 0; a_joptable[n].name != 0; n++) if (StrEq(op, a_joptable[n].name)) return a_joptable[n].bits & a_u_bit[u]; return 0; } static bool peepop_use(PeepOpDef const *p, P_OpPred u) { if (u == p_uses_r4) /* uses_r4 - a function of peep as well as op */ return YES; /* WD: is fault!!!!!!!!!!! */ switch (p->type) { case pot_op_m: case pot_op: return a_opuse(p->p.op.val.c, u) != 0; case pot_prop: return p->p.prop.val == u; case pot_opinset: case pot_opinset_m: { int i = 0; for (i = 0; i < p->setcount; i++) if (a_opuse(p->p.set.ops.cp[i], u)) return YES; return NO; } case pot_andnot: return peepop_use(p->p.sub.op1.p, u); case pot_and: case pot_or: return peepop_use(p->p.sub.op1.p, u) || peepop_use(p->p.sub.op2.p, u); } return NO; } static bool FindConstraintEqFields(P_InstField *resf, PeepHole *p, P_InstField *f) { int cix = 0; for (; cix < p->constraintcount; cix++) { PeepConstraint *pc = p->constraints[cix]; if (pc->f1.type == pft_field && pc->f2.type == pft_field) { if (pc->f1.f.f.inst == f->inst && pc->f1.f.f.field == f->field) { *resf = pc->f2.f.f; return YES; } else if (pc->f2.f.f.inst == f->inst && pc->f2.f.f.field == f->field) { *resf = pc->f1.f.f; return YES; } } } return NO; } static void DeduceDeadBits(PeepHole *p) { int i; for (i = 0; i < p->opcount; i++) { int count = p->ops[i]->replacecount; PeepReplace **prv = p->ops[i]->replace.r->replace; for (; --count >= 0; ) { PeepReplace *pr = prv[count]; P_ReplaceType w = pr->type; P_InstField otherf; if (w == prt_set && pr->f2.type == pft_field) { if (pr->f1.f.f.field == pf_r1 && peepop_use(&p->ops[i]->op, p_loads_r1) && FindConstraintEqFields(&otherf, p, &pr->f1.f.f)) p->ops[otherf.inst]->dead |= deadbit(otherf.field); } else if (w == prt_kill && peepop_use(&p->ops[i]->op, p_loads_r1)) { P_InstField f; f.inst = i; f.field = pf_r1; if (FindConstraintEqFields(&otherf, p, &f)) { int countj = p->ops[otherf.inst]->replacecount; P_Field field = otherf.field; int j; PeepReplace **pjv = p->ops[otherf.inst]->replace.r->replace; for (j = 0; j < countj ; j++) { PeepReplace *pj = pjv[j]; if (pj->type == prt_swapr2r3 && (field == pf_r2 || field == pf_r3)) field = field == pf_r2 ? pf_r3 : pf_r2; else if (pj->type == prt_set && pj->f2.type == pft_field && pj->f1.f.f.field == field) { p->ops[otherf.inst]->dead |= deadbit(otherf.field); break; } } } } } } } static bool n_use(char const *newop, PeepOpDef const *p, P_OpPred u) { bool b; if (newop != NULL) b = (a_opuse(newop, u) != 0); else b = peepop_use(p, u); return b; } static bool FirstRealOp(PeepOp **ops, int i) { for (; --i >= 0; ) if (ops[i]->op.type != pot_none) return NO; return YES; } #define OldUsesField(p, i, f) \ ((f)>=pf_r1 && (f) <= pf_r4 && \ peepop_use(&(p)->ops[i]->op, (P_OpPred)((f)+p_uses_r1-pf_r1))) #define OldWritesR1(p, i) peepop_use(&(p)->ops[i]->op, p_loads_r1) #define NewUsesField(new, p, i, f) \ ((f)>=pf_r1 && (f) <= pf_r4 && \ n_use(new, &(p)->ops[i]->op, (P_OpPred)((f)+p_uses_r1-pf_r1))) #define NewWritesR1(new, p, i) n_use(new, &(p)->ops[i]->op, p_loads_r1) static void DeduceUsage(PeepHole *p) { int i; if (p->gapconstraint != NULL && StrEq(p->gapconstraint, "G_ANY")) return; for (i = 0; i < p->constraintcount; i++) { PeepConstraint *c = p->constraints[i]; if (c->ctype == pct_eq && c->f1.type == pft_field && c->f2.type == pft_field) { P_InstField *f1 = &c->f1.f.f, *f2 = &c->f2.f.f; if (f1->inst < f2->inst) f1 = &c->f2.f.f, f2 = &c->f1.f.f; else if (f1->inst == f2->inst) continue; /* f1 is in the earlier instruction */ if ( OldUsesField(p, f2->inst, f2->field) && ( OldUsesField(p, f1->inst, f1->field) || ( f1->field == pf_r1 && OldWritesR1(p, f1->inst)) )) MayNotKill(p, f1->inst, f1->field); } } for (i = 0; i < p->opcount; i++) { int count = p->ops[i]->replacecount; PeepReplace **prv = p->ops[i]->replace.r->replace; bool swap = NO; int c; char const *newop = NULL; for (c = 0; c < count; c++) { PeepReplace *pr = prv[c]; if (pr->type == prt_set && pr->f1.type == pft_field && pr->f1.f.f.field == pf_op && pr->f2.type == pft_int) { newop = pr->f2.f.val; break; } } for (c = 0; c < count; c++) { PeepReplace *pr = prv[c]; switch (pr->type) { case prt_swapr2r3: swap = YES; break; case prt_kill: if (i != 0 && OldWritesR1(p, i)) MayNotUse(p, i, pf_r1); break; case prt_set: { P_Field f1 = pr->f1.f.f.field; if (OldUsesField(p, i, f1)) { P_Field f = f1; if (swap && (f == pf_r2 || f == pf_r3)) f = f == pf_r2 ? pf_r3 : pf_r2; MayNotKill(p, i, f); } if (pr->f2.type == pft_field) { int i2 = pr->f2.f.f.inst; if (p->ops[i]->op.type == pot_none && FirstRealOp(p->ops, i2)) break; if (OldUsesField(p, i2, pr->f2.f.f.field) && NewUsesField(newop, p, i, f1)) MayNotKill(p, i2, pr->f2.f.f.field); else if (f1 == pf_r1 && NewWritesR1(newop, p, i)) MayNotUse(p, i, pf_r1); } } } } } } #undef MayNotKill #undef MayNotUse #undef OldUsesField #undef OldWritesR1 #undef NewUsesField #undef NewWritesR1 static void WriteDeadBits(int d, FILE *f) { int i = pf_r1; for (; i <= pf_r4; i++) if (d & deadbit(i)) { d ^= deadbit(i); fputs(dead_name[i], f); if (d == 0) break; fputc('+', f); } } static void WriteUsage(int u, char const *after, FILE *f) { int n; if (u == 0) fputc('0', f); else for (n = pu_r1; n < pu_r3mask; n++) if (u & (1 << n)) { u ^= 1 << n; fputs(use_name[n], f); if (u == 0) break; fputc('+', f); } fputs(after, f); } static PeepHole *ReadPeepHole(int *chp) { bool traceit = NO; int ch = SigCh(*chp); if (ch == 'T') { traceit = YES; ch = SigCh(NextCh()); } if (ch == EOF) return 0; { PeepHole *p = (PeepHole *) malloc(sizeof(*p)); p->next = NULL; p->index = ++peephole_index; p->trace = traceit; p->gapconstraint = NULL; ch = WantCh('(', ch, "ReadPeepHole 1"); p->ops = ReadOps(&ch, &p->opcount); ch = WantCh('(', ch, "ReadPeepHole 2"); p->constraints = ReadConstraints(p, &ch, &p->constraintcount); ch = WantCh('(', ch, "ReadPeepHole 3"); ReadReplacements(p, &ch); DeduceDeadBits(p); DeduceUsage(p); if (debug) { int i = p->opcount; int ix = 0; for (; --i >= 0; ) { PeepOp *op = p->ops[i]; int end = op->debugix; int posn = 0; if (debugbuf[end] == '\n') end--; else if (debugbuf[end+1] == ')' && debugbuf[end+2] == '\n') end++; /* cope with single op given as ( xx(..) ) */ for (; ix <= end; ix++) { char c = debugbuf[ix]; if (c == '\n') posn = 0; else posn++; fputc(c, debug); } for (; posn < 50; posn++) fputc(' ', debug); fputs("; ", debug); if (op->dead != 0) WriteDeadBits(op->dead, debug); if (op->maynot.use != 0) { fputs(" maynotuse ", debug); WriteUsage(op->maynot.use, "", debug); } if (op->maynot.kill != 0) { fputs(" maynotkill ", debug); WriteUsage(op->maynot.kill, "", debug); } if (debugbuf[ix] != '\n') fputc('\n', debug); } for (; ix < debugix; ix++) fputc(debugbuf[ix], debug); debugix = 0; } *chp = WantCh(')', ch, "ReadPeepHole"); return p; } } static void WriteField(PeepField const *f, char const *after) { switch (f->type) { case pft_none: fputc('0', output); break; case pft_int: fputs(f->f.val, output); break; case pft_field: fprintf(output, "fb_(%d, %s)", f->f.f.inst, field_name[f->f.f.field]); break; case pft_inst: fprintf(output, "fb_(%d, 0)", f->f.f.inst); break; case pft_constraint: case pft_exprn: fprintf(output, "%d", f->f.ex.i); break; } fputs(after, output); } typedef struct OpDefList { struct OpDefList *next; PeepOpDef *op; } OpDefList; typedef struct IOpList { struct IOpList *next; char *val; } IOpList; static int setindex, opindex; static IOpList *iops; static IOpList **iopp; static OpDefList *opdefs; static OpDefList **opdefp; static int NewOpList(char *op) { IOpList *p = (IOpList *) malloc(sizeof(*p)); p->next = 0; p->val = op; *iopp = p; iopp = &p->next; return setindex++; } static int FindOpList(char *op) { IOpList *p = iops; int i = 0; for (; p != NULL; p = p->next, i++) if (op == p->val) return i; return NewOpList(op); } static int FindSubOp(PeepOpDef *op) { OpDefList *p = opdefs; int i = 0; for (; p != NULL; p = p->next, i++) if (memcmp(p->op, op, sizeof(*op)) == 0) return i; p = (OpDefList *) malloc(sizeof(*p)); p->next = 0; p->op = op; *opdefp = p; opdefp = &p->next; return opindex++; } static void WriteTableForOp(PeepOpDef *p) { switch (p->type) { case pot_peep: case pot_op: if (p->p.op.mask.c != 0) { p->p.op.val.i = FindOpList(p->p.op.val.c); p->p.op.mask.i = FindOpList(p->p.op.mask.c); p->type = (P_OpType)(p->type + (pot_peep_m - pot_peep)); } break; case pot_opinset: if (p->p.set.mask.c != 0) { p->p.set.mask.i = FindOpList(p->p.set.mask.c); p->type = pot_opinset_m; } else p->p.set.mask.i = 0; { IOpList *q = iops; int i = 0; for (; q != NULL; q = q->next, i++) if (q->val == p->p.set.ops.cp[0]) { int ix = 1; IOpList *qq = q->next; for (; ix < p->setcount && qq != NULL; qq = qq->next, ix++) if (qq->val != p->p.set.ops.cp[ix]) break; if (ix==p->setcount) break; } if (q == NULL) { int ix; for (ix = 0; ix < p->setcount; ix++) NewOpList(p->p.set.ops.cp[ix]); } p->p.set.ops.i = i; } break; case pot_and: case pot_or: case pot_andnot: { PeepOpDef *op1 = p->p.sub.op1.p, *op2 = p->p.sub.op2.p; WriteTableForOp(op1); WriteTableForOp(op2); p->p.sub.op1.i = FindSubOp(op1); p->p.sub.op2.i = FindSubOp(op2); break; } case pot_none: case pot_prop: break; } } static void WriteOpDef(PeepOpDef *p, char const *after, RegisterUsage const *u) { fprintf(output, "{%s, ", pot_name[p->type]); WriteUsage(u->use, ", ", output); WriteUsage(u->kill, ", ", output); switch (p->type) { case pot_none: fputs("0, 0", output); break; case pot_prop: fprintf(output, "0, %s", opr_name[p->p.prop.val]); break; case pot_peep: case pot_op: fprintf(output, "0, %s", p->p.op.val.c); break; case pot_op_m: case pot_peep_m: fprintf(output, "0, fh_(%d, %d)", p->p.op.mask.i, p->p.op.val.i); break; case pot_and: case pot_or: case pot_andnot: fprintf(output, "0, fh_(%d, %d)", p->p.sub.op1.i, p->p.sub.op2.i); break; case pot_opinset_m: case pot_opinset: fprintf(output, "%d, fh_(%d, %d)", p->setcount, p->p.set.mask.i, p->p.set.ops.i); } fprintf(output, "}%s", after); } static RegisterUsage const nullusage = {0, 0}; static void WriteOpTables(PeepHole *pl) { int i; setindex = 0; opindex = 0; opdefs = 0; iops = 0; opdefp = &opdefs; iopp = &iops; for (; pl != NULL; pl = pl->next) { PeepOp **ops = pl->ops; for (i = 0; i < pl->opcount; i++) WriteTableForOp(&ops[i]->op); } fputs("static const int32 peepsets[] = {\n", output); for (i = 0; iops != NULL; i++, iops = iops->next) fprintf(output, " /*%3d*/%s,\n", i, iops->val); fputs(" 0\n};\nstatic const PeepOpDef peepsubs[] = {", output); for (i = 0; opdefs != NULL; i++, opdefs = opdefs->next) { if (i != 0) fputc(',', output); fprintf(output, "\n /*%3d*/", i); WriteOpDef(opdefs->op, "", &nullusage); } if (i == 0) fputs("\n {0, 0, 0}", output); fputs("\n};\n", output); } static PeepReplaceDef *replacelist[MaxReplace]; static int replacementcount; static bool SameField(PeepField const *f1, PeepField const *f2) { if (f1->type != f2->type) return NO; switch (f1->type) { case pft_int: return f1->f.val == f2->f.val; case pft_field: return f1->f.f.inst == f2->f.f.inst && f1->f.f.field == f2->f.f.field; case pft_inst: return f1->f.f.inst == f2->f.f.inst; case pft_exprn: return f1->f.ex.i == f2->f.ex.i; default: return YES; } } static PeepExprn *exlist; static PeepExprn **expptr; static void NoteExprnsInField(PeepField *f) { if (f->type == pft_exprn) { PeepExprn *ex = f->f.ex.ex; NoteExprnsInField(&ex->f1); NoteExprnsInField(&ex->f2); { PeepExprn *p = exlist; int n = 0; for (; p != 0; p = p->next, n++) { if (p->op == ex->op && p->fn == ex->fn && SameField(&p->f1, &ex->f1) && SameField(&p->f2, &ex->f2)) { f->f.ex.i = n; return; } } ex->next = NULL; *expptr = ex; expptr = &ex->next; f->f.ex.i = n; } } } static void WriteExprns(void) { int i = 0; fputs("static PeepExprn const peepexprns[] = {\n", output); for (; exlist != NULL; exlist = exlist->next, i++) { if (i != 0) fputs(",\n", output); fprintf(output, " /*%3d*/{%s, ", i, peo_name[exlist->op]); if (exlist->fn == NULL) fputs("0, ", output); else fprintf(output, "pep_%s, ", exlist->fn); fprintf(output, "%s, %s, ", ft_name[exlist->f1.type], ft_name[exlist->f2.type]); WriteField(&exlist->f1, ","); WriteField(&exlist->f2, "}"); } if (i == 0) fputs(" {}", output); fputs("\n};\n\n", output); } static bool SameReplace(PeepReplace const *r1, PeepReplace const *r2) { return (r1->type == r2->type && r1->f1.type == r2->f1.type && r1->procno == r2->procno && (r1->f1.type != pft_field || r1->f1.f.f.field == r2->f1.f.f.field) && SameField(&r1->f2, &r2->f2)); } static void WriteReplacements(void) { int count = MaxReplace; int index = 0; PeepReplace **replacements = (PeepReplace **) malloc(replacementcount * sizeof(PeepReplace *)); fputs("static PeepReplace const replacements[] = {\n /* 0*/", output); { int i, c; for (c = count; --c >= 0;) { PeepReplaceDef *prd = replacelist[c]; for (; prd != NULL; prd = prd->next) for (i = 0; i < c; i++) NoteExprnsInField(&(prd->replace[i]->f2)); } } for (; --count >= 0;) { PeepReplaceDef *prd = replacelist[count]; for (; prd != NULL; prd = prd->next) { int r; if (count == 0) { prd->op->replace.i = 0; continue; } for (r = 0; r <= index - count; r++) { if (SameReplace(replacements[r], prd->replace[0])) { int i; for (i = 1; i < count; i++) if (!SameReplace(replacements[r+i], prd->replace[i])) break; if (i == count) { prd->op->replace.i = r; goto alreadypresent; } } } prd->op->replace.i = index; for (r = 0; r < prd->op->replacecount; r++, index++) { PeepReplace *pr = prd->replace[r]; replacements[index] = pr; if (index != 0 || r != 0) fprintf(output, ",\n /*%3d*/", index); if (pr->procno >= 0) { fprintf(output, "{%s, 0, 0, %d}", rt_name[pr->type], pr->procno); } else if (pr->f1.type != pft_field && pr->f2.type == pft_none) { fprintf(output, "{%s}", rt_name[pr->type]); } else { fprintf(output, "{%s, %s, %s, ", rt_name[pr->type], field_name[pr->f1.f.f.field], ft_name[pr->f2.type]); WriteField(&pr->f2, "}"); } } alreadypresent:; } } fputs("\n};\n", output); } static void CollectReplacements(int n, PeepOp **ops) { for (; --n >= 0; ) { int count = ops[n]->replacecount; PeepReplaceDef *pr = ops[n]->replace.r; pr->next = replacelist[count]; replacelist[count] = pr; replacementcount += count; } } static void WriteOps(int ix, int n, PeepOp * const *ops) { int i; fprintf(output, "static PeepOp const p%d_ops[] = {\n {", ix); for (i = 0; i < n; i++) { PeepOp *op = ops[i]; if (i != 0) fputs(",\n {", output); WriteOpDef(&op->op, ", ", &op->maynot); if (op->dead == 0) fputc('0', output); else WriteDeadBits(op->dead, output); fprintf(output, ", %d, %d}", op->replacecount, op->replace.i); } fputs("};\n", output); } static void CheckArgCt(FnArgList *p, char const *type) { for (; p != NULL; p = p->next) fprintf(output, "\ #if %s_argct_%s != %d\n # error wrong argument count for %s_%s\n#endif\n", type, p->fn, p->args, type, p->fn); } static void NoteExprnsInConstraint(PeepConstraint *pc) { if (pc->f1.type == pft_constraint) NoteExprnsInConstraint(pc->f1.f.c.c); else NoteExprnsInField(&pc->f1); if (pc->f2.type == pft_constraint) NoteExprnsInConstraint(pc->f2.f.c.c); else NoteExprnsInField(&pc->f2); } static int CollectSubConstraints(PeepHole *p, PeepConstraint *pc, PeepConstraint **subc, int ix) { if (pc->f1.type == pft_constraint) { ix = CollectSubConstraints(p, pc->f1.f.c.c, subc, ix); subc[ix] = pc->f1.f.c.c; pc->f1.f.c.i = p->constraintcount+ix; ix++; } if (pc->f2.type == pft_constraint) { ix = CollectSubConstraints(p, pc->f2.f.c.c, subc, ix); subc[ix] = pc->f2.f.c.c; pc->f2.f.c.i = p->constraintcount+ix; ix++; } return ix; } static void WriteConstraint(PeepConstraint *pc, bool nl) { if (nl) fprintf(output, ",\n"); fprintf(output, " {%s, ", ct_name[pc->ctype]); if (pc->proc != NULL) fprintf(output, "pcp_%s, ", pc->proc); else fputs("0, ", output); fprintf(output, "%s, %s, ", ft_name[pc->f1.type], ft_name[pc->f2.type]); WriteField(&pc->f1, ", "); WriteField(&pc->f2, "}"); } typedef struct IntList { struct IntList *next; int i; } IntList; static struct { int count; IntList *p; } perop[J_LAST_A_JOPCODE+1]; static void WritePeepHoles(PeepHole *pl) { fputs("typedef int32 propproc(const PendingOp *const p);\n", output); fputs("static propproc * const peepprops[] = {\n", output); fputs(" a_loads_r1,\n a_uses_r1,\n a_uses_r2,\n a_uses_r3,\n a_uses_r4,\n a_loads_r2\n};\n", output); fputs("#define p_loads_r1 0\n#define p_uses_r1 1\n", output); fputs("#define p_uses_r2 2\n#define p_uses_r3 3\n", output); fputs("#define p_uses_r4 4\n#define p_loads_r2 5\n", output); fputs("#define fb_(a, b) ((((int32)(a))<<8) | (b))\n", output); fputs("#define fh_(a, b) ((((int32)(a))<<16) | (b))\n", output); { PeepHole *p; PeepConstraint *subc[MaxConstraints]; int i; exlist = 0; expptr = &exlist; WriteOpTables(pl); replacementcount = 0; for (p = pl; p != NULL; p = p->next) for (i = 0; i < p->constraintcount; i++) NoteExprnsInConstraint(p->constraints[i]); for (p = pl; p != NULL; p = p->next) CollectReplacements(p->opcount, p->ops); WriteReplacements(); WriteExprns(); for (p = pl; p != NULL; p = p->next) { WriteOps(p->index, p->opcount, p->ops); if (p->constraintcount != 0) { int subc_ix = 0; for (i = 0; i < p->constraintcount; i++) subc_ix = CollectSubConstraints(p, p->constraints[i], subc, subc_ix); fprintf(output, "static PeepConstraint const c%d[] = {\n", p->index); for (i = 0; i < p->constraintcount; i++) WriteConstraint(p->constraints[i], i != 0); for (i = 0; i < subc_ix; i++) WriteConstraint(subc[i], YES); fputs("};\n", output); } } } fputs("static PeepHole const patterns[] = {\n", output); for (; pl != NULL; pl = pl->next) { fprintf(output, " {&p%d_ops[0], ", pl->index); if (pl->constraintcount != 0) fprintf(output, "&c%d[0]", pl->index); else fputc('0', output); fprintf(output, ", %d, %d, %d, %s}", pl->opcount, pl->constraintcount, pl->trace, pl->gapconstraint == NULL ? "0": pl->gapconstraint); if (pl->next != NULL) fputc(',', output); fputc('\n', output); } fprintf(output, "};\n\n#define PeepholeMax %d\n#define MaxInst %d\n", peephole_index, opMax); CheckArgCt(constraintfns, "pcp"); CheckArgCt(exprnfns, "pep"); { int i; char *b; for (i = 0; i <= J_LAST_A_JOPCODE; i++) { IntList *ip = perop[i].p; if (ip != NULL) { b = ""; fprintf(output, "static int const po_%d[] = { /* %s */\n", i, JOPNAME(i)); for (; ip != NULL; ip = ip->next) { fprintf(output, "%s\t%d", b, ip->i-1); b = ",\n"; } fputs("\n};\n", output); } } fputs("\nstatic struct { int i; int const *peepv; } const peepholeperop[] = {\n", output); b = ""; for (i = 0; i <= J_LAST_A_JOPCODE; i++) { fprintf(output, "%s\t{%d, ", b, perop[i].count); if (perop[i].count == 0) fputs("0", output); else fprintf(output, "&po_%d[0]", i); b = "},\n"; } fputs("}\n};\n", output); } } static void ComputePeepholesPerOp(PeepHole *pl) { int i = 0; for (i = 0; i <= J_LAST_A_JOPCODE; i++) { IntList **ip = &perop[i].p; PeepHole *p; perop[i].count = 0; perop[i].p = 0; for (p = pl; p != NULL; p = p->next) { if (OpSatisfies(i, &(p->ops[0]->op))) { IntList *t = (IntList *) malloc(sizeof(*t)); perop[i].count++; t->next = NULL; t->i = p->index; *ip = t; ip = &t->next; } } } } static void ArgErr(char const *mess, char const *arg) { fprintf(stderr, "%s%s\n", mess, arg); exit(1); } static char *AddHeapString(char const *s) { return NewHeapString(s, strlen(s)); } int main(int argc, char **argv) { int ch = 0; PeepHole *pl = 0, **pp = &pl; int argno = 1; syms = NULL; debug = NULL; constraintfns = exprnfns = NULL; if (StrEq(argv[1], "-d") || StrEq(argv[1], "-D")) { debugbuf = (char *)malloc(DebugSize); debugix = 0; if (StrEq(argv[2], "-")) { debug = stdout; } else { debug = fopen(argv[2], "w"); if (debug == NULL) ArgErr("can't write ", argv[2]); } argno = 3; } if (argc != (2 + argno)) ArgErr("Usage: peepgen <source> <destn>", ""); if (StrEq(argv[argno], "-")) input = stdin; else { input = fopen(argv[argno], "r"); if (input == NULL) ArgErr("can't read ", argv[argno]); } argno++; if (StrEq(argv[argno], "-")) { outputfile = 0; output = stdout; } else { outputfile = argv[argno]; output = fopen(outputfile, "w"); if (output == NULL) ArgErr("can't write ", argv[argno]); } pcp_regset_unused = AddHeapString("regset_unused"); pcp_regset_unkilled = AddHeapString("regset_unkilled"); pcp_nointervening = AddHeapString("nointervening"); pep_bit = AddHeapString("bit"); opMax = 0; InitProcDefList(&rproc); line_number = 1; bracket_nesting = 0; ch = NextCh(); for (; ch != EOF ;) { PeepHole *ph = ReadPeepHole(&ch); if (ph == NULL) break; *pp = ph; pp = &ph->next; } { ProcDef *p; int i = 0; for (p = rproc.list; p != 0; p = p->next) { int l; fprintf(output, "static bool rproc__%d(PendingOp *%s, PendingOp **ops, RegisterUsage *u)\n", i++, p->arg); for (l = 0; l < p->n; l++) fprintf(output, "%s", p->line[l]); fputc('\n', output); } fputs("static RProc * const rprocs[] = {\n", output); for (i = 0; i < rproc.count; i++) fprintf(output, " rproc__%d,\n", i); fputs(" 0\n};\n\n", output); } ComputePeepholesPerOp(pl); WritePeepHoles(pl); return 0; }
stardot/ncc
cfe/syn.h
<gh_stars>0 /* * cfe/syn.h * Copyright (C) Acorn Computers Ltd., 1988 * Copyright (C) Codemist Ltd., 1988-1993 * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _syn_h #define _syn_h #ifndef _defs_LOADED # include "defs.h" #endif extern bool syn_hashif(void); extern bool implicit_return_ok; extern int32 syn_begin_agg(void); extern void syn_end_agg(int32 beganbrace); extern Expr *syn_rdinit(TypeExpr *t, Binder *whole, int32 flag); extern bool syn_canrdinit(void); extern Expr *rd_expr(int n); extern Expr *rd_ANSIstring(void); extern TopDecl *rd_topdecl(bool); extern void syn_init(void); #ifdef CPLUSPLUS extern void xsyn_reinit(void); #define syn_reinit() xsyn_reinit() #else #define syn_reinit() ((void)0) #endif extern AEop peepsym(void); extern void checkfor_ket(AEop s); extern void checkfor_delimiter_ket(AEop s, msg_t expected1, msg_t expected1a); extern void checkfor_2ket(AEop s, AEop t); extern void checkfor_delimiter_2ket(AEop s, AEop t); #define PASTCOMMA 10 #define UPTOCOMMA 11 #define UPTORELOP 29 #ifdef CPLUSPLUS extern int recursing; /* check by mkctor_v_1 but save/restore on function context changes */ extern void add_pendingfn(Symstr *name, Symstr *realname, TypeExpr *t, SET_BITMAP stg, TagBinder *scope, ScopeSaver formaltags, int tokhandle, ScopeSaver templateformals, bool tfn); extern void syn_attempt_template_memfn(Binder *generic, Binder *specific); extern TagBinder *syn_implicit_instantiate_2(TagBinder *tb); extern ScopeSaver copy_env(ScopeSaver env, int n); extern void parameter_names_transfer(FormTypeList *from, FormTypeList *to); extern void add_expr_dtors(Expr *edtor); extern void add_to_saved_temps(SynBindList *tmps); #else #define add_pendingfn(a,b,c,d,e,f,g,h,i) ((void)0) #define copy_env(a,b) 0 #define parameter_names_transfer(a,b) 0 #define add_expr_dtors(a) 0 #define add_to_saved_temps(a) 0 #endif #endif /* end of cfe/syn.h */
stardot/ncc
mip/main.c
/* * main.c * The top level module of the compiler. * Copyright (C) 1996 Advanced RISC Machines Limited. All rights reserved. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <stdio.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> #include "host.h" #include "globals.h" #include "compiler.h" #if defined(FOR_ACORN) && defined(COMPILING_ON_RISCOS) #include "dde.h" #endif #define TOOLNAME armcc #include "toolbox.h" /* DEPEND_FORMAT used to output dependency line (-m option) */ #ifdef COMPILING_ON_MACINTOSH # define DEPEND_FORMAT "%s\304\t%s\n" #else # define DEPEND_FORMAT "%s:\t%s\n" #endif static FILE *errorstream; static void ErrorMessage(backchat_Diagnostic const *diag) { char const *msg = diag->msgtext; unsigned line = diag->lineno; char b[256]; cc_announce_error(b, diag->severity, diag->filename, line); #ifdef HOST_IS_RISCOS if (dde_throwback_flag != 0) switch(diag->severity) { case BC_SEVERITY_WARN: dde_throwback_send(THROWBACK_WARN, line, msg); break; case BC_SEVERITY_ERROR: dde_throwback_send(THROWBACK_ERROR, line, msg); break; case BC_SEVERITY_SERIOUS: dde_throwback_send(THROWBACK_SERIOUS, line, msg); break; } #endif fputs(b, errorstream); fputs(msg, errorstream); } static int BC(void *handle, unsigned code, const void *msg) { switch (code) { case BC_DIAGMSG: if (handle != NULL) errorstream = handle; ErrorMessage((backchat_Diagnostic const *)msg); break; case BC_INCLUDEMSG: { const backchat_InclusionDependency *dep = (const backchat_InclusionDependency *)msg; fprintf((FILE *)handle, DEPEND_FORMAT, dep->targetName, dep->dependsonName); } break; case BC_NULLMSG: break; } return 0; } int Tool_EditEnv(ToolEnv *t, HWND wh) { IGNORE(t); IGNORE(wh); return 0; } bool Tool_Configurable(ToolEnv *t, char const *name) { IGNORE(t); IGNORE(name); return YES; } int main(int argc, ArgvType *argv) { ToolEntryPoints const *ep; ToolEnv *env; int status; errorstream = stderr; ep = armccinit(); env = ep->toolenv_new(); ep->toolenv_mark(env); /* In case of -config argument */ ep->toolenv_merge(env, "*"); status = ep->toolbox_main(argc, argv, env, BC, NULL); if (errorstream != NULL && errorstream != stderr) fclose(errorstream); ep->toolenv_dispose(env); ep->toolbox_finalise(ep); exit(status); }
stardot/ncc
mip/defs.h
<reponame>stardot/ncc /* * defs.h: front-end to cg interface. * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Codemist Ltd., 1987-1992. * Copyright (C) Advanced RISC Machines Limited, 1991-1992. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 130 * Checkin $Date$ * Revising $Author$ */ /* * This file defines the set of data structures which constitute the * interface between a language-specific front-end and the code generator. * The set of structures is not yet minimal - some embedded comments point * to possible improvements. * * A similar file - cgdefs.h - defines structures which are global to the * code generator but hidden from front-ends. More private structures are * defined, perhaps opaquely, in individual module headers. * * Our intentions are good, but the execution of them is not yet perfect. * * General Convention: macros of the form foo_(x) are understood to be * access functions. Names with trailing underscores are used for no other * purpose. The names of access functions always end with an '_'. * * Some structures - e.g. Symstr and FloatCon - have trailing string fields * which are described as being of length [1]. These are actually allocated * as large as required to hold the relevant null-terminated value. */ #ifndef _defs_LOADED #define _defs_LOADED 1 #include "ieeeflt.h" #include "int64.h" /* The following lines allow the precise details of C++ scope rules */ /* to be ignored. Consider 'struct A { struct B *c; }' */ /* where B is undefined or 'struct A { struct C{} *c; };'. IF C++ */ /* really means that structs are SCOPE's then struct B (and its typedef */ /* should not be exported from scope A. gcc seems to export B/C! */ /* By pre-declaring we create the struct at top level, not inside A. */ typedef struct Binder Binder; typedef struct LabBind LabBind; typedef struct TagBinder TagBinder; typedef struct ExtRef ExtRef; typedef struct Cmd Cmd; typedef struct SynBindList SynBindList; typedef struct LabelNumber LabelNumber; typedef struct BindList BindList; typedef struct Handler Handler; typedef struct FormTypeList FormTypeList; typedef struct SynScope SynScope; typedef struct SynGoto SynGoto; typedef struct DeclRhsList DeclRhsList; /* * List is a generic list type of general utility. */ typedef struct List { struct List *cdr; IPtr car; } List; #define cdr_(p) ((p)->cdr) #define car_(p) ((p)->car) /* * List3 is used in some back-ends as an extended version of the existing * List2 datastructure but where extra informaton is needed - the only * case at the tim this note was written was for long-format forward * references where the extra field is used to cope with some ugly * issues about relocating 32-bit forward references where too many * offsets seem needed for the original structures. (ACN Feb '90) */ typedef struct List3 { struct List *cdr; IPtr car; IPtr csr; } List3; /* The following two lines are IPtrs, not int32 because they are either */ /* abused (e.g. cast to pointer in aetree.c) or for storage layout */ /* like an AEop h0_() field. */ typedef IPtr AEop; /* An AEop is implemented as an integer */ #define SET_BITMAP IPtr /* ... as are small sets... */ /* * Sometime the type VRegnum should be made into a union or some such that * can not accidentally be punned with an int32. */ typedef int32 VRegnum; /* a pity this has to be here, but... */ #ifndef NON_CODEMIST_MIDDLE_END /* * NMAGICREGS is defined here as whatever length integer comes out * of the arithmetic shows. This is intended to allow it to be a * preprocessor-available constant, whereas putting in a cast to (int32) * would mean that #if NMAGICREGS < .. etc would be illegal. * NANYARGREGS is useful as an array size (e.g. per-argument register info). * It is (harmlessly) overlarge if TARGET_FP_ARGS_CALLSTD2. */ #ifdef TARGET_SHARES_INTEGER_AND_FP_REGISTERS #define NMAGICREGS NINTREGS #define NANYARGREGS NARGREGS #else #define NMAGICREGS (NINTREGS+NFLTREGS) #define NANYARGREGS (NARGREGS+NFLTARGREGS) #endif typedef struct RealRegSet { unsigned32 map[(NMAGICREGS+31)/32]; } RealRegSet; #endif /* * A TypeExpr is the basic, generic node of a type expression tree. * The first field - called h0 for historical reasons - is a discriminator * which determines the fine structure of the node. * @@@ AM would like to swap typespecmap_ and typespecbind_ one day. */ typedef struct TypeExprFnAux { unsigned16 minargs, maxargs; unsigned8 variad, oldstyle; /* notionally bool */ unsigned32 flags; int32 inlinecode; } TypeExprFnAux; /* flags bits are bitoffnaux_() bits (0x3F), together with ... */ typedef int FnAuxFlags; #define f_resultinflags 0x800 #define f_resultinintregs 0x400 #define f_notailcall 0x200 #define f_specialargreg 0x100 #define f_nofpregargs 0x080 #define f_norettype 0x040 #define fntypeisvariadic(t) (maxargs_(t)==1999) /* could do with improvement */ /* * packTypeExprFnAux also sets the usedregs field to describe that ALL * registers are clobbered. A more refined value is set when/if the * function gets defined. Codemist + LDS agree this must be re-organised. */ #define packTypeExprFnAux1(s,mina,maxa,var,old,fl,il) \ (s.minargs=mina, s.maxargs=maxa, s.variad=((var)<0 ? 0:(var)), \ s.oldstyle=old, s.flags=fl, s.inlinecode = il, \ &s) #define packTypeExprFnAux(s,mina,maxa,var,old,fl) \ packTypeExprFnAux1(s,mina,maxa,var,old,fl,0) typedef struct TypeExpr TypeExpr; typedef struct Expr Expr; struct TypeExpr /* make into a better union type */ { AEop h0; union { TypeExpr *t; SET_BITMAP m; /* for s_typespec */ } typearg; union { Binder *b; TagBinder *tb; /* for struct / union */ BindList *bl; /* ovldlist */ SET_BITMAP m; /* ptrmap */ Expr *e; /* subsize */ } typespecbind; IPtr dbglanginfo; /* dbx support requires f77 type info */ #ifdef PASCAL /*ECN*/ union { TypeExpr *type; Expr *e; } pun; #endif union { FormTypeList *ftl; DeclRhsList *rhl; } fnargs; /* only if t_fnap */ TypeExprFnAux fnaux; /* only if t_fnap */ }; /* * TypeExpr access functions */ #define typearg_(p) ((p)->typearg.t) #define typespecmap_(p) ((p)->typearg.m) #define typespecbind_(p) ((p)->typespecbind.b) #define typespectagbind_(p) ((p)->typespecbind.tb) #define typefnargs_(p) ((p)->fnargs.ftl) #define typefnargs1_(p) ((p)->fnargs.rhl) #define typeovldlist_(p) ((p)->typespecbind.bl) #define typeptrmap_(p) ((p)->typespecbind.m) #define typesubsize_(p) ((p)->typespecbind.e) /* And the following apply only to function TypeExprs... */ #define typefnaux_(p) ((p)->fnaux) #define typedbginfo_(p) ((p)->dbglanginfo) #define minargs_(p) ((p)->fnaux.minargs) #define maxargs_(p) ((p)->fnaux.maxargs) #define typefnauxflags_(p) ((p)->fnaux.flags) #define TypeSpec TypeExpr /* used when known to be a s_typespec TypeExpr */ /* * A Symstr is a symbol table entry. Symstr's can be overloaded - i.e. can * have several definitions - e.g. as a variable name, as a structure field, * as a label. The 3 'overloading classes' (pointing to Binders of one kind * or another) are explicitly represented. */ typedef struct Symstr Symstr; struct Symstr { AEop h0; /* keyword or s_identifier. Must be first field */ Symstr *symchain; /* linear list of hash bucket members */ /* The 4 overloading classes... */ Binder *symbind; /* variable name, function name etc. */ LabBind *symlab; /* definition as a label */ TagBinder *symtag; /* structure, union, enumeration tag */ ExtRef *symext; /* Data about use as an external sym */ Symstr *symfold; /* for 6 char monocase extern check */ /* may one day allocate within *symext to save space here */ char symname[1]; /* Text name... allocated as needed */ }; /* * Symstr access functions */ #define symchain_(sym) ((sym)->symchain) #define symtype_(sym) ((sym)->h0) #define sympp_(sym) ((sym)->sympp) #define symlab_(sym) ((sym)->symlab) /* #define symtag_(sym) ((sym)->symtag) @@@ under threat */ #define symext_(sym) ((sym)->symext) #define symfold_(sym) ((sym)->symfold) /* #define symdata_(sym) ((sym)->bindglobal) @@@ under threat */ #ifdef CALLABLE_COMPILER #define symname_(sym) ((sym)->symname + 1) #else #define symname_(sym) ((sym)->symname) #endif #define bind_global_(sym) ((sym)->symbind) #define tag_global_(sym) ((sym)->symtag) #if defined(CALLABLE_COMPILER) #define dbgbinder_(sym) (*(Binder **)&((sym)->symext)) #endif /* * String literals in ANSI-C are naturally segmented, so the code * generator is prepared to handle segmented string values. */ typedef struct StringSegList StringSegList; struct StringSegList { StringSegList *strsegcdr; char *strsegbase; IPtr strseglen; }; typedef struct String { AEop h0; StringSegList *strseg; } String; typedef struct FloatCon { AEop h0; /* the type discriminator for the union */ SET_BITMAP floatlen; union { int32 irep[2]; /* so asemblers can print hex patterns */ DbleBin db; FloatBin fb; } floatbin; char floatstr[1]; /* the source representation - if there */ } FloatCon; /* is one (consider x = 1.0 + 2.0, which */ /* has none) - allocated as needed. */ typedef struct { AEop h0; SET_BITMAP typespec; union { int64 i; uint64 u; } bin; } Int64Con; /* * FileLine structures are used to describe source file positions and * in support of debugger table generation. Essentially, a FileLine can * associate a file name and position with any object. * Notionally, p should be of type struct dbg_... *. */ typedef struct FileLine { char const *f; /* The source file name */ unsigned16 l; /* Source file line number */ unsigned16 column; /* position within line */ int32 filepos; /* source file byte offset */ VoidStar p; } FileLine; typedef List ExprList; /* a list of Exprs is a List... */ /* * exprcar: ExprList -> Expr -- extract an Expr from an Expr list element * mkExprList: ExprList x Expr -> ExprList -- add an Expr to an ExprList */ #define exprcar_(l) (*(Expr **)&(l)->car) #define mkExprList(a,b) ((ExprList *)syn_cons2(a,b)) #define mkExprList1(x) (mkExprList(0,x)) #define mkExprList2(x,y) (mkExprList(mkExprList(0,y),x)) #define mkExprList3(x,y,z) (mkExprList(mkExprList(mkExprList(0,z),y),x)) #define mkExprList4(x,y,z,a) (mkExprList(mkExprList3(y,z,a),x)) #define mkExprList5(x,y,z,a,b) (mkExprList(mkExprList4(y,z,a,b),x)) typedef List CmdList; /* a list of commands is a List... */ /* * cmdcar: CmdList -> Cmd -- extract a Cmd from a Cmd list element * mkCmdList: CmdList x Cmd -> CmdList -- add a Cmdr to a CmdList */ #define mkCmdList(a,b) ((CmdList *)syn_cons2(a,b)) #define cmdcar_(l) (*(Cmd **)&(l)->car) /* * A node of an expression tree is an Expr... * (or a FloatCon or Int64Con or String or Binder) */ struct Expr { AEop h0; /* node type, discriminates unions */ TypeExpr *etype; FileLine *fileline; /* only a small subset of Exprs want this */ union { Expr *e; /* as in expr :: unop exprr... */ Cmd *c; /* for valof expressions... */ SynBindList *bl; /* for expr :: (let t; f(t,...)) */ IPtr i; /* h0==s_integer; expr = intval */ } arg1; /* Fields from here on are optional any may not even be allocated. */ union { Expr *e; /* e.g. expr :: expr binop expr, */ /* & const expr yielding arg1.i */ ExprList *l; /* as in expr :: f(expr,expr...) */ IPtr i; /* as in expr :: expr dot intval */ } arg2; union { Expr *e; /* eg ?-expr :: expr expr expr...*/ /* (as in (e1 ? e2 : e3)) */ IPtr i; /* for bitfields, intval bitsize */ } arg3; IPtr msboff; /* for bitfields, ms bit offset */ }; /* * And the Expr access functions... */ #define type_(p) ((p)->etype) #define arg1_(p) ((p)->arg1.e) #define arg2_(p) ((p)->arg2.e) #define arg2i_(p) ((p)->arg2.i) #define arg3_(p) ((p)->arg3.e) #define arg3i_(p) ((p)->arg3.i) #define exprletbind_(p) ((p)->arg1.bl) #define exprfnargs_(p) ((p)->arg2.l) #define exprdotoff_(p) ((p)->arg2.i) #define exprbsize_(p) ((p)->arg3.i) #define exprmsboff_(p) ((p)->msboff) #define expr1c_(p) ((p)->arg1.c) #define exprfileline_(p) ((p)->fileline) /* for integer constants */ #define intval_(p) ((p)->arg1.i) #define intorig_(p) arg2_(p) #define exb_(e) ((Binder *)(e)) #define exs_(e) ((String *)(e)) #define exi64_(e) ((Int64Con *)(e)) #define exf_(e) ((FloatCon *)(e)) #define int64map_(e) (exi64_(e)->typespec) #define int64val_(e) (exi64_(e)->bin) #ifdef TARGET_HAS_INLINE_ASSEMBLER typedef struct AsmInstr { struct AsmInstr *cdr; FileLine fl; IPtr opcode; Expr *opnd1, *opnd2, *opnd3, *opnd4; } AsmInstr; #define asmopcode_(p) ((p)->opcode) #define asmfl_(p) ((p)->fl) #define asmopnd1_(p) ((p)->opnd1) #define asmopnd2_(p) ((p)->opnd2) #define asmopnd3_(p) ((p)->opnd3) #define asmopnd4_(p) ((p)->opnd4) #endif #define handcdr cdr struct Handler { Handler *handcdr; SynBindList *handbl; Cmd *handbody; TypeExpr *caught_type; }; #define mkHandler(a,b,c,d) ((Handler *)syn_list4(a,b,c,d)) /* * The other essential object the code generator recognises is a Cmd, * which represents a command or statement. The structure is very flexible * and is designed to represent any C abstract syntax command. */ struct Cmd { AEop h0; /* The node type and union discriminator */ FileLine fileline; /* File, line, and code address hook... */ union { /* Then up to four component Cmd/Exprs...*/ Cmd *c; /* Consider, for example, the C 'for':- */ Expr *e; /* for-cmd :: expr expr expr cmd */ } cmd1, cmd2, cmd3, cmd4; /* (for (e1; e2; e3) stmnt;) */ }; /* * Cmd structure access functions... */ #define cmd1c_(x) ((x)->cmd1.c) #define cmd2c_(x) ((x)->cmd2.c) #define cmd3c_(x) ((x)->cmd3.c) #define cmd4c_(x) ((x)->cmd4.c) #define cmd1e_(x) ((x)->cmd1.e) #define cmd2e_(x) ((x)->cmd2.e) #define cmd3e_(x) ((x)->cmd3.e) #define cmd4e_(x) ((x)->cmd4.e) #define cmdfileline_(x) ((x)->fileline) /* * And some more convenient syntactic sugaring, which hints how other * structures such as case labels, labels, and blocks. */ #define cmd1lab_(c) ((LabBind *)cmd1c_(c)) #define switch_caselist_(c) cmd3c_(c) #define switch_default_(c) cmd4c_(c) #define case_next_(c) cmd3c_(c) #define case_lab_(c) ((LabelNumber *)cmd4c_(c)) #define cmdblk_bl_(c) ((SynBindList *)cmd1c_(c)) #define cmdblk_cl_(c) ((CmdList *)cmd2c_(c)) #define cmdhand_(c) ((Handler *)cmd2c_(c)) /* * LabBinds describe source-level labels (e.g. 'out' in goto out;... out:...) * and addres the corresponding internal LabelNumber. */ #define labcdr cdr struct LabBind { LabBind *labcdr; /* rev. list of binders at this scope level */ Symstr *labsym; /* the label's name */ LabelNumber *labinternlab; /* and its internal representation, */ /* (opaque to back end). */ IPtr labuses; /* flags, further elucidated below. */ union { SynGoto *ref; SynScope *def; } labu; /* opaque to all but C/C++ syn.c */ #ifdef PASCAL /*ECN*/ union { Binder *jbuf; Binder *proc; } lun; unsigned8 bindlevel; #endif }; /* * Flags for labuses in LabBind */ #define l_referenced 1L #define l_defined 2L /* * In C++, Binders, TagBinders and ClassMembers can all occur in name scopes, * on the same list of named entities, discriminated by their h0 fields. * Pro tem, and prior to more radical rationalisation, we ensure that each * structure has the same common head: * AEop h0; * SelfType *cdr; * Symstr *name; * TypeExpr *type; * SET_BITMAP attributes; * Attributes sweeps up C++ access specifiers (via bitofaccess_(), base * class flags and other miscellaneous flag values. Eventually, we could * unify attributes with h0. * AM, Jun-93: merge Binder and ClassMember. */ #define attributes_(p) ((p)->attributes) /* Fields of attributes... */ /* bitofaccess_(s_private, s_protected, s_public) = 0x700 */ #define A_DYNINIT 0x0100 /* Binder has dynamic init. */ #define A_NOLINKAGE 0x0400 /* [Tag]Binder has no linkage... */ #define A_INTERN 0x0800 /* Binder has internal linkage... */ #define A_EXTERN 0x1000 /* [Tag]Binder has external linkage... */ #define A_PRIMARY 0x2000 /* Binder is a primary template name */ #define A_TEMPLATE 0x4000 /* Binder is a template name. */ #define A_REALUSE 0x8000 #define CB_VBASE 0x10000 /* virtual base class */ #define CB_BASE 0x20000 /* base class */ #define CB_CORE 0x40000 /* base class core member */ #define CB_HASCOREFN CB_CORE /* real Binder has attached core Binder */ #define CB_VBPTR 0x80000 /* ptr to VBASE */ #define CB_VTAB 0x100000 /* vtable pointer... */ #define CB_ANON 0x200000 /* anon union binder */ #define CB_MASK 0x3f0000 /* non-aggregate fields */ #define CB_TCONV 0x400000 /* type conversion fn */ #define CB_CGEN 0x800000 /* (member) fn has compiler-generated */ /* components: ctor, dtor, operator= */ #define NON_CONFORMING 0x1000000 /* attribute but really to indicate a t_unknown type is conforming only to itself. */ #define DEDUCED 0x2000000 /* attribute but really to indicate the non-t_unknown type is deduced rather than by other means. */ #define A_LOCALSTORE (~0x7fffffff) #define A_GLOBALSTORE 0x40000000 /* * Binders describe variables and functions (named objects). * The code generator also introduces Binders for some anonymous abjects. * In C++ (CPLUSPLUS) they are also used for member bindings. * The intent is that this should only be exploited in code guarded by * CPLUSPLUS so that in C the two structs can differ. */ typedef struct SuperBinder SuperBinder; /* opaque here */ #define ClassMember Binder typedef ClassMember *ScopeSaver; struct Binder { AEop h0; /* needed as Binder is a subtype of Expr */ Binder *bindcdr; /* reverse chain of binders at this level */ Symstr *bindsym; /* pointer to Symstr (for name and restore) */ TypeExpr *bindtype; /* the object's type... but disappears */ /* for auto objects - cached in bindmcrep */ SET_BITMAP attributes; /* this scope entity's attributes... */ SET_BITMAP bindstg; /* flags describing sort of object - also */ /* used to discriminate unions and opts */ union { /* discriminated by bindstg & b_bindaddrlist */ /* BindVar choices: */ IPtr i; /* offset in stack/dataseg etc. or enumval */ BindList *bl; /* stack offset as BindList (auto only) */ Binder *realbinder; /* for instate_alias()... */ SuperBinder *super; /* for sub binders made by splitting */ /* live ranges. */ /* enumvals are represented as 'i' above. */ } bindaddr; struct TagBinder *bindparent; /* name of scope or NULL */ union { struct { Expr *bindconst; /* allows C++ "const x=8, A[x], *y=&x;" */ void *inlineinfo; #ifdef PASCAL /*ECN*/ unsigned8 bindlevel; unsigned16 synflags; #endif } bindvar; struct { #ifdef PASCAL /*ECN*/ int32 offset; struct VariantList *vlist; #else int32 offset; /* Sadly, not in bindaddr (anonus need */ /* a realbinder) */ unsigned8 bitfieldbits, bitfieldpos; #endif } bindmem; } var_or_mem; /* The following fields support the debugger toolbox */ #ifdef CALLABLE_COMPILER void *namedef, *dbgdata; #define namedef_(b) (*(Dbg_NameDef **)&((b)->namedef)) #define dbgdata_(b,t) (*(t **)&((b)->dbgdata)) #else IPtr binddbg; #endif ScopeSaver bindscope; /* set only if A_PRIMARY */ ExprList *bindactuals; /* set only in generic binder and temporarily */ ScopeSaver bindformals; /* set only if A_PRIMARY and in specialized binder */ BindList *bindinstances; /* set only if A_PRIMARY */ int bindtext; /* set only if A_PRIMARY */ BindList *fntmptlist; /* set only in generic binder */ /* Athough the following fields are logically part of BindVar, the code */ /* requires less changes by leaving them here. */ #define SIZEOF_NONAUTO_BINDER offsetof(Binder,bindxx) #define SIZEOF_CLASSMEMBER offsetof(Binder,bindxx) union { VRegnum i; void *p; } bindxx; /* this and following fields in s_auto Binders only */ int32 bindmcrep; /* in flux */ #define NOMCREPCACHE (-1L) }; /* If s_member (or b_member soon) then memtype_() can be ACCESSADJ... */ #define ACCESSADJ te_void /* flag for [ES, p245] */ #ifdef CPLUSPLUS #define is_datamember_(/*(ClassMember *)*/l) \ (h0_(l) == s_member && !(attributes_(l) & CB_ANON) \ && memtype_(l) != ACCESSADJ) #define is_datamemberoranon_(/*(ClassMember *)*/l) \ (h0_(l) == s_member && memtype_(l) != ACCESSADJ) #else #define is_datamember_(l) 1 #define is_datamemberoranon_(l) 1 #endif #define memcdr_(p) ((p)->bindcdr) #define memsv_(p) ((p)->bindsym) #define memtype_(p) ((p)->bindtype) #define membits_(p) ((p)->var_or_mem.bindmem.bitfieldbits) #define memwoff_(p) ((p)->var_or_mem.bindmem.offset) #define memboff_(p) ((p)->var_or_mem.bindmem.bitfieldpos) #define memvtablesize_(p) ((p)->bindaddr.i) #define OFFSET_UNSET (~0x7fffffffL) /* * Useful access functions... */ #define bindcdr_(p) ((p)->bindcdr) #define bindsym_(p) ((p)->bindsym) #define bindstg_(p) ((p)->bindstg) #define bindtype_(p) ((p)->bindtype) #define binduses_(p) ((p)->bindstg) /* n.b. */ #define bindaddr_(p) ((p)->bindaddr.i) #define bindenumval_(p) ((p)->bindaddr.i) #define bindbl_(p) ((p)->bindaddr.bl) #define realbinder_(p) ((p)->bindaddr.realbinder) #define bindconst_(p) ((p)->var_or_mem.bindvar.bindconst) #define bindinline_(p) ((p)->var_or_mem.bindvar.inlineinfo) #define bindparent_(p) ((p)->bindparent) #define bindsuper_(p) ((p)->bindaddr.super) #define bindxx_(p) ((p)->bindxx.i) #define bindxxp_(b) ((b)->bindxx.p) #define bindmcrep_(p) ((p)->bindmcrep) #define binddbg_(p) ((p)->binddbg) #define bindscope_(p) ((p)->bindscope) #define bindactuals_(p) ((p)->bindactuals) #define bindformals_(p) ((p)->bindformals) #define bindenv_(p) ((p)->bindformals) #define bindinstances_(p) ((p)->bindinstances) #define bindtext_(p) ((p)->bindtext) #define bindftlist_(p) ((p)->fntmptlist) /* * Flag bits in bindaddr */ #define BINDADDR_MASK (~0x0fffffffL) /* Use top-bit-set values to provide a little free union checking. */ /* The lower 28 bits give offset within class for local_address() */ /* (q.v.) which should only get to see BINDADDR_ARG or BINDADDR_LOC. */ #define BINDADDR_ARG (~0x7fffffffL) /* a formal parameter */ #define BINDADDR_LOC (~0x3fffffffL) /* a local variable */ /* The next case is currently only used if TARGET_STACK_MOVES_ONCE and */ /* is converted to BINDADDR_LOC by flowgraf.c (in flux Nov89). */ #define BINDADDR_NEWARG (~0x2fffffffL) /* an actual parameter */ #define BINDADDR_UNSET (~0x1fffffffL) /* aeops.h reserves the (lsb) bits satisfying isdeclstarter_() for */ /* bit maps of types and storage classes (C allows their intermixing). */ /* These now (Apr 93) never occupy the same word, so need not be */ /* disjoint. Sep 93: there are 17 type bits (occupying 0x1ffff) and */ /* 10 STGBITS (occupying 0x03ff0000) so the top 6 bits plus the lower */ /* STGBITS are available for the uses listed below */ /* After parsing, the type has the additional value 'BITFIELD'. The */ /* storage part is held in bindstg_ and shares with the binduses_ field */ /* of a Binder. The stg part can (and does) re-use the type part of the */ /* map below. */ #ifdef PASCAL /* No longer used in C/C++: */ #define b_synbit1 (~0x7fffffffL) /* reserved to parser */ #define b_synbit2 0x40000000L /* reserved to parser */ #define b_synbits (b_synbit1+b_synbit2) #endif #define b_generated (~0x7fffffffL) /* generated ctor/assignment.*/ #define b_impl 0x40000000L /* real_binder_() implements. */ #define b_pseudonym 0x20000000L /* for instate_alias */ #define b_dbgbit 0x10000000L /* reserved to debugger support */ /* N.B. none of the above 4 bits were used by instate_decl/member. */ /* (they are only tested via bindstg_(b) & b_xxx). */ /* So, pending rework, we have used the 0x70000000 bits for access */ /* specs (so to remove an arg to instate_member to allow instate_decl */ /* to be merged). Beware. AM Feb 93. */ /* @@@ HIGHLY DEPENDENT ON aeops.h! Rework soon. */ #define killstgacc_(m) ((m) & ~0x70000000) #define attribofstgacc_(m) \ ((((m) >> 28) & 7) << shiftoftype_(s_union+1)) #define stgaccof_(s) (1L << (s)-s_private+28) #define b_memfna 0x08000000L /* memfn (non-static) */ #define b_memfns 0x04000000L /* memfn (static) */ /* * bit selectors within binduses_ (now in bindstg_) additional to STGBITS * The bits in lowbit(STGBITS)-1 are available (Sep 93: this is 0xffff, * i.e. 16 bits. */ #define u_implicitdef 0x0001L #define u_referenced 0x0002L #define b_purevirtual 0x0004L #define u_bss 0x0008L #define u_constdata 0x0010L #define u_loctype (u_bss+u_constdata) #define u_superceded 0x0020L /* bit selectors logically within the sharing bindstg_: */ #define b_spilt 0x0040L /* not allocatable to registers, but */ /* not address taken (i.e. unaliased) */ #define b_addrof 0x0080L #define b_maybeinline 0x0100L /* for class member fns until definite */ #define b_enumconst 0x0200L #define b_implicitstg 0x0400L #define b_undef 0x0800L /* 'forward ref' static or extern */ #define b_fnconst 0x1000L #define b_bindaddrlist 0x2000L /* discriminator for bindstg */ #define b_noalias 0x4000L /* variable p is a pointer: *(p+x) (any x) is guaranteed to have no aliases not involving p */ #define b_clinkage 0x08000L /* c linkage */ #define b_globalregvar bitofstg_(s_globalreg) /* STGBITS 0x03ff0000L */ #define isenumconst_(b) (bindstg_(b) & b_enumconst) /* b_enumconst isn't wanted by the back-end (no binder in the jopcode */ /* stream can have it: any that did has been transformed to the */ /* appropriate constant). So we can share it for a property wanted only */ /* in the backend. */ #define b_unbound b_enumconst /* Bits additional to TYPEBITS, sharing with STGBITS: */ #define BITFIELD bitoftype_(s_lasttype+1) /* beware: a type not a stg bit */ typedef struct Friend Friend; #define friendcdr cdr struct Friend { Friend *friendcdr; union { TagBinder *friendclass; /* h0_() == s_tagbind */ Binder *friendfn; /* h0_() == s_binder */ } u; }; typedef BindList TagBindList; /* * The type TagBinder is used for struct name bindings and is similar * to Binder. BEWARE: the relationship with Binder may be depended upon. */ struct TagBinder { AEop h0; /* Must be the first field... */ TagBinder *bindcdr; /* reverse chain of binders at this level */ Symstr *bindsym; /* pointer to Symstr (for name and restore) */ TypeExpr *tagbindtype; /* pointer to parent type... */ SET_BITMAP attributes; /* common binder attributes */ SET_BITMAP tagbindbits; /* TagBinder-specific flags: */ /* discriminates struct, union, (enum?)... */ /* ...TB_UNDEFMSG, TB_BEINGDEFD, TB_DEFD. */ union { ClassMember *tagbindmems; /* list of struct/union members */ BindList *tagbindenums; /* list of enum members */ } m; Friend *friends; /* list of friends of the class... */ TagBinder *tagparent; /* parent class of class or 0. */ int32 cachedsize; /* Rearrange next 2-3 lines to end so need not always be allocated? */ TagBindList *taginstances; /* used if TB_TEMPLATE */ ScopeSaver tagscope; /* used if TB_TEMPLATE */ ScopeSaver tagformals; /* used if TB_TEMPLATE */ ScopeSaver tagactuals; /* used if TB_TEMPLATE */ int tagtext; /* used if TB_TEMPLATE */ TagBinder *tagprimary; IPtr *tagmemfns; /* used if TB_TEMPLATE */ #ifdef TARGET_HAS_DEBUGGER IPtr tagbinddbg; /* space reserved to debug-table writer */ #endif Symstr *typedefname; }; #define tagbindcdr_(p) ((p)->bindcdr) #define tagbindsym_(p) ((p)->bindsym) #define tagbindtype_(p) ((p)->tagbindtype) #define tagbindbits_(p) ((p)->tagbindbits) #define tagbindmems_(p) ((p)->m.tagbindmems) #define tagbindenums_(p) ((p)->m.tagbindenums) #define tagbindparent_(p) ((p)->tagparent) #define tagbinddbg_(p) ((p)->tagbinddbg) #define tagscope_(p) ((p)->tagscope) #define tagformals_(p) ((p)->tagformals) #define tagactuals_(p) ((p)->tagactuals) #define tagtext_(p) ((p)->tagtext) #define taginstances_(p) ((p)->taginstances) #define tagprimary_(p) ((p)->tagprimary) #define tagmemfns_(p) (*(IPtr **)&(p)->tagmemfns) /* Fields of tagbindbits... */ /* beware: bitoftype_(s_enum, s_struct, s_class, s_union) = 0x1c8 */ #define TB_UNALIGNED 1 #define TB_TEMPLATE 2 /* tagbinder is just a template. */ #define TB_TPARAM 4 /* tagbinder is just a template param. */ #define TB_SPECIALIZED 0x0010 /* tagbinder is an explicitly specialized template instance */ #define TB_ABSTRACT 0x0800 /* has >=1 pure virtual fn. */ #define TB_BEINGDEFD 0x1000 /* police "struct d { struct d { ..." */ #define TB_UNDEFMSG 0x2000 /* so 'size needed' msg appears once. */ #define TB_DEFD 0x4000 /* in C++ struct a;/struct a{} differ. */ #define TB_HASVTABLE 0x8000 /* has a virtual function table member. */ #define TB_CONTAINER 0x70000 /* enums only */ #define TB_CONTAINER_SHIFT 16 #define TB_CONTAINER_CHAR 0x00000 #define TB_CONTAINER_SHORT 0x10000 #define TB_CONTAINER_INT 0x20000 #define TB_CONTAINER_LONG 0x30000 #define TB_CONTAINER_UCHAR 0x40000 #define TB_CONTAINER_USHORT 0x50000 #define TB_CONTAINER_UINT 0x60000 #define TB_CONTAINER_ULONG 0x70000 #define TB_HASDTOR 0x00080000 /* has a dtor in its derivation... */ #define TB_HASCONSTCCTOR 0x00100000 /* generate T(T*, const T&) */ #define TB_HASCONSTOPEQ 0x00200000 /* generate op=(T*, const T&) */ #define TB_NEEDSCTOR 0x00400000 /* has a ctor in class */ #define TB_HASVBASE 0x00800000 /* has a vbase member */ #define TB_CORE 0x01000000 /* tagparent points to derivation */ #define TB_HASCMEM 0x02000000 /* has a const data member or its derivation*/ #define TB_SIZECACHED 0x04000000 #define TB_OPAQUE 0x08000000 /* data member access and sizeof not allowed*/ #define TB_NEEDSCCTOR 0x00000200 /* has a user-defined copy ctor in class or in its derivation */ #define TB_NEEDSOPEQ 0x00000400 /* has a user_defined op= in class or in its derivation */ /* POD def for pass by value purpose: no vfns, no user cctor, no vbases and all base/mems are bitwise cctor/op= OK. */ #define TB_NOTPODC_(tb) (tagbindbits_(tb) & (TB_NEEDSCCTOR|TB_NEEDSOPEQ)) #define TB_NOTPODU_(tb, a) (tagbindbits_(tb) & (TB_HASVTABLE|TB_HASVBASE|a)) #define TB_NOTPOD_(tb) (tagbindbits_(tb) & (TB_NEEDSOPEQ|TB_NEEDSCTOR|TB_NEEDSCCTOR)) #define isclasstagbinder_(tb) (tagbindbits_(tb) & \ (bitoftype_(s_struct)|bitoftype_(s_class)|bitoftype_(s_union))) #define isenumtagbinder_(tb) (tagbindbits_(tb) & bitoftype_(s_enum)) /* * FormTypeList is used in globalised types, and is a subtype of * DeclRhsList for both minimality and space reasons. */ typedef struct TentativeDefn TentativeDefn; #define declcdr cdr struct DeclRhsList { DeclRhsList *declcdr; Symstr *declname; TypeExpr *decltype; union { Expr *init; /* temp. for init (shares with declbits). */ Expr *bits; /* (members never have inits). */ IPtr stgval; /* for global register number */ } u; #ifdef PASCAL /*ECN*/ unsigned16 synflags; unsigned8 section; #endif SET_BITMAP declstg; FileLine fileline; /* added by RCC 25-Mar-88 */ Binder *declbind; /* temp. working space to help ->declinit */ Symstr *declrealname; /* declrealname set only for specialized template function name */ TentativeDefn *tentative; }; #define declbits_(d) ((d)->u.bits) #define declinit_(d) ((d)->u.init) #define declstgval_(d) ((d)->u.stgval) #define ftcdr cdr struct FormTypeList { FormTypeList *ftcdr; Symstr *ftname; TypeExpr *fttype; #ifdef PASCAL /*ECN*/ unsigned16 synflags; unsigned8 section; #endif Expr *ftdefault; /* C++ default args. */ }; /* * SynBindList and BindList are notionally identical, but AM wants * to separate concerns while re-arranging allocators. */ #define bindlistcdr cdr struct SynBindList { SynBindList *bindlistcdr; Binder *bindlistcar; /* AM: this code in flux: I want to moan about 'private' destructors */ /* at scope start, not scope end. Thus I make the destructor Expr */ /* when the Binder and ctor) is made. Dunno if this will persist. */ Expr *bindlistdtor; /* CPLUSPLUS only (else 0) */ }; #define mkSynBindList(a,b) ((SynBindList *)syn_list3(a,b,0)) #define freeSynBindList(p) ((SynBindList *)discard3((List *)p)) struct BindList { BindList *bindlistcdr; Binder *bindlistcar; }; #define mkBindList(a,b) ((BindList *)binder_cons2(a,b)) typedef struct BindListList BindListList; struct BindListList { BindListList *bllcdr; SynBindList *bllcar; }; typedef struct VfnList VfnList; #define vfcdr cdr struct VfnList { VfnList *vfcdr; Binder *vfmem; IPtr vfdelta; }; #define mkVfnList(a,b,c) ((VfnList *)syn_list3(a,b,c)) typedef struct TopDecl { /* a top-level decalration */ AEop h0; /* discriminator for union v_f... */ union { DeclRhsList *var; /* h0 == s_decl => variable */ struct { Binder *name; /* the function's name */ SynBindList *formals; /* its formal argument list... */ Cmd *body; /* its body... */ bool ellipsis; /* and whether the argument list ends '...' */ } fn; /* h0 = s_fndef => fn definition */ } v_f; } TopDecl; /* * ****** TEMPORARY HACK ****** * This structure should be private to the back-end. Making it so * requires splitting vargen into machine-specific and language-specific * parts. Also used by xxxobj.c and xxxasm.c * @@@ LDS: also used by bind.c for tentative definition stuff... but that * be improved by moving save/restore_vargen_state to vargen... */ typedef struct DataInit DataInit; #define datacdr cdr struct DataInit { DataInit *datacdr; IPtr rpt, sort, len, val; }; /* * To be used sparingly... */ #define h0_(p) ((p)->h0) typedef struct { /* Return values from structfield ... */ int32 woffset, /* offset (bytes) of current field (for bitfields, */ /* offset of word containing current field. */ boffset, /* bit offset of start of bitfield in word; or 0. */ bsize, /* bit size of field - 0 if not a bitfield. */ typesize; /* Byte size of field - 0 for bitfields. */ bool nopadding, padded; /* If padding occurred. */ /* Internal fields for structfield's use - caller of structfield should set them to zero before the first call for a structure. */ int32 n, bitoff; int32 sizeofcontainer, endofcontainer; } StructPos; #endif /* end of defs.h */
stardot/ncc
tests/1918.c
<reponame>stardot/ncc /* * ARM C compiler regression test $RCSfile$ * Copyright (C) 1997 Advanced Risc Machines Ltd. All rights reserved. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include "testutil.h" /********************* 1918 ***********************/ const int t0_1918[2]; const int t0_1918[] = { 1,2 }; /* no executable test */ /********************* ***********************/ int main(void) { BeginTest(); EQI(0,0); EndTest(); return 0; }
stardot/ncc
tests/fcmp.c
/* * ARM C compiler regression test $RCSfile$ * Copyright (C) 1995 Advanced Risc Machines Ltd. All rights reserved. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include "testutil.h" #include <stdio.h> #include <stdlib.h> #include <setjmp.h> #include <signal.h> typedef int bool; #define T 1 #define F 0 /********************* xxxx ***********************/ #include "testutili.h" float finf, fnan, fsnan, fone = 1.0; double dinf, dnan, dsnan, done = 1.0; jmp_buf jmpbuf; bool exception; #define set_jmp() (exception = 0, setjmp(jmpbuf)) void fpe_exception(int x) { if (exception != 0) { fprintf(stdout, "Uncaught FP execption\n"); test_fail(); EndTest(); abort(); } exception = 1; signal(SIGFPE, fpe_exception); longjmp(jmpbuf,1); } int test_cmpd(int lineno, double x, double y, char *cmp, bool res1, bool res2) { test_execute(); if (res1 == res2) { if (test_isverbose()) fprintf(stdout, "\"%s\", line %d: OK\n", test_name(), lineno); return 0; } test_fail(); fprintf(stdout, "\"%s\", line %d: %g %s %g failed\n", test_name(), lineno, x, cmp, y); return 1; } #define FCMP(a, b, cmp, r) test_cmpd(__LINE__, a, b, #cmp, (a cmp b), r) #define FCMPE(a, b, cmp, r, exec) if (set_jmp() == 0) test_cmpd(__LINE__, a, b, #cmp, (a cmp b), r); else EQI(exception, exec); void fcmp(float a, float b, bool eq, bool lt) { FCMP(a, b, ==, eq); FCMP(a, b, !=, !eq); FCMP(a, b, < , lt); FCMP(a, b, <=, lt | eq); FCMP(a, b, > , !lt & !eq); FCMP(a, b, >=, !lt | eq); } void fcmpnan(float *a, float *b, bool snan) { /* one of a or b is a NaN - use ptrs to avoid conversion */ FCMPE(*a, *b, ==, F, snan); FCMPE(*a, *b, !=, T, snan); FCMPE(*a, *b, < , F, T); FCMPE(*a, *b, <=, F, T); FCMPE(*a, *b, > , F, T); FCMPE(*a, *b, >=, F, T); } void dcmp(double a, double b, bool eq, bool lt) { FCMP(a, b, ==, eq); FCMP(a, b, !=, !eq); FCMP(a, b, < , lt); FCMP(a, b, <=, lt | eq); FCMP(a, b, > , !lt & !eq); FCMP(a, b, >=, !lt | eq); } void dcmpnan(double *a, double *b, bool snan) { /* one of a or b is a NaN */ FCMPE(*a, *b, ==, F, snan); FCMPE(*a, *b, !=, T, snan); FCMPE(*a, *b, < , F, T); FCMPE(*a, *b, <=, F, T); FCMPE(*a, *b, > , F, T); FCMPE(*a, *b, >=, F, T); } void t_cmp(void) { /* enable the IVO exception */ __fp_status(__fpsr_IOE, __fpsr_IOE); fcmp( 0.0, 0.0, T, F); fcmp(-0.0, 0.0, T, F); fcmp(-0.0, -0.0, T, F); fcmp( 0.0, -0.0, T, F); fcmp( 1.0, 1.0, T, F); fcmp(-1.0, 1.0, F, T); fcmp(-1.0, -1.0, T, F); fcmp( 1.0, -1.0, F, F); fcmp( 1.0, 2.0, F, T); fcmp(-1.0, 2.0, F, T); fcmp( 1.0, -2.0, F, F); fcmp(-1.0, -2.0, F, F); fcmp( finf, finf, T, F); fcmp(-finf, finf, F, T); fcmp( finf,-finf, F, F); fcmp(-finf,-finf, T, F); dcmp( 0.0, 0.0, T, F); dcmp(-0.0, 0.0, T, F); dcmp(-0.0, -0.0, T, F); dcmp( 0.0, -0.0, T, F); dcmp( 1.0, 1.0, T, F); dcmp(-1.0, 1.0, F, T); dcmp(-1.0, -1.0, T, F); dcmp( 1.0, -1.0, F, F); dcmp( 1.0, 2.0, F, T); dcmp(-1.0, 2.0, F, T); dcmp( 1.0, -2.0, F, F); dcmp(-1.0, -2.0, F, F); dcmp( dinf, dinf, T, F); dcmp(-dinf, dinf, F, T); dcmp( dinf,-dinf, F, F); dcmp(-dinf,-dinf, T, F); dcmp( 1.0000000001, 1.0, F, F); dcmp( 1.0000000001, -1.0, F, F); dcmp(-1.0000000001, 1.0, F, T); dcmp(-1.0000000001, -1.0, F, T); dcmp( 0.9999999999, 1.0, F, T); dcmp( 0.9999999999, -1.0, F, F); dcmp(-0.9999999999, 1.0, F, T); dcmp(-0.9999999999, -1.0, F, F); fcmpnan(&fnan, &finf, F); fcmpnan(&fnan, &fone, F); fcmpnan(&finf, &fnan, F); fcmpnan(&fone, &fnan, F); fcmpnan(&finf, &fsnan,T); fcmpnan(&fsnan, &fnan,T); fcmpnan(&fone, &fsnan,T); fcmpnan(&fsnan, &finf,T); dcmpnan(&dnan, &dinf, F); dcmpnan(&dnan, &done, F); dcmpnan(&dinf, &dnan, F); dcmpnan(&done, &dnan, F); dcmpnan(&dinf, &dsnan, T); dcmpnan(&dsnan, &dnan, T); dcmpnan(&done, &dsnan, T); dcmpnan(&dsnan, &dnan, T); __fp_status(__fpsr_IOE, 0); /* IVO disabled -> signalling NaNs behave like normal NaNs */ fcmpnan(&finf, &fsnan,T); fcmpnan(&fsnan, &fnan,T); fcmpnan(&fone, &fsnan,T); fcmpnan(&fsnan, &finf,T); dcmpnan(&dinf, &dsnan, T); dcmpnan(&dsnan, &dnan, T); dcmpnan(&done, &dsnan, T); dcmpnan(&dsnan, &dnan, T); __fp_status(__fpsr_IOE, __fpsr_IOE); } void t_init(void) { int *p; p = (int*) &finf; p[0] = 0x7F800000; p = (int*) &fnan; p[0] = 0x7FC00000; p = (int*) &fsnan; p[0] = 0x7F800001; p = (int*) &dinf; p[0] = 0x7FF00000; p[1] = 0; p = (int*) &dnan; p[0] = 0x7FF80000; p[1] = 1; p = (int*) &dsnan; p[0] = 0x7FF00000; p[1] = 1; /* tricky NaN - high word looks like an infinite */ signal(SIGFPE, fpe_exception); } /********************* main ***********************/ int main(void) { BeginTest(); t_init(); t_cmp(); EndTest(); return 0; }
stardot/ncc
tests/inlnarm.c
<reponame>stardot/ncc /* * ARM C compiler inline assembler test $RCSfile$ * Copyright (C) 1997 Advanced Risc Machines Ltd. All rights reserved. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include "testutil.h" #include <stdlib.h> #include <string.h> int t0(int a, int b, int c) { /* Quoted assembler construct can only be used in C++ as a declaration, the assembler block can be used as a command. */ __asm("ADD a, b, c ; ADD b, a, c"); if (a) __asm { ADD a, b, c } else __asm { ADD a, a, 1 } #ifdef __cplusplus asm(" ADD a, a, 1 "); asm { ADD a, a, 2 }; #endif return a + b + c; } int t1(int a, int b, int c) { /* Data processing */ __asm { MOV r0, a MOV r1, b MOV r2, c /* none of the instructions below may be removed */ AND r0, r1, r2 EOR r1, r0, r2 SUB r2, r1, r0 RSB r0, r1, r2 ADDS r1, r0, r2 ADCS r2, r0, r1 SBCS r0, r1, r2 RSC r1, r0, r2 TST r0, r1 TEQ r0, r1 CMP r0, r1 CMN r0, r1 ORR r2, r0, r1 MOV r0, r1 BIC r1, r0, r2 MVN r0, r2 /* until here */ ADD a, r0, r1, ROR r2 } return a; } void t2(int a, int *b, int *c) { /* Load/store instructions */ __asm { LDR a, [b] ADD a, a, #1 STR a, [b] LDR a, [b, #4] ADD a, a, #1 STR a, [b, #4] LDRT a, [c], #4 /* no preindex possible */ ADD a, a, #1 STRBT a, [c] LDRB a, [b, #8] ADD a, a, #1 STRB a, [b, #9] #ifdef __TARGET_FEATURE_HALFWORD LDRSB a, [b] STRH a, [b, #12] LDRSH a, [b] STR a, [b, #16] LDRH a, [b] STR a, [b, #20] #endif LDMIA b!, {r0 - r2} ADD b, b, #12 STMIA b!, {r0 - r2} MOV a, #-1 STR a, [b] LDR a, [b, #-9*4] SWP c, a, [b] SWPB a, c, [b] } } int t3(int a, int b) { /* multiply */ int c, d; __asm { MUL c, a, b MLA c, b, a, c #ifdef x__TARGET_FEATURE_MULTIPLY UMULL a, d, a, b SMLAL a, b, c, d #else MOV d, #0 #endif } return a + b + c + d; } void t4(int a, int b) { /* not runnable - parsing only */ /* MRS/TEQP/condition codes */ __asm { MRS a, CPSR MRS b, SPSR MSR SPSR_all, b /* equals SPSR_cf */ MSR CPSR_f, #15 MSR SPSR_ctl, b MSR SPSR_sc, a MSR CPSR_cx, b MSR SPSR, a MSR SPSR_fsxc, b /* only for 26 bit compatibility */ TEQP a, b CMPP a, b TEQP a, #1 TSTP a, #1 << 24 CMPP b, #1 CMNP a, #1 CMP a, b /* mark PSR as live */ ADDEQ a, a, b ADDNE a, a, b ADDCS a, a, b ; ADDHS a, a, b /* synomyms */ ADDCC a, a, b ; ADDLO a, a, b /* synomyms */ ADDMI a, a, b ADDPL a, a, b ADDVS a, a, b ADDVC a, a, b ADDHI a, a, b ADDLS a, a, b ADDGE a, a, b ADDLT a, a, b ADDGT a, a, b ADDLE a, a, b ADDAL a, a, b ; ADD a, a, b /* synomyms */ /* NOTE: NV not supported */ ADDS a, a, b SUBNE b, b, a RSBEQ a, a, b #if defined(__TARGET_FEATURE_HALFWORD) && defined(__TARGET_FEATURE_MULTIPLY) MULVSS a, a, b MLAMIS a, b, b, a SMULLGTS a, b, a, b UMLALNES a, b, b, a LDRLEBT a, [b] LDRVSSH a, [b, #4] #endif SWPALB a, b, [a] NOP SWI 100 BL t3, {}, {}, {} } } void t5(char *a, char *b, int n) { /* labels & branches */ int ch; char *end; __asm { ADD end, a, n loop: LDRB ch, [a], #1 CMP a, end STRB ch, [b], #1 CMPNE ch, #0 BNE loop } } #define ROR(x,y) (((unsigned)(x)>>(y))|((x)<<(32-(y)))) void t6(int x, int y) { /* shifts */ int a, b, c, d; a = x; b = y; c = x; d = y; __asm { MOV a, a, LSL #0 /* no shift */ MOV b, b, ASL #2 /* synonym of LSL */ MOV c, c, LSL #31 } EQI(a, x); EQI(b, y << 2); EQI(c, x << 31); a = x; b = y; c = x; d = y; __asm { MOV a, a, LSR #0 /* no shift */ MOV b, b, LSR #1 MOVS c, c, LSR #32 /* preserve LSR #32 */ ADDCS c, c, #1 MOV d, d, LSR #32 /* might translate to MOV a, #0 */ } EQI(a, x); EQI(b, (unsigned) y >> 1); EQI(c, x & (1U << 31) ? 1 : 0); EQI(d, 0); a = x; b = y; c = x; d = y; __asm { MOV a, a, ASR #0 /* no shift */ MOV b, b, ASR #1 MOVS c, c, ASR #32 /* preserve ASR #32 */ ADDCS c, c, #2 MOV d, d, ASR #32 /* preserve ASR #32 */ } EQI(a, x); EQI(b, y >> 1); EQI(c, (x < 0) ? -1+2 : 0); EQI(d, (y < 0) ? -1 : 0); a = x; b = y; c = x; d = y; __asm { MOV a, a, ROR #0 /* no shift */ MOV b, b, ROR #1 MOV c, c, ROR #31 CMP d, #1 /* set carry if (us)d >= 1 */ MOV d, d, RRX } EQI(a, x); EQI(b, ROR(y,1)); EQI(c, ROR(x,31)); EQI(d, (d != 0 ? (1U << 31) : 0) + ((unsigned) y >> 1)); a = x; b = y; c = x; d = y; __asm { MOV a, a, LSL a MOV b, b, LSR b MOV c, c, ASR c MOV d, d, ROR d } EQI(a, (x & 255 >= 32) ? 0 : x << x); EQI(b, (y & 255 >= 32) ? 0 : (unsigned) y >> y); EQI(c, (x & 255 >= 32) ? (x < 0 ? -1 : 0) : x >> x); EQI(d, ROR(y, y&31)); } void test(void) { int arr[10] = { 0x81818181, 0x22334455, 0xffffffff, 0, 0xffffffff, 0 }; char str1[20] = "Inline assembler..."; char str2[20] = " "; #ifdef __cplusplus EQI(t0(1, 2, 3), 25); #else EQI(t0(1, 2, 3), 22); #endif EQI(t1(0x11223344, 0x55667788, 0x99aabbcc), 0xAC004458); EQI(t1(0xFFEEDDCC, 0xBBAA9988, 0x77665544), 0x8841EEBB); t2(0, arr, arr+1); #ifndef __BIG_ENDIAN EQI(arr[0], 0x81818182); EQI(arr[1], 0x22334456); EQI(arr[2], 0xffff5857); #ifdef __TARGET_FEATURE_HALFWORD EQI(arr[3], 0x0000ff82); EQI(arr[4], 0xffff8182); EQI(arr[5], 0x00008182); #endif EQI(arr[6], arr[0]); EQI(arr[7], arr[1]); EQI(arr[8], arr[2]); EQI(arr[9], arr[0] | 0xff); #endif #ifdef x__TARGET_FEATURE_MULTIPLY EQI(t3(0x11223344, 0x55667788), 0x164B7F0D); EQI(t3(0xffeeddcc, 0xbbaa9988), 0x86ECEA9F); #else EQI(t3(0xffeeddcc, 0xbbaa9988), 0xC972F814); EQI(t3(0x11223344, 0x55667788), 0x68B85B0C); #endif /* t4 not runnable */ t5(str1, str2, 16); EQI(0, strcmp(str2, "Inline assembler ")); t6(-1, -2); t6(100, 1000); t6(0,0); t6(0xFEDCBA98, 0x76543210); t6(0x76543210, 0xFEDCBA98); } /******************* test *************************/ typedef unsigned int uint; unsigned char bitrev_tab[256]; uint bitrev_1(uint n) { char *tab; uint res, t; __asm { MOV tab, bitrev_tab LDRB res, [tab, n, LSR #24] MOV n, n, LSL #8 LDRB t, [tab, n, LSR #24] MOV n, n, LSL #8 ORR res, res, t, LSL #8 LDRB t, [tab, n, LSR #24] MOV n, n, LSL #8 LDRB n, [tab, n, LSR #24] ORR res, res, t, LSL #16 ORR res, res, n, LSL #24 } return res; } uint bitrev_2(uint n) { uint c0, c1, c2, t; __asm { MOV c2, #0x0F0F0F0F EOR c1, c2, c2, LSL #2 // 0x33333333 EOR c0, c1, c1, LSL #1 // 0x55555555 AND t, c0, n AND n, c0, n, LSR #1 ORR n, n, t, LSL #1 AND t, c1, n AND n, c1, n, LSR #2 ORR n, n, t, LSL #2 AND t, c2, n AND n, c2, n, LSR #4 ORR n, n, t, LSL #4 MOV t, n, LSR #8 // DCBA BIC t, t, #255 << 8 // 0D0B EOR n, t, n, ROR #8 // A0C0 ORR n, n, t, ROR #16 // ABCD } return n; } uint bitreverse(uint n) { uint res = 0, i; for (i = 32; i > 0; i--) { res = (res << 1) | (n & 1); n >>= 1; } return res; } void bitreverse_test(void) { int i; for (i = 0; i < 256; i++) bitrev_tab[i] = bitreverse(i) >> 24; for (i = 0; i < 1000; i++) { uint r = rand(); uint r1 = bitrev_1(r); uint r2 = bitrev_2(r); uint r3 = bitreverse(r); EQI(r1, r3); EQI(r2, r3); } } /**************************************************/ __inline int mul48(int a, int b) { int tmp, res; __asm { BIC a, a, #255 << 24 BIC b, b, #255 << 24 AND tmp, b, #255 MUL res, a, tmp MOV tmp, b, LSR #8 AND tmp, tmp, #255 TST res, #255 MOV res, res, LSR #8 MLA res, a, tmp, res MOV tmp, b, LSR #16 TSTEQ res, #255 MOV res, res, LSR #8 MLA res, a, tmp, res // 24 bit result in bit 8..31 of res, bit 7 = round bit ORRNE res, res, #1 // bit 0..5 are the sticky bits, bit 6 = guard bit } return res; } int fmul(int a, int b) { int mask, expa, expb, exp, tmp, res; __asm { MOV mask, #255 << 16 // first check for denorms, infinites and NaNs ANDS expa, mask, a, LSR #7 ANDNES expb, mask, b, LSR #7 CMPNE expa, #255 << 16 CMPNE expb, #255 << 16 BEQ fmul_uncommon TEQ a, b ADDMI exp, exp, #1 << 8 // insert result sign into exponent ORR a, a, #1 << 23 // do the 24*24 -> 48 bit multiply ORR b, b, #1 << 23 ADD exp, expa, expb SUB exp, exp, #128 << 16 // subtract bias+1 - 0..253 normal (anti-interlock) MOV res, mul48(a, b) CMP exp, #252 << 16 // 0..251 can never overflow BHS fmul_check_overflow fmul_round: MOVS a, res, LSL #1 // CS -> high bit set MOVCC res, res, LSL #1 // CC : shift 1 left - sets bit 23 ADC exp, exp, exp, LSR #16 // recombine sign and exponent MOVS a, res, LSR #8 // CS -> round TSTCS res, #127 // EQ -> round to even ADC a, a, exp, LSL #23 // add fraction, and round BICEQ a, a, #1 // round to even } return a; __asm { fmul_check_overflow: BMI fmul_underflow // was really underflow MOV tmp, exp, LSR #16 // test whether there is overflow TST res, #1 << 31 ADDNE tmp, tmp, #1 CMP tmp, #253 CMPEQ res, #0xFFFFFF80 // rounding overflow possible? BLO fmul_round // will not overflow after all fmul_overflow: // exception handling not yet implemented... AND a, a, #1 << 31 // create signed infinite ORR a, a, #255 << 23 } return a; __asm { fmul_underflow: // underflow -> denormalise (not implemented) MOV expa, #0 MOV res, #0 B fmul_round fmul_uncommon: // a or b denorm/NaN/inf AND expb, mask, b, LSR #7 CMP expa, #255 << 16 CMPNE expb, #255 << 16 BEQ fmul_uncommon1 // a or b NaN/inf // denorms not implemented - act as if it was a zero EOR a, a, b AND a, a, #1 << 31 } return a; __asm { fmul_uncommon1: CMP expb, #255 << 16 MOVEQ a, b } return a; } typedef union { int i; float f; } intfloat; void fmul_test(void) { intfloat a, b, c, d; int i; a.f = 1.00001; b.f = 0.99999; c = a; for (i = 0; i < 10000; i++) c.i = fmul(c.i, b.i); d = a; for (i = 0; i < 10000; i++) d.f = d.f * b.f; EQI(1, c.i == d.i); /* results should be bit identical */ } /******************* fail *************************/ /* ldm peepholer should not combine assembler LDRs? */ void f_0(void) { int arr[2] = { 0x11223344, 0 }; char *p = (char*)(&arr[0]) + 2; int t0, t1; __asm { LDR r0, [p, #0] /* unaligned access - rotate */ LDR r1, [p, #4] EOR t0, r0, r1 LDMIA p, {r0, r1} EOR t1, r0, r1 } EQI(t0, 0x33441122); EQI(t1, 0x11223344); } /* register allocator does not handle dead physical registers correctly - p is allocated to r1... */ void f_1(void) { int arr[4] = { 1, 2 }; int *p = arr; __asm { LDMIA p!, {r0 - r1} STMDB p, {r0} } EQI(arr[0], 1); EQI(arr[1], 1); } /**************************************************/ int main () { BeginTest(); test(); bitreverse_test(); fmul_test(); f_0(); f_1(); EndTest(); return 0; }
stardot/ncc
mip/compiler.c
/* * C compiler file compiler.c * Copyright (C) Codemist Ltd., 1987-1992. * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Advanced RISC Machines Limited, 1990-1992. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 147 * Checkin $Date$ * Revising $Author$ */ /* AM Mar 89: start 'ccom-like' interface. I allow the compiler to produce */ /* both object and asm output (after all unix ccom cannot never allow */ /* obj output!). Fix up FLG_STDIN to allow 0 args. Add '-' for stdin/out */ /* Move compile_abort to here from misc.c -- move out to driver.c? */ #include <stddef.h> #include <time.h> #ifdef __STDC__ # include <stdlib.h> # include <string.h> #else # include <strings.h> #endif #include <ctype.h> #ifndef COMPILING_ON_MSDOS # include <signal.h> #endif #include "globals.h" #include "compiler.h" #include "fname.h" #include "pp.h" #include "lex.h" #include "syn.h" #include "sem.h" /* init */ #include "bind.h" /* init */ #include "builtin.h" /* init */ #include "vargen.h" /* initstaticvar */ #include "aetree.h" #include "cg.h" #include "mcdep.h" #include "aeops.h" #include "xrefs.h" #include "store.h" #include "version.h" /* for CC_BANNER */ #include "errors.h" #include "dump.h" #if defined(FOR_ACORN) && defined(COMPILING_ON_RISCOS) #include "dde.h" #endif #include "filestat.h" #include "trackfil.h" #ifndef COMPILING_ON_MVS # define BSD_LIKE_SEARCH 1 /* ansi trying to ban (like sysV/K&R) */ #endif #ifdef ENABLE_MAPSTORE extern void _mapstore(void); #endif #define MAX_NAME 256 /* The longest file name I'm prepared to handle */ #define ccom_alloc(n) GlobAlloc(SU_Other, n) #define INSTORE_FILE 2 /* used in PathElement.flags */ #define PE_USER 4 /* used in PathElement.flags */ #define PE_SYS 8 /* used in PathElement.flags */ typedef struct PathElement { struct PathElement *link; /* sometimes a stack; sometimes a queue */ int flags; char name[2]; /* to allow for a trailing separator and a NUL */ } PathElement; /* <NAME> - added to link Callable compiler */ #ifdef CALLABLE_COMPILER void mcdep_set_options(ToolEnv *t) { } Uint TE_Integer(ToolEnv *t, char const *name, Uint def) { return def; } int Tool_OrderedEnvEnumerate( ToolEnv *t, char const *prefix, ToolEdit_EnumFn *f, void *arg) { return 0; } Uint TE_Count(ToolEnv *t, char const *prefix) { return 0; } #endif /* COMPILE CALLABLE_COMPILER */ /* AM/LDS: beware: the stack path_hd is assumed always to be non-empty, and */ /* the first element is treated very specially (in BSD). Maybe it should be */ /* a separate variable. */ static PathElement *path_hd, *path_tl, *path_sav; /* @@@ AM: I would prefer to use listingfile = NULL/string instead of */ /* FLG_LISTING etc. */ #define FLG_COMPILE 1 /* various ccom_flags */ #define FLG_MAKEFILE 4 #define FLG_PREPROCESS 8 #define FLG_NO_OBJECT_OUTPUT 16 #define FLG_INSTORE_FILES_IMPLICITLY 32 #define FLG_COUNTS 128 #define FLG_USE_SYSTEM_PATH 256 #define FLG_NOSYSINCLUDES 512 #define TEXT_FILE 0 #define BINARY_OUTPUT 1 #define TEXT_FILE_APPEND 2 /* for Acorn RISC OS DDE */ #define BINARY_INPUT 3 static int ccom_flags; time_t tmuse_front, tmuse_back; bool host_lsbytefirst; int files_debugcount; #define FILES_DEBUG_LEVEL(i) (debugging(DEBUG_FILES) && (i) < files_debugcount) #ifdef MIN_ALIGNMENT_CONFIGURABLE int32 alignof_struct_val; int32 alignof_toplevel_static_var; #endif int bss_threshold; bool disallow_tentative_statics = NO; /* * Define the following as global, for various debugger back-ends. */ char const *sourcefile; char const *objectfile, *sourcemodule; static const char *asmfile, *listingfile, *makefile; /* system_flavour copes with enabling this compiler to rename synbols */ /* to reflect libraries. E.g. on BSD sprintf must be renamed to refer */ /* to a different symbol from on ANSI (as their results differ). */ static char const *system_flavour; static FILE *makestream; #ifndef NO_DUMP_STATE static char const *compiledheader; static FILE *dumpstream; #endif #ifdef COMPILING_ON_RISC_OS #ifdef FOR_ACORN static int makeflg = 0; #endif #include "riscos.h" static void set_time_stamp(const char *file, bool good) { __riscos_osfile_block b; b.load = 0; /* OS_File(2, ...) sets the load address (type & ms part of time stamp) */ /* OS_File(9, ...) sets the type to &FFD and the time stamp to now. */ __riscos_osfile((good ? 9 : 2), file, &b); } #endif /* DEPEND_FORMAT used to output dependency line (-m option) */ #ifdef COMPILING_ON_MACINTOSH # define DEPEND_FORMAT "%s\304\t%s\n" #else # define DEPEND_FORMAT "%s:\t%s\n" #endif /* * Abort compilation if major fault found. */ extern void driver_abort(char *message) { cc_msg_lookup(driver_abort_msg, message); dbg_finalise(); compiler_exit(EXIT_error); } static FILE *cc_open(const char *s, int mode) { FILE *f; if (*s == 0 || StrEq(s, "-")) f = (mode == BINARY_INPUT) ? (s = "binary stdin", (FILE *)0) : (mode == BINARY_OUTPUT) ? (s = "binary stdout", (FILE *)0) : stdout; else f = fopen(s, (mode == BINARY_INPUT) ? FOPEN_RB : (mode == BINARY_OUTPUT) ? FOPEN_WB : (mode == TEXT_FILE_APPEND) ? "a" : "w"); if (f == NULL) { char msg[MAX_NAME]; msg_sprintf(msg, (mode == BINARY_INPUT) ? driver_couldnt_read : driver_couldnt_write, s); driver_abort(msg); } return f; } static void cc_close(FILE **fp, const char *file) { /* Be careful so that the following test always closes f when needed */ /* but tests ferror before the close. (There may be an I/O error, and */ /* the file still be closeable in which case it must be closed! */ /* Consider a floppy disc running out of space.) */ FILE *f = *fp; int err; *fp = NULL; if (f != NULL && f != stdout && (err = ferror(f), fclose(f) || err)) cc_fatalerr(compiler_fatalerr_io_error, file); } extern void compile_abort(int sig_no) { /* pre-conditions: initialisation done, closing not done. Call from */ /* SIGINT handler at your peril! */ #ifndef COMPILING_ON_MSDOS (void) signal(SIGINT, SIG_IGN); #endif #ifndef NO_ASSEMBLER_OUTPUT if (asmstream) { cc_close(&asmstream, asmfile); # ifndef COMPILING_ON_MVS if (asmfile != NULL) remove(asmfile); # endif } #endif #ifndef NO_LISTING_OUTPUT cc_close(&listingstream, listingfile); #endif #ifndef NO_OBJECT_OUTPUT if (objstream) { cc_close(&objstream, objectfile); # ifndef COMPILING_ON_MVS remove(objectfile); # endif } #endif if (makestream != NULL) { cc_close(&makestream, makefile); if (makefile != NULL) remove(makefile); } #ifndef NO_DUMP_STATE if (dumpstream != NULL) { cc_close(&dumpstream, compiledheader); remove(compiledheader); } #endif dbg_finalise(); compiler_exit(sig_no == (-1) ? EXIT_fatal : EXIT_syserr); } #if 'A' == 193 /* HOST_USES_EBCDIC... */ extern char _etoa[]; # define ASCII(x) (_etoa[x]) #else # define ASCII(x) (x) #endif /* * Disable warning messages. */ static int32 const warning_flags[] = { /*abcd*/ D_ASSIGNTEST, 0, D_CFRONTCALLER, D_DEPRECATED, /*efgh*/ 0, D_IMPLICITFNS, D_GUARDEDINCLUDE, 0, /*ijkl*/ D_IMPLICITCTOR,0, 0, D_LOWERINWIDER, /*mnop*/ D_MULTICHAR, D_LOWERINWIDER|D_IMPLICITNARROWING, D_LONGLONGCONST, D_PPNOSYSINCLUDECHECK, /*qrst*/ 0, D_IMPLICITVIRTUAL, D_STRUCTPADDING,D_UNUSEDTHIS, /*uvwx*/ D_FUTURE, D_IMPLICITVOID, 0, 0, /*yz */ 0, D_STRUCTASSIGN }; static int32 const feature_flags[] = { /*abc*/ FEATURE_ANOMALY, FEATURE_VERBOSE, FEATURE_LIMITED_PCC, /*def*/ 0, /* -fd */ FEATURE_6CHARMONOCASE, 0L-FEATURE_SAVENAME, /*ghi*/ 0, /* UNUSED */ FEATURE_PREDECLARE, FEATURE_USERINCLUDE_LISTING, /*jkl*/ FEATURE_SYSINCLUDE_LISTING, FEATURE_KANDR_INCLUDE, FEATURE_DONTUSE_LINKREG, /*mno*/ FEATURE_PPNOUSE, FEATURE_SAVENAME, FEATURE_WARNOLDFNS, /*pqr*/ FEATURE_TELL_PTRINT, FEATURE_ALLOWCOUNTEDSTRINGS, FEATURE_LET_LONGJMP_CORRUPT_REGVARS, /*stu*/ FEATURE_ANNOTATE, FEATURE_REVERSE_BITFIELDS, FEATURE_UNEXPANDED_LISTING, /*vwx*/ FEATURE_NOUSE, FEATURE_WR_STR_LITS, 0, /* -fx */ /*yz */ FEATURE_ENUMS_ALWAYS_INT, FEATURE_INLINE_CALL_KILLS_LINKREG }; static int32 ClearOrSet(int32 val, int32 bits, bool clear) { if (clear) return val & ~bits; else return val | bits; } static int SetFeatures(void *arg, char const *name, char const *val) { size_t len; IGNORE(arg); if (StrEq(name, ".-Isearch")) name = ".fk"; else if (StrEq(name, ".rolits")) name = ".fw"; else if (StrEq(name, ".enums")) name = ".fy"; else if (StrEq(name, ".swilr")) name = ".fz"; len = strlen(name); if (len == 3 && name[0] == '.') { int ch = name[2]; bool on = val[3] == '+'; if (name[1] == 'W') { if (ch == 'd') var_warn_deprecated = on; else if (ch == 'f') var_warn_implicit_fns = on; else suppress = ClearOrSet(suppress, warning_flags[ASCII(ch) - ASCII('a')], on); } #ifdef DISABLE_ERRORS else if (name[1] == 'E') { int32 new_suppress = 0, new_feature = 0; switch (ch) { case 'c': new_suppress = D_IMPLICITCAST; break; case 'm': new_suppress = D_MPWCOMPATIBLE | D_PPALLOWJUNK | D_ZEROARRAY | D_PPNOSYSINCLUDECHECK | D_MULTICHAR; new_feature = FEATURE_ALLOWCOUNTEDSTRINGS; break; case 'p': new_suppress = D_PPALLOWJUNK; break; #ifdef EXTENSION_VALOF case 'v': new_suppress = D_VALOFBLOCKS; break; #endif case 'z': new_suppress = D_ZEROARRAY; break; case 'f': new_suppress = D_CAST; break; /* Force casts */ case 'l': new_suppress = D_LINKAGE; break; case 'a': new_suppress = D_ACCESS; break; case 'i': new_suppress = D_IMPLICITINT; break; } suppress = ClearOrSet(suppress, new_suppress, on); feature = ClearOrSet(feature, new_feature, on); } #endif else if (name[1] == 'f') { if (ch == 'x') suppress &= ~D_SUPPRESSED; else if (ch == 'd') { ccom_flags = ccom_flags | FLG_USE_SYSTEM_PATH; } else { int32 flag = feature_flags[ASCII(ch) - ASCII('a')]; if (flag < 0) feature = ClearOrSet(feature, -flag, !on); else feature = ClearOrSet(feature, flag, on); } } #ifdef PASCAL else if (name[1] == 'r') /* Disable run time checks */ switch (ch) { case 'A': rtcheck |= RTCHECK_ARRAY; break; case 'C': rtcheck |= RTCHECK_CASE; break; case 'N': rtcheck |= RTCHECK_NIL; break; case 'R': rtcheck |= RTCHECK_REFERENCE; break; case 'P': rtcheck |= RTCHECK_ASSERT; break; case 'D': rtcheck |= RTCHECK_DEADCODE; break; } } #endif } return 0; } static int DoPredefine(void *arg, char const *name, char const *val) { IGNORE(arg); if (name[0] == '-') { if (name[1] == 'D') { size_t nlen = strlen(&name[2]), vlen = strlen(&val[1]); char *s = (char *)GlobAlloc(SU_PP, nlen+vlen+1); memcpy(s, &name[2], nlen); memcpy(&s[nlen], &val[1], vlen+1); pp_predefine(s); } else if (name[1] == 'z' && name[2] == 'p') { int pragmachar = safe_tolower(name[3]); int32 value = -1L; if (isdigit(val[1])) { value = strtol(&val[1], NULL, 0); /* allow 0x... form too */ #ifdef FORTRAN if ((pragmachar == 'x' || pragmachar == 'w') && pp_pragmavec[pragmachar-'a'] != -1) { pp_pragmavec[pragmachar-'a'] |= value; return; } #endif } pp_pragmavec[pragmachar-'a'] = value; } } return 0; } /* * Enable the features for PCC style compilation. */ static int32 pcc_features(void) { return FEATURE_PCC | FEATURE_UNIX_STYLE_LONGJMP; } static void translate_fname(const char *file, UnparsedName *un, char *new_file) { fname_parse(file, FNAME_INCLUDE_SUFFIXES, un); fname_unparse(un, FNAME_AS_NAME, new_file, MAX_NAME); } static void translate_path(const char *path, UnparsedName *un, char *new_path) { fname_parse(path, FNAME_INCLUDE_SUFFIXES, un); fname_unparse(un, FNAME_AS_PATH, new_path, MAX_NAME); #if defined(FOR_ACORN) && defined(COMPILING_ON_RISC_OS) /* DDE fix for paths like foo: ... */ if (un->un_pathlen > 1 && new_path[un->un_pathlen-2] == ':') new_path[un->un_pathlen-1] = 0; /* kill trailing separator */ #endif } static PathElement *mk_path_element(PathElement *link, int flags, char *name) { PathElement *p; if (FILES_DEBUG_LEVEL(1)) cc_msg("mk_path_element(%s)\n", name); p = (PathElement *) ccom_alloc((int32)strlen(name) + sizeof(PathElement)); p->link = link; p->flags = flags; strcpy(p->name, name); return p; } /* * Set the user/sys include path (no difference for bsd!). */ static void set_include_path(const char *path, int flags) { PathElement *p; UnparsedName unparse; int ch; char new_path[MAX_NAME]; char path_element[MAX_NAME]; for (ch = *path; ch != 0;) { /* one or more path elements joined by commas... */ int length = 0; while (ch != ',' && ch != 0) { if (length < (MAX_NAME-1)) path_element[length++] = ch; ch = *(++path); } if (ch == ',') ch = *(++path); path_element[length] = 0; if (length == 1 && path_element[0] == '-' /* unix-like 'std place' */ #ifdef COMPILING_ON_ACORN_KIT /* backwards compatibility -- RISCOS only soon? */ || StrEq(path_element, ":mem") || StrEq(path_element, ":MEM") #endif ) { flags |= INSTORE_FILE; length = 0; ccom_flags &= ~FLG_INSTORE_FILES_IMPLICITLY; new_path[0] = 0; } else { translate_path(path_element, &unparse, new_path); dbg_notepath(new_path); } /* Add a new path element at the END of the list. */ p = mk_path_element(NULL, flags, new_path); if (path_hd == NULL) path_tl = path_hd = p; else path_tl = (path_tl->link = p); } } static int AddInclude(void *arg, char const *name, char const *value, bool readonly) { IGNORE(arg); IGNORE(readonly); set_include_path(&value[1], name[1] == 'I' ? PE_USER : PE_SYS); return 0; } /* * Stack include path name. */ static char *push_include(char const *path, const char *name) { /* Return a copy of the native (translated) file-name. Do this so ASD */ /* will have a file-name it can use directly for its 'type' command. */ char *hostname = strcpy((char *)ccom_alloc((int32)strlen(name)+1L), name); #ifdef BSD_LIKE_SEARCH { PathElement *p; UnparsedName unparse; char new_path[MAX_NAME]; if (feature & FEATURE_KANDR_INCLUDE) return hostname; /* remove the head of the path and push it on the save stack */ p = path_hd; path_hd = p->link; p->link = path_sav; path_sav = p; if (path != NULL) { translate_fname(path, &unparse, new_path); new_path[unparse.un_pathlen] = 0; dbg_notepath(new_path); } else new_path[0] = 0; path_hd = p = mk_path_element(path_hd, /* @@@ next line flag PE_USER/SYS? */ path == NULL ? INSTORE_FILE : 0, new_path); } #endif return hostname; } static void pop_include(void) { #ifdef BSD_LIKE_SEARCH PathElement *p; if (feature & FEATURE_KANDR_INCLUDE) return; /* * pop the saved path element off the save stack and * push it on to the front of the regular path element stack. */ p = path_hd; path_hd = path_sav; path_sav = path_sav->link; path_hd->link = p->link; #endif } static void preprocess_only(void) { #ifdef PASCAL /*ECN*/ syn_init(); #endif if (ccom_flags & FLG_PREPROCESS) { /* Selected if -E or -E -MD set */ pp_copy(); } else { /* Selected if -M set */ int character; while ((character = pp_nextchar()) != PP_EOF) continue; } } #ifdef FOR_ACORN #ifndef PASCAL #ifndef FORTRAN int cplusplus_preprocessing(void) { return (ccom_flags & FLG_PREPROCESS) && cplusplus_flag; } #endif #endif #endif static void pre_include(char const *file) { FILE *f; if ((f = trackfile_open(file, "r")) != NULL) { pp_notesource(file, f, YES); preprocess_only(); } else cc_warn(warn_preinclude, file); } /* * Initialise compiler state. */ static void set_debug_options(ToolEnv *t) { #ifdef TARGET_HAS_DEBUGGER char const *dbgval = toolenv_lookup(t, "-g"); if (dbgval != NULL && dbgval[1] == '+') { int ch; uint32 opt = 0; dbgval = toolenv_lookup(t, "-gx"); while ((ch = *++dbgval) != 0) switch (ch) { case 'c': opt |= DBG_OPT_CSE; break; case 'r': opt |= (DBG_OPT_ALL-DBG_OPT_REG); break; case 'g': opt |= DBG_OPT_DEAD;break; case 'o': opt |= DBG_OPT_ALL; break; } dbgval = toolenv_lookup(t, "-gt"); opt |= DBG_ANY; while ((ch = *++dbgval) != 0 && ch != '+') switch (ch) { case 'f': opt &= ~DBG_PROC; break; case 'l': opt &= ~DBG_LINE; break; case 'v': opt &= ~DBG_VAR; break; case 'p': opt &= ~DBG_PP; break; } if (ch == '+') while ((ch = *++dbgval) != 0) switch (ch) { case 'f': opt |= DBG_PROC; break; case 'l': opt |= DBG_LINE; break; case 'v': opt |= DBG_VAR; break; case 'p': opt |= DBG_PP; break; } usrdbgmask |= opt; } #endif } static int makeflag; static void set_compile_options(ToolEnv *t) { char const *val; int n; val = toolenv_lookup(t, ".lang"); #ifdef PASCAL if (StrEq(val, "=-iso")) feature |= FEATURE_ISO; #else if (StrEq(val, "=-pcc")) feature = (feature | pcc_features()) & ~(FEATURE_ANSI|FEATURE_CPP|FEATURE_CFRONT); else if (StrEq(val, "=-pcc -strict")) feature = (feature | pcc_features() | FEATURE_FUSSY) & ~(FEATURE_ANSI|FEATURE_CPP|FEATURE_CFRONT); else if (StrEq(val, "=-ansi -strict")) feature = (feature | FEATURE_ANSI | FEATURE_FUSSY) & ~(FEATURE_LIMITED_PCC|FEATURE_CPP|FEATURE_CFRONT); else if (StrEq(val, "=-ansi")) feature = (feature | FEATURE_ANSI) & ~(FEATURE_PCC|FEATURE_CPP|FEATURE_CFRONT); else if (StrEq(val, "=-ansi -fc")) feature = (feature | FEATURE_ANSI | FEATURE_LIMITED_PCC) & ~(FEATURE_PCC|FEATURE_CPP|FEATURE_CFRONT); # ifdef CPLUSPLUS else if (StrEq(val, "=-cfront")) feature = (feature | FEATURE_CPP | FEATURE_CFRONT) & ~(FEATURE_PCC|FEATURE_ANSI); else if (StrEq(val, "=-cpp")) feature = (feature | FEATURE_CPP) & ~(FEATURE_PCC|FEATURE_ANSI); else if (StrEq(val, "=-cpp -strict")) feature = (feature | FEATURE_CPP | FEATURE_FUSSY) & ~(FEATURE_PCC|FEATURE_ANSI); # endif #endif toolenv_enumerate(t, SetFeatures, NULL); toolenv_enumerate(t, DoPredefine, NULL); Tool_OrderedEnvEnumerate(t, "-I.", AddInclude, NULL); if (TE_Count(t, "-J.") > 0) { ccom_flags &= ~FLG_INSTORE_FILES_IMPLICITLY; Tool_OrderedEnvEnumerate(t, "-J.", AddInclude, NULL); } if ((val = toolenv_lookup(t, "-ZI")) != NULL) pre_include(&val[1]); if ((val = toolenv_lookup(t, "-ZS")) != NULL) system_flavour = &val[1]; if ((val = toolenv_lookup(t, "-zj")) != NULL) config |= CONFIG_INDIRECT_SETJMP; if ((val = toolenv_lookup(t, ".schar")) != NULL) feature = ClearOrSet(feature, FEATURE_SIGNED_CHAR, val[3] == '+'); if ((val = toolenv_lookup(t, ".areaperfn")) != NULL) feature = ClearOrSet(feature, FEATURE_AOF_AREA_PER_FN, val[3] == '+'); #ifndef NO_DUMP_STATE if ((val = toolenv_lookup(t, "-zgw")) != NULL) { compiledheader = &val[1]; dump_state |= DS_Dump; } if ((val = toolenv_lookup(t, "-zgr")) != NULL) { compiledheader = &val[1]; dump_state |= DS_Load; } #endif if ((val = toolenv_lookup(t, ".pp_only")) != NULL) ccom_flags = (ccom_flags | FLG_PREPROCESS) & ~FLG_COMPILE; if ((val = toolenv_lookup(t, "-K")) != NULL) ccom_flags |= FLG_COUNTS; if ((val = toolenv_lookup(t, "-C")) != NULL) feature |= FEATURE_PPCOMMENT; if ((val = toolenv_lookup(t, "-p")) != NULL) var_profile_option = val[0] == '=' ? 2 : 1; if ((val = toolenv_lookup(t, ".no_object")) != NULL) ccom_flags |= FLG_NO_OBJECT_OUTPUT; if ((val = toolenv_lookup(t, ".nowarn")) != NULL && val[0] != '?') feature |= FEATURE_NOWARNINGS; val = toolenv_lookup(t, "-O"); if (StrEq(val, "=time")) config |= CONFIG_OPTIMISE_TIME; else if (StrEq(val, "=space")) config |= CONFIG_OPTIMISE_SPACE; n = TE_Integer(t, "-zap", 0); config = ClearOrSet(config, CONFIG_STRUCT_PTR_ALIGN, n == 0); #ifdef MIN_ALIGNMENT_CONFIGURABLE if ((n = TE_Integer(t, "-zas", 0)) != 0) alignof_struct_val = n; if ((n = TE_Integer(t, "-zat", 0)) != 0) alignof_toplevel_static_var = n; #endif if ((n = TE_Integer(t, "-zz", 0x12345)) != 0x12345) bss_threshold = n; if ((val = toolenv_lookup(t, "-disallow_tentative_statics")) != NULL) disallow_tentative_statics = YES; else disallow_tentative_statics = (LanguageIsCPlusPlus ? YES : NO); if ((val = toolenv_lookup(t, "-M")) != NULL) { ccom_flags |= FLG_MAKEFILE; if (val[0] == '?') ccom_flags &= ~(FLG_COMPILE+FLG_NOSYSINCLUDES); else if (val[1] == '<') ccom_flags = (ccom_flags | FLG_NOSYSINCLUDES) & ~FLG_COMPILE; #ifdef FOR_ACORN else if (val[1] == '+') makefile = toolenv_lookup(t, ".depend"); #endif makeflag = 0; } } /* * Inner compile control routine. */ #ifndef NO_DUMP_STATE static void DumpCompiledHeader(void); #endif static void compile_statements(void) { bool decls = NO; bool returneof = YES; #ifndef PASCAL /*ECN*/ /* AM, Sept 91: I am inclined to think the best interface is to call */ /* rd_topdecl(0) (1,2,3,...) until it returns NULL (or list1(s_eof)) */ /* Then all conceivable actions could be done, instead of this mess. */ /* May 1993: process almost complete for C/C++... */ for (;;) #endif { TopDecl *d; AEop h0d; clock_t t0; phasename = "reinit"; lex_beware_reinit(); /* preserve needed things over reinit */ drop_local_store(); /* in case nextsym() above read #if */ alloc_reinit(); lex_reinit(); cg_reinit(); /* must be done BEFORE parsing */ #ifdef PASCAL /*ECN*/ syn_init(); /* @@@ AM: surely is just part of rd_topdecl? */ /* then syn_init can be OK as usual. */ #endif syn_reinit(); #ifndef PASCAL /*ECN*/ t0 = clock(); #endif phasename = "parse"; d = rd_topdecl(returneof); if (d == 0) syserr("rd_topdecl() => NULL"); alloc_noteAEstoreuse(); #ifndef PASCAL /*ECN*/ tmuse_front += clock() - t0; #endif if (debugging(DEBUG_AETREE)) pr_topdecl(d); t0 = clock(); phasename = "jopcode"; h0d = h0_(d); /* killed by drop_local_store()! */ if (h0d == s_fndef) cg_topdecl(d, curlex.fl); currentfunction.symstr = NULL; tmuse_back += clock() - t0; drop_local_store(); if (h0d == s_eof) { if (returneof) { #ifndef NO_DUMP_STATE if (dump_state & DS_Dump) DumpCompiledHeader(); #endif returneof = NO; } else break; } else decls = YES; } #ifndef PASCAL /*ECN*/ if (!decls && (feature & FEATURE_ANSI)) /* move to rd_topdecl()? */ { if (feature & FEATURE_FUSSY) cc_rerr(compiler_rerr_no_extern_decl); else cc_warn(compiler_rerr_no_extern_decl); } #endif if (LanguageIsCPlusPlus) vg_ref_dynamic_init(); } static void cleanup(void) { bind_cleanup(); pp_tidyup(); if (debugging(DEBUG_STORE)) { cc_msg("Time: %ldcs front-end %ldcs back-end\n", (long) tmuse_front,(long) tmuse_back); show_store_use(); } cg_tidy(); #ifndef NO_OBJECT_OUTPUT # ifdef COMPILING_ON_ACORN_KIT { bool have_obj = (objstream != NULL); /* objstream cannot be stdout, so cc_close does a spurious test. */ cc_close(&objstream, objectfile); # ifdef COMPILING_ON_RISC_OS if (have_obj) set_time_stamp(objectfile, YES); # endif # ifdef COMPILING_ON_UNIX if (have_obj && system_flavour != NULL) { char *cmd; cmd = GlobAlloc(SU_Other, 24 + strlen(system_flavour) + strlen(objectfile)); sprintf(cmd,"/usr/bin/symrename -%s %s",system_flavour,objectfile); system(cmd); } # endif } # else cc_close(&objstream, objectfile); # endif #endif #ifndef NO_ASSEMBLER_OUTPUT cc_close(&asmstream, asmfile); #endif cc_close(&listingstream, listingfile); cc_close(&makestream, makefile); summarise(); #ifdef ENABLE_MAPSTORE if (debugging(DEBUG_MAPSTORE)) _mapstore(); #endif alloc_perfilefinalise(); } /* * Open include file for pre-processor. * (included here because of system dependencies). */ static void show_h_line(int32 line, const char *file, bool to_makefile) { if (ccom_flags & FLG_PREPROCESS) printf("#%s %lu \"%s\"\n", (feature & FEATURE_PCC ? "" : "line"), (long)line, file); if (to_makefile && ccom_flags & FLG_MAKEFILE) { if (makestream == stdout) { backchat_InclusionDependency dep; dep.targetName = objectfile; dep.dependsonName = file; backchat.send( (backchat.handle != NULL) ? backchat.handle : (void *)stdout, BC_INCLUDEMSG, &dep); } else fprintf(makestream, DEPEND_FORMAT, objectfile, file); } } void UpdateProgress(void) { #ifdef COMPILING_ON_MPW UPDATE_PROGRESS(); #else backchat.send(backchat.handle, BC_NULLMSG, NULL); #endif } #ifndef NO_INSTORE_FILES static FILE *try_instore_file(const char *file, pp_uncompression_record **urp) { FILE *include_file = open_builtin_header(file, urp); if (include_file != NULL) { if (debugging(DEBUG_FILES)) cc_msg("Opened instore file '%s'\n", file); show_h_line(1, file, NO); push_include(NULL, file); } else if (FILES_DEBUG_LEVEL(1)) cc_msg("Instore file '%s' not found.\n", file); return include_file; } #endif /* NO_INSTORE_FILES */ static FILE *incl_search(char const *file, const char *new_file, bool systemheader, pp_uncompression_record **urp, char const **hostname) { FILE *new_include_file; PathElement *p; #ifndef NO_INSTORE_FILES if ((ccom_flags & FLG_INSTORE_FILES_IMPLICITLY) && systemheader) { /* Note that it is important for portability (even across unix/riscos) */ /* to have the original 'file' and not the munged 'new_file' instore. */ new_include_file = try_instore_file(file, urp); if (new_include_file != NULL) return new_include_file; } #endif p = path_hd; if (systemheader || (ccom_flags & FLG_USE_SYSTEM_PATH)) p = p->link; while (p != NULL) { char current[MAX_NAME]; if (p->flags & INSTORE_FILE) { #ifndef NO_INSTORE_FILES /* Note that it is important for portability (even across unix/riscos) */ /* to have the original 'file' and not the munged 'new_file' instore. */ new_include_file = try_instore_file(file, urp); if (new_include_file != NULL) return new_include_file; #endif } else /* current path is not :mem */ { strcpy(current, p->name); if (strlen(current) + strlen(new_file) + 1 <= MAX_NAME) { strcat(current, new_file); if ((new_include_file = trackfile_open(current, "r")) != NULL) { if (debugging(DEBUG_FILES)) cc_msg("Opened file '%s'\n", current); if (!(systemheader && (ccom_flags & FLG_NOSYSINCLUDES))) show_h_line(1, current, YES); *hostname = push_include(current, current); return new_include_file; } else if (FILES_DEBUG_LEVEL(1)) cc_msg("File '%s' not found.\n", current); } } p = p->link; } #ifdef COMPILING_ON_RISC_OS /* IDJ 06-Jun-94: before trying instore headers we try just the filename * by itself. This is because of something like <foo$dir>.h.bar which * may or may not be a rooted filename. */ if ((new_include_file = trackfile_open(new_file, "r")) != NULL) { if (debugging(DEBUG_FILES)) cc_msg("Opened file '%s'\n", new_file); if (!(systemheader && (ccom_flags & FLG_NOSYSINCLUDES))) show_h_line(1, new_file, YES); *hostname = push_include(new_file, new_file); return new_include_file; } else if (FILES_DEBUG_LEVEL(1)) cc_msg("File '%s' not found.\n", new_file); #endif #ifndef NO_INSTORE_FILES /* Not found - ANSI require looking for "stdio.h" as <stdio.h> when all */ /* else has failed. */ /* Note that it is important for portability (even across unix/riscos) */ /* to have the original 'file' and not the munged 'new_file' instore. */ return try_instore_file(file, urp); #else return NULL; #endif } extern FILE *pp_inclopen(char const *file, bool systemheader, pp_uncompression_record **urp, char const **hostname, FileLine fl) { FILE *new_include_file; UnparsedName unparse; char new_file[MAX_NAME]; *hostname = file; translate_fname(file, &unparse, new_file); if (!(unparse.type & FNAME_ROOTED)) { new_include_file = incl_search(file, new_file, systemheader, urp, hostname); #ifdef RETRY_INCLUDE_LOWERCASE if (new_include_file == NULL) { bool not_all_lowercase = NO; char *p = new_file; int c; while ((c = *p++) != '\0') if (isupper(c)) { not_all_lowercase = YES; p[-1] = tolower(c); } if (not_all_lowercase) new_include_file = incl_search(file, new_file, systemheader, urp, hostname); } #endif if (new_include_file != NULL && usrdbg(DBG_PP)) dbg_include(*hostname, NULL, fl); } else /* rooted file */ { if ((new_include_file = trackfile_open(new_file, "r")) != NULL) { if (debugging(DEBUG_FILES)) cc_msg("Opened file '%s'\n", new_file); if (!(systemheader && (ccom_flags & FLG_NOSYSINCLUDES))) show_h_line(1, new_file, YES); *hostname = push_include(new_file, new_file); if (usrdbg(DBG_PP)) dbg_include(*hostname, NULL, fl); } else if (FILES_DEBUG_LEVEL(1)) cc_msg("File '%s' not found.\n", new_file); } return new_include_file; } extern void pp_inclclose(FileLine fl) { if (debugging(DEBUG_FILES)) cc_msg("Resuming file '%s' at line %d\n", fl.f, fl.l); if (usrdbg(DBG_PP)) dbg_include(NULL, NULL, fl); pop_include(); show_h_line(fl.l, fl.f, NO); } #ifndef NO_DUMP_STATE static void LoadCompiledHeader(void) { FILE *f = cc_open(compiledheader, BINARY_INPUT); uint32 w; fread(&w, sizeof(uint32), 1, f); if (w != DS_Version) cc_fatalerr(compiler_fatalerr_load_version, compiledheader); if (ferror(f) == 0) PP_LoadState(f); if (ferror(f) == 0) Bind_LoadState(f); if (ferror(f) == 0) Vargen_LoadState(f); cc_close(&f, compiledheader); } static void DumpCompiledHeader(void) { uint32 w = DS_Version; dumpstream = cc_open(compiledheader, BINARY_OUTPUT); fwrite(&w, sizeof(uint32), 1, dumpstream); if (ferror(dumpstream) == 0) PP_DumpState(dumpstream); if (ferror(dumpstream) == 0) Bind_DumpState(dumpstream); if (ferror(dumpstream) == 0) Vargen_DumpState(dumpstream); cc_close(&dumpstream, compiledheader); } #endif bool inputfromtty; #ifdef REBUFFERSTDOUT char stdoutbuffer[8192]; #endif extern int ccom(ToolEnv *t, char const *infile, char const *outfile, char const *listfile, char const *mdfile) { char *stdin_name = "<stdin>"; FILE *sourcestream = NULL; #ifdef HOST_USES_CCOM_INTERFACE #ifndef TARGET_IS_UNIX cc_msg("%s\n", CC_BANNER); #ifndef COMPILING_ON_MSDOS (void) signal(SIGINT, compile_abort); #endif #else /* TARGET_IS_UNIX */ /* The signal ignore state can be inherited from the parent... */ #define sig_ign ((void (*)(int))(SIG_IGN)) if (signal(SIGINT, sig_ign) != sig_ign) (void) signal(SIGINT, compile_abort); if (signal(SIGHUP, sig_ign) != sig_ign) (void) signal(SIGHUP, compile_abort); if (signal(SIGTERM, sig_ign) != sig_ign) (void) signal(SIGTERM, compile_abort); #endif #endif #if (defined NLS) && (defined HOST_USES_CCOM_INTERFACE) msg_init(argv[0],MSG_TOOL_NAME); #endif ccom_flags = FLG_COMPILE + FLG_INSTORE_FILES_IMPLICITLY; makefile = mdfile; listingfile = listfile; sourcefile = objectfile = asmfile = NULL; sourcemodule = ""; #ifndef NO_DUMP_STATE compiledheader = NULL; dumpstream = NULL; #endif dump_state = 0; system_flavour = NULL; #ifndef NO_ASSEMBLER_OUTPUT asmstream = 0; #endif #ifndef NO_OBJECT_OUTPUT objstream = 0; #endif #ifndef NO_LISTING_OUTPUT listingstream = 0; #endif makestream = 0; makeflag = 0; tmuse_front = tmuse_back = 0; path_hd = path_sav = 0; #ifdef PASCAL /*ECN*/ rtcheck = 0; #endif feature = 0; suppress = 0; #ifndef NO_CONFIG config_init(t); #else config = 0; #endif { static int endian_test = 1; host_lsbytefirst = *((char *)&endian_test) != 0; } #ifdef MIN_ALIGNMENT_CONFIGURABLE alignof_struct_val = alignof_struct_default; alignof_toplevel_static_var = alignof_toplevel_static_default; #endif #ifdef BSS_THRESHOLD_DEFAULT bss_threshold = BSS_THRESHOLD_DEFAULT; #endif phasename = "init"; currentfunction.symstr = NULL; errstate_perfileinit(); set_debug_options(t); /* -g options need to be known about before pp_init gets called (since */ /* that causes some macros to be defined, which may need to go into */ /* debug tables) */ alloc_perfileinit(); pp_init(&curlex.fl); /* for pp_predefine() option and pragma on command line */ /* must init_sym_tab here if pp shares its symbol tables */ sourcefile = stdin_name; sourcemodule = "none"; #ifdef FORTRAN pp_pragmavec['x'-'a'] = 1; /* Enable double-complex by default for now */ #endif var_cc_private_flags = 0; /* No development options switched on yet */ set_compile_options(t); mcdep_set_options(t); if (toolenv_lookup(t, ".asm_out") != NULL) asmfile = outfile; else objectfile = outfile; if (StrEq(infile, "-")) { /* then just leave as stdin */ inputfromtty = filestat_istty(stdin); sourcestream = stdin; #ifdef COMPILING_ON_RISC_OS /* Change default no-buffering to line buffering... */ # if defined(FOR_ACORN) /* A fault in the shared library forces the use of a */ /* real buffer. NULL will not do... */ static char input_buffer[256]; setvbuf(stdin, input_buffer, _IOLBF, sizeof(input_buffer)); dde_prefix_init(""); # elif defined(TARGET_IS_ARM) && !defined(OBSOLETE_ARM_NAMES) setvbuf(stdin, NULL, _IOLBF, 256); # endif #endif path_hd = mk_path_element(path_hd, PE_USER, ""); if (path_hd->link == 0) path_tl = path_hd; } else { #ifdef FOR_ACORN /* IDJ: 06-Jun-94. Set desktop "current directory" */ dde_prefix_init(current); dde_sourcefile_init(); #endif inputfromtty = NO; if ((sourcestream = trackfile_open(infile, "r")) == NULL) { char message[256]; msg_sprintf(message, driver_couldnt_read, infile); driver_abort(message); } else { UnparsedName unparse; char new_dir[MAX_NAME], *mod; sourcefile = infile; /* * Add path name of source file to the -I list. */ translate_fname(infile, &unparse, new_dir); new_dir[unparse.un_pathlen] = '\0'; path_hd = mk_path_element(path_hd, PE_USER, new_dir); /* Make sure path_tl is always the tail, even if file precedes -I */ if (path_hd->link == 0) path_tl = path_hd; /* set up 'sourcemodule' from main part of file name: */ mod = (char *)ccom_alloc(unparse.rlen+1L); memcpy(mod, unparse.root, unparse.rlen); mod[unparse.rlen] = 0; sourcemodule = mod; } } if (ccom_flags & FLG_COMPILE) { /* under the driver.c interface at most one of the following is true */ #ifndef NO_OBJECT_OUTPUT if (objectfile != NULL && !(ccom_flags & FLG_NO_OBJECT_OUTPUT)) { objstream = cc_open(objectfile, BINARY_OUTPUT); # ifdef COMPILING_ON_RISC_OS set_time_stamp(objectfile, NO); # endif } #endif #ifndef NO_ASSEMBLER_OUTPUT if (asmfile != NULL) asmstream = cc_open(asmfile, TEXT_FILE); #endif if (objectfile == NULL && asmfile == NULL) { #ifndef NO_ASSEMBLER_OUTPUT asmstream = stdout; #endif feature |= FEATURE_ANNOTATE; /* simple test use */ } #ifndef NO_LISTING_OUTPUT if (listingfile != NULL) { if (listingfile[0] != '\0') { listingstream = cc_open(listingfile, TEXT_FILE); if (listingstream != stdout) /* @@@ get rid of this hack */ fprintf(listingstream, " 1 "); } else listingstream = stdout; if (ccom_flags & FLG_COUNTS) { FILE *map = fopen("counts", "rb"); if (map == NULL) driver_abort(msg_lookup(driver_couldnt_read_counts)); if (!map_init(map)) driver_abort(msg_lookup(driver_malformed_counts)); } } #endif } if (ccom_flags & FLG_MAKEFILE) { if (makefile == NULL) { backchat_InclusionDependency dep; dep.targetName = objectfile; dep.dependsonName = sourcefile; backchat.send( (backchat.handle != NULL) ? backchat.handle : (void *)stdout, BC_INCLUDEMSG, &dep); makestream = stdout; } else { /* if -M+, then open with append ("a") if already writing to */ /* makefile (makeflag != 0) */ makestream = cc_open(makefile, makeflag ? TEXT_FILE_APPEND : TEXT_FILE); makeflag = 1; /* Print out source file and object file for -M option... */ fprintf(makestream, DEPEND_FORMAT, objectfile, sourcefile); } } if (config & CONFIG_OPTIMISE_TIME) var_crossjump_enabled = 0; #if REBUFFERSTDOUT if ((ccom_flags & FLG_PREPROCESS) || asmstream == stdout || listingstream == stdout || makestream == stdout) setvbuf(stdout, stdoutbuffer, _IOFBF, sizeof stdoutbuffer); #endif if (debugging(DEBUG_FILES)) cc_msg("Compiling '%s'.\n", sourcefile); pp_notesource(sourcefile, sourcestream, NO); show_h_line(1, sourcefile, NO); if (sourcefile != stdin_name) dbg_include(sourcefile, path_hd->name, curlex.fl); aetree_init(); bind_init(); lex_init(); /* sets curlex.sym to s_nothing */ builtin_init(); /* change to setup from syn_init? */ sem_init(); #ifndef PASCAL /*ECN*/ syn_init(); #endif vargen_init(); cg_init(); #ifndef NO_DUMP_STATE if (dump_state & DS_Load) LoadCompiledHeader(); #endif initstaticvar(datasegment, 1); /* nasty here */ drop_local_store(); /* required for alloc_reinit() */ if (ccom_flags & FLG_COMPILE) compile_statements(); else preprocess_only(); if (sourcefile != stdin_name) dbg_include(NULL, NULL, curlex.fl); cleanup(); /* AM: re-open the discussion on return codes and errors. */ if (errorcount != 0) return EXIT_error; if (pp_pragmavec['e'-'a'] > 0) return 0; /* -zpe1 => "generous" mode */ if (recovercount != 0) return EXIT_error; if (warncount != 0) return EXIT_warn; return 0; } /* end of compiler.c */
stardot/ncc
clbcomp/clb_store.c
/* * clbcomp/clb_store.c: Storage allocation for the Codemist C compiler * Copyright (C) Codemist Ltd., 1987-1992. * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Advanced RISC Machines Limited, 1990-1992, 1996. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifdef __STDC__ # include <stdlib.h> # include <string.h> #else # include "stddef.h" /* for size_t */ # include "strings.h" extern char *calloc(); extern free(); #endif #include "globals.h" #include "store.h" #include "defs.h" #include "mcdep.h" /* usrdbg(xxx) */ #include "errors.h" typedef struct FreeList { struct FreeList *next; int32 rest[1]; } FreeList; void ClearToNull(void **a, int32 n) { while (--n >= 0) a[n] = NULL; } VoidStar xglobal_cons2(StoreUse t, IPtr a, IPtr b) { IPtr *p = (IPtr *) GlobAlloc(t, sizeof(IPtr[2])); p[0] = a; p[1] = b; return (VoidStar) p; } VoidStar xglobal_list3(StoreUse t, IPtr a, IPtr b, IPtr c) { IPtr *p = (IPtr *) GlobAlloc(t, sizeof(IPtr[3])); p[0] = a; p[1] = b; p[2] = c; return (VoidStar) p; } VoidStar xglobal_list4(StoreUse t, IPtr a, IPtr b, IPtr c, IPtr d) { IPtr *p = (IPtr *) GlobAlloc(t, sizeof(IPtr[4])); p[0] = a; p[1] = b; p[2] = c; p[3] = d; return (VoidStar) p; } VoidStar xglobal_list5(StoreUse t, IPtr a, IPtr b, IPtr c, IPtr d, IPtr e) { IPtr *p = (IPtr *) GlobAlloc(t, sizeof(IPtr[5])); p[0] = a; p[1] = b; p[2] = c; p[3] = d; p[4] = e; return (VoidStar)p; } VoidStar xglobal_list6(StoreUse t, IPtr a, IPtr b, IPtr c, IPtr d, IPtr e, IPtr f) { IPtr *p = (IPtr *) GlobAlloc(t, sizeof(IPtr[6])); p[0] = a; p[1] = b; p[2] = c; p[3] = d; p[4] = e; p[5] = f; return (VoidStar)p; } VoidStar xglobal_list7(StoreUse t, IPtr a, IPtr b, IPtr c, IPtr d, IPtr e, IPtr f, IPtr g) { IPtr *p = (IPtr *) GlobAlloc(t, sizeof(IPtr[7])); p[0] = a; p[1] = b; p[2] = c; p[3] = d; p[4] = e; p[5] = f; p[6] = g; return (VoidStar)p; } VoidStar GlobAlloc(StoreUse t, int32 n) { char *p = calloc(1,n); IGNORE(t); if (p == NULL) syserr("out of store"); return p; } VoidStar discard(VoidStar p) { FreeList *q = ((FreeList *)p)->next; free(p); return (VoidStar) q; } /* end of clbcomp/clb_store.c */
stardot/ncc
tests/regress.c
/* * ARM C compiler regression test $RCSfile$ * Copyright (C) 1995 Advanced Risc Machines Ltd. All rights reserved. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <setjmp.h> #include <stdio.h> #include <string.h> #include "testutil.h" /********************* ***********************/ typedef struct { int a; short x; } X_xxx; unsigned char f_xxx(X_xxx *x, int y) { return x->x > (y & 0x3fff); } void t_xxx() { X_xxx x = { 2, 3 }; EQI(f_xxx(&x, 1), 1); } /********************* 536 ***********************/ jmp_buf buf; int h_536(int x) { EQI(x, 1); longjmp(buf, 1); return 0; } int g_536(int x) { if (x != 1) return h_536(x); else return x+1; } int t_536() { struct { int a[1030]; int (* f)(int); } xx; xx.f = g_536; if (setjmp(buf) == 0) { EQI(xx.f(1), 2); return 0; } else return 0; } /********************* 591 ***********************/ void t_591() { char a[4]; strcpy(a, "xxx"); strcpy(a, "a\0b"); EQI(a[2], 'x'); } /********************* 593 ***********************/ typedef struct { int sig; } S_593; static int x_593[1000]; int sub_593(int *ap) { S_593 *uap = (S_593 *)ap; int ret; ret = x_593[uap->sig + 1]; return(ret); } void t_593(void) { int n = 33; x_593[34] = 7; EQI(sub_593(&n), 7); } /********************* 628 ***********************/ int f_628(int x) { int a = (x>0?10:20)/7+3; int b = (x>0?0:1)/7+3; return a+b; } void t_628() { EQI(f_628(1), 7); } /********************* 639 ***********************/ void g_639(unsigned short *p, int i, int j, int k, int l) { *p = i; } int f_639() { unsigned short p[6]; p[0] = 0; g_639(p, 1, 2, 3, 4); return *p == 0; } void t_639(void) { EQI(f_639(), 0); } /********************* 678 ***********************/ typedef struct S_678 S_678; struct S_678 { void (*f)(S_678 *, int); int x; }; void g_678(S_678 *p, int n) { p->x += n; } void f_678(S_678 *p) { if (p->x == -1) p->f(p, 1); else p->f(p, 5); } void t_678(void) { S_678 s; s.f = g_678; s.x = -1; f_678(&s); EQI(s.x, 0); f_678(&s); EQI(s.x, 5); } /********************* 683 ***********************/ int f_683(unsigned x, unsigned y) { x = (x & 0xff00ffff) | ((x & (y << 16)) & 0xff0000); return x; } void t_683() { EQI(f_683(0x11ff1111, 0x34), 0x11341111); } /********************* 701 ***********************/ typedef struct T_701 T_701; typedef struct E_701 E_701; struct E_701 { int n; T_701 *t; E_701 *a; }; static E_701 e2_701, e1_701 = {74, 0, &e2_701}; E_701 *g_701(int a, T_701 *t, E_701 *e) { T_701 *tt = NULL; EQI((int)t, (int)tt); EQI((int)e, (int)&e2_701); return e; } E_701 *h_701(T_701 *t, E_701 *e, int x) { return e; } static E_701 *f_701(E_701 *x, T_701 *t) { return (x->n == 74) ? g_701(74, t, x->a) : h_701(t, x->a, 0); } int t_701(void) { f_701(&e1_701, 0); return 0; } /********************* 724 ***********************/ typedef union { int : 20; int : 20; double d; int i; } U_724; U_724 u_724 = { 1.23 }, v_724 = { 2.34 }; void t_724(void) { U_724 *p = &u_724; EQI(sizeof(u_724), sizeof(double)); EQI(v_724.i, p[1].i); } /********************* 725 ***********************/ typedef struct S_725 { int i; } S_725; int f_725(S_725 s) { switch (s.i) { case 2:break; default:return 7; } return 5; } /* With faulty compilers, case 2: generates a spurious error: cast to non-equal 'S' illegal. */ void t_725(void) { S_725 s; s.i = 7; EQI(f_725(s), 7); } /********************* 727 ***********************/ typedef struct { int size; int put_ix; int get_ix; int cnt; unsigned char *buff; } S_727; unsigned char f_727(S_727 *p) { p->cnt--; return p->get_ix == p->size-1 ? p->buff[(p->get_ix = 0, p->size-1)] : p->buff[p->get_ix++]; } void t_727(void) { S_727 s; unsigned char b[16] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; s.buff = b; s.size = 16; s.get_ix = 3; s.cnt = 7; EQI(f_727(&s), 4); EQI(s.get_ix, 4); } /********************* 742 ***********************/ int f_742(int x, int len, int code) { int i; if (code != 1) return len; for (i = 0; i < len; i++) if (x == i) i++; return i; } void t_742() { EQI(f_742(1, 6, 2), 6); } /********************* 770 ***********************/ int f_770(int i) { return ((i>>31) & 2) != 0; } void t_770() { EQI(f_770(0x80000000), 1); } /********************* 776 ***********************/ typedef struct { int c; int xx[150]; } S_776; static S_776 s_776 = { 0 }; S_776 f_776(void) { S_776 x; x=s_776; x.c=1; return x; } void g_776(int i, int j) { } void t_776() { int i = 7, j = 8, k = 9, l = 10, m = 22, n = 23, n1 = 14, n2 = 25; { S_776 xx0, xx1, xx2, xx3, xx4, xx5, xx6, xx7; g_776(i >>= (xx0 = f_776()).c, 3); g_776(j >>= (xx1 = f_776()).c, 4); g_776(k >>= (xx2 = f_776()).c, 4); l >>= (xx3 = f_776()).c; g_776(l, 5); g_776(m >>= (xx4 = f_776()).c, 11); n >>= (xx5 = f_776()).c; g_776(n, 11); n1 >>= (xx6 = f_776()).c; EQI(n1, 7); n2 >>= (xx7 = f_776()).c; EQI(n2, 12); } } /********************* 778 ***********************/ typedef struct { unsigned int hi, lo; } S_778; typedef struct { unsigned int a, b, c, d, e, f, g, h, i, j, k; } S_778a; static S_778 s_778; static S_778a s_778a; void f_778(void) { S_778 x = {0x3ff00000, 0}; x.lo = 1; s_778 = x; } void f_778a(void) { S_778a x = {10,11,12,13,14,15,16,17,18,19,20}; x.j = 1; s_778a = x; } void t_778() { f_778(); EQI(s_778.lo, 1); EQI(s_778.hi, 0x3ff00000); f_778a(); EQI(s_778a.i, 18); EQI(s_778a.j, 1); } /********************* 825 ***********************/ typedef struct { int a, b, c; } S_825; typedef struct { int a; char b, c; S_825 s; char d, e, f, g; } S1_825; static S_825 MkS_825(void) { S_825 s; s.a = s.b = s.c = 0; return s; } static void f_825(S1_825 * s1, int x) { s1->a = 0; s1->b = 6 + x; s1->c = 3; s1->s = MkS_825(); s1->d = 0; s1->e = 5; s1->f = 1; s1->g = 0; } void t_825() { S1_825 s; f_825(&s, 3); EQI(s.d, 0); EQI(s.e, 5); EQI(s.f, 1); EQI(s.g, 0); } /********************* 919 ***********************/ typedef struct { int x, y, z; int a[1024], b[1024]; } S_919; void f_919(S_919 *s) { int i; for (i = 0; i < 1024; i++) { s->a[i] = -1; s->b[i] = i; } } void t_919() { S_919 s; memset(&s, 0, sizeof(S_919)); f_919(&s); EQI(s.a[3], -1); EQI(s.b[5], 5); } /********************* 922 ***********************/ typedef struct { unsigned n; unsigned p; } S_922; void f_922(unsigned p) {} void g_922(S_922 *s) { if (s->n == 0) { f_922(0x1234); s->p = 0x1234; } else { f_922(0x1234); s->p = 0x1234; } } void t_922(void) { S_922 s = { 15, 23}; g_922(&s); EQI(s.p, 0x1234); } /********************* 1049 ***********************/ int a_1049; int b_1049[2] = {1, 2}; int f_1049(void) { return *((int*) (a_1049 + 4)); } void t_1049(void) { a_1049 = (int)b_1049; EQI(f_1049(), 2); } /********************* 1075 ***********************/ typedef unsigned uint; static char *inf; typedef int F(void); static int f1(void); static int *f2(void); static int f3(int x); static int f4(char *p); /* pf needs to be spilt, but not because it's address-taken, for this * test to fail (If it's address-taken, there will be no tailcall). * Accordingly, it's a bit delicate, and probably in this form is OK * with apcs /noswst even with faulty compilers. */ void f(F *pf, uint ns) { int i; int format = f1(); for (i = 1; i <= ns; i++) { int *p = f2(); if (format == 0) *p = f3(3); else { int s = f4(inf); int n = f4(inf); if (s == 0) *p = 0; } } pf(); } static int s; static int f1() { return 0; } static int *f2() { return &s; } static int f3(int x) { return x+3; } static int f4(char *p) { return 0; } void t_1075() { int v[32]; int i; for (i = 0; i < 32; i++) v[i] = 0; /* That tries to ensure that, when pf is loaded from the wrong place * inside f, the value loaded will cause a fault when used. */ f(f1, 3); EQI(s, 6); } /********************* 1152 ***********************/ typedef struct { void *a, *b, *c, *d; } S_1152; S_1152 f_1152(S_1152 *p) { return *p; } void t_1152(void) { S_1152 a, b, c; c.a = c.b = c.c = c.d = 0; b.a = b.b = b.c = b.d = &c; a = f_1152(&b); EQI((int)a.a, (int)b.a); EQI((int)a.b, (int)b.b); EQI((int)a.c, (int)b.c); EQI((int)a.d, (int)b.d); EQI((int)c.a, 0); EQI((int)c.b, 0); EQI((int)c.c, 0); EQI((int)c.d, 0); } /********************* 1193 ***********************/ void g_1193(int *x, int *y, int *z) { *x = *y = 0; } void h_1193(int a, int b) { EQI(a, 1); EQI(b, 2); } void f_1193(short *s, int i, int x) { int a, b; int v[1024]; g_1193(&a, &b, v); a += 1; s[i] = x; b += 2; h_1193(a, b); } void t_1193() { short s[4]; f_1193(s, 1, 53); EQI(s[1], 53); } /********************* 1280 ***********************/ typedef struct { int a:32; } S_1280; void f_1280(S_1280 *s) { s->a = 0; } void t_1280() { union { int i; S_1280 s; } s; s.i = -1; f_1280(&s.s); EQI(s.i, 0); } /********************* 1281 ***********************/ void f1_1281(int *p) { *p = 33; } void f2_1281(void) { } void f3_1281(int *p) { *p = 57; } void f_1281(int *a, int b, int *c) { if (b) f1_1281(c); else { f2_1281(); f3_1281(a); } } void t_1281(void) { int a = 0, b = 0; f_1281(&a, 1, &b); EQI(a, 0); EQI(b, 33); } /********************* 1282 ***********************/ typedef struct { int a, b, c, d, e, f; } S_1282; int f_1282(int *p, int n) { *p = n; return 1; } void f1_1282(S_1282 *s, int n) { s->d = f_1282(&s->a, n) & 0; s->e = f_1282(&s->b, n) | -1; s->f = f_1282(&s->c, n) * 0; } void f2_1282(S_1282 *s, int n) { s->d = (s->a = n) & 0; s->e = (s->b = n) | -1; s->f = (s->c = n) * 0; } void f3_1282(S_1282 *s, int n) { s->d = (s->a++) & 0; s->e = (s->b++) | -1; s->f = (s->c++) * 0; } void f4_1282(S_1282 *s, int n) { s->d = (++s->a) & 0; s->e = (++s->b) | -1; s->f = (++s->c) * 0; } void t_1282(void) { S_1282 s, s1 = {0,0,0,3,3,3}; s = s1; f1_1282(&s, 5); EQI(s.a, 5); EQI(s.b, 5); EQI(s.c, 5); EQI(s.d, 0); EQI(s.e, -1); EQI(s.f, 0); s = s1; f2_1282(&s, 7); EQI(s.a, 7); EQI(s.b, 7); EQI(s.c, 7); EQI(s.d, 0); EQI(s.e, -1); EQI(s.f, 0); s = s1; f3_1282(&s, 3); EQI(s.a, 1); EQI(s.b, 1); EQI(s.c, 1); EQI(s.d, 0); EQI(s.e, -1); EQI(s.f, 0); s = s1; f4_1282(&s, 13); EQI(s.a, 1); EQI(s.b, 1); EQI(s.c, 1); EQI(s.d, 0); EQI(s.e, -1); EQI(s.f, 0); } /********************* 1360 ***********************/ int f_1360(int a) { return a; } int g_1360(int a, int b, int c, int d) { int e; int arr[1000]; a = f_1360(a); e = d + 100; arr[100] = a; arr[101] = b; arr[102] = c; arr[103] = d; return arr[e]; } void t_1360(void) { EQI(g_1360(10, 11, 12, 0),10); EQI(g_1360(13, 14, 15, 1),14); EQI(g_1360(16, 17, 18, 2),18); EQI(g_1360(19, 20, 21, 3), 3); } /********************* 1404 ***********************/ #include <string.h> char b_1404[13]; char c_1404[13]; void t_1404() { memcpy( c_1404,"cccccc",6 ); memcpy( b_1404,"bbbbbbbbbbbbbeeee",13 ); EQI(0, memcmp(c_1404, "cccccc", 6)); EQI(0, memcmp(b_1404, "bbbbbbbbbbbbbeeee", 13)); } /********************* 1550 ***********************/ typedef struct { char a; char b:4; } S_1550; S_1550 s_1550 = {1, 2}; typedef struct { char a; int b:4; } S_1550_1; S_1550_1 s_1550_1 = {1, 2}; void t_1550(void) { EQI(s_1550.a, 1); EQI(s_1550.b, 2); EQI(s_1550_1.a, 1); EQI(s_1550_1.b, 2); } /********************* 1556 ***********************/ typedef struct { char a:4; char b; } S_1556; S_1556 s_1556 = {1, 2}; typedef struct { int a:4; char b; } S_1556_1; S_1556_1 s_1556_1 = {1, 2}; void t_1556(void) { EQI(s_1556.a, 1); EQI(s_1556.b, 2); EQI(s_1556_1.a, 1); EQI(s_1556_1.b, 2); } /********************* 1681 ***********************/ int i_1681; void f_1681(void) { while (i_1681 == 0) { continue; } } void t_1681() { i_1681 = 1; f_1681(); EQI(i_1681, 1); } /********************* 1755 ***********************/ typedef int F_1755(void); int f1_1755(void) { return 1; } int f2_1755(void) { return 2; } int f_1755(F_1755 **fp) { F_1755 *f = *fp; *fp = f2_1755; return f(); } void t_1755(void) { F_1755 *f = f1_1755; EQI(f_1755(&f), 1); EQI(f(), 2); } /********************* 1780 ***********************/ typedef struct { double mt[2]; double t; } t1_1780; typedef struct { unsigned b; } t2_1780; typedef struct { float value; } t3_1780; typedef struct { unsigned b; } t4_1780; extern t1_1780 v1_1780; extern t2_1780 v2_1780; extern t3_1780 v3_1780; extern t4_1780 v4_1780; extern int count_1780; extern void f2_1780(void); void f0_1780(int i) { } float f1_1780(void) { float f, g; f = v1_1780.mt[0] - v1_1780.mt[1]; if (!f || v3_1780.value || v2_1780.b || v4_1780.b) { v1_1780.t = v1_1780.mt[0]; return 1; } if (f > 0.1) { v1_1780.mt[1] = v1_1780.mt[0] - 0.1; f = 0.1; } g = (v1_1780.t - v1_1780.mt[1]) / f; if (g < 0) { if (g < -0.01) { f0_1780(1); v1_1780.t = v1_1780.mt[1]; } g = 0; } else if (g > 1) { if (g > 1.01) { f0_1780(2); v1_1780.t = v1_1780.mt[0]; } g = 1; } f0_1780(0); if (count_1780++ != 0) f2_1780(); return g; } static jmp_buf exitbuf_1780; int count_1780; t1_1780 v1_1780; t2_1780 v2_1780; t3_1780 v3_1780; t4_1780 v4_1780; void f2_1780() { EQI(1, 0); longjmp(exitbuf_1780, 1); } void t_1780() { count_1780 = 0; v2_1780.b = v4_1780.b = 0; v3_1780.value = 0; v1_1780.mt[0] = 1.1; v1_1780.mt[1] = 1.0; v1_1780.t = 1.0; if (setjmp(exitbuf_1780) == 0) f1_1780(); } /********************* 1782 ***********************/ int t0_1782(int a, int b) { if (a / b == 2) return 1; /* returns after one recursive call */ if (++b > a) return 0; /* faulty code exits here */ return t0_1782(a / 3, b); } void t_1782(void) { EQI(t0_1782(12,1), 1); } /********************* 2125 ***********************/ /* must be compiled with /hardfp/nofp */ void t0_2125(int *p, int *q); void t1_2125(double); double t2_2125(int a, int b) { double c = 3.1; t0_2125(&a, &b); return c; } void t0_2125(int *p, int *q) { } double dval(double x) { return x; } void t_2125(void) { double x = dval(1.3); double y = dval(2.3); EQI(t2_2125(1, 2), 3); EQI((int)x, 1); EQI((int)y, 2); } /********************* 2292 ***********************/ struct { int x : 32; } X_2290 = 1; void t_2290(void) { EQI(X_2290.x, 1); } /********************* 2292 ***********************/ int s0_2292[200]; int s1_2292[200]; void t0_2292(int* in,int* out,int in_len,int* coef,int coef_len,int scale) { EQI((int)in, (int)s0_2292); EQI(in_len, 700); EQI((int)coef, (int)s1_2292); EQI(coef_len, 35); EQI(scale, 285); } void t1_2292(int **a, int **b) { EQI((int)*a, (int)s0_2292); EQI((int)*b, (int)s1_2292); } void t_2292() { int *input0 = s0_2292; int *input1 = s1_2292; int output[720]; t1_2292(&input0, &input1); t0_2292(input0,output,700,input1,35,285); } /********************* 2311 ***********************/ typedef int (*F_2311)(int, int, int); int f_2311(int a, int b, int c) { return a+b+c; } int g_2311(void) { return 2; } F_2311 ff_2311(void) { return f_2311; } void t_2311(void) { EQI(ff_2311()(1, g_2311(), g_2311()), 5); } /********************* 2516 ***********************/ void t_2516(void) { char buf[sizeof(double)]; double obj = 1.234; memcpy(buf, &obj, sizeof(double)); obj = 999.; memcpy(&obj, buf, sizeof(double)); EQD(obj, 1.234); } /********************* main ***********************/ int main() { BeginTest(); t_xxx(); t_536(); t_591(); t_593(); t_628(); t_639(); t_678(); t_683(); t_701(); t_724(); t_725(); t_727(); t_742(); t_770(); t_776(); t_778(); t_825(); t_919(); t_922(); t_1049(); t_1075(); t_1152(); t_1193(); t_1280(); t_1281(); t_1282(); t_1360(); t_1404(); t_1550(); t_1556(); t_1681(); t_1755(); t_1780(); t_1782(); t_2125(); t_2290(); t_2292(); t_2311(); t_2516(); EndTest(); return 0; }
stardot/ncc
mip/dwarf2.c
/* * C compiler file mip/dwarf1.c * Copyright: (C) 1995, Advanced RISC Machines Limited. All rights reserved. * Writer for DWARF version 2 debug tables. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <string.h> #include "globals.h" #if defined(TARGET_HAS_DEBUGGER) && defined(TARGET_HAS_DWARF) #include "errors.h" #include "aeops.h" #include "cgdefs.h" #include "version.h" #include "xrefs.h" #include "codebuf.h" #include "builtin.h" /* te_xxx, xxxsegment */ #include "simplify.h" /* mcrep */ #include "mcdep.h" #include "dwarf.h" #include "dw_int.h" typedef struct { Uint attrib; Uint form; } AttribDesc; typedef struct { Uint tag; bool children; AttribDesc const *attribs; } AbbrevEntry; #define DW_FORM_tref 0xff #define DW_FORM_string_expr 0xfe static AttribDesc const attr_null[] = { { 0, 0 } }; static AbbrevEntry const abbr_null = { 0, NO, attr_null }; static AttribDesc const attr_arraybound[] = { { DW_AT_upper_bound, DW_FORM_udata }, { 0, 0 } }; static AbbrevEntry const abbr_arraybound = { DW_TAG_subrange_type, NO, attr_arraybound }; static AbbrevEntry const abbr_arraybound_open = { DW_TAG_subrange_type, NO, attr_null }; static AttribDesc const attr_arraytype[] = { { DW_AT_type, DW_FORM_ref_udata }, { 0, 0 } }; static AbbrevEntry const abbr_arraytype = { DW_TAG_array_type, YES, attr_arraytype }; static AttribDesc const attr_basetype[] = { { DW_AT_byte_size, DW_FORM_data1 }, { DW_AT_encoding, DW_FORM_data1 }, { 0, 0 } }; static AbbrevEntry const abbr_basetype = { DW_TAG_base_type, NO, attr_basetype }; static AttribDesc const attr_classtype[] = { { DW_AT_name, DW_FORM_string }, { DW_AT_byte_size, DW_FORM_udata }, { 0, 0 } }; static AttribDesc const attr_classtype_nodata[] = { { DW_AT_name, DW_FORM_string }, { 0, 0 } }; static AttribDesc const attr_classtype_anon[] = { { DW_AT_byte_size, DW_FORM_udata }, { 0, 0 } }; static AbbrevEntry const abbr_classtype = { DW_TAG_class_type, YES, attr_classtype }; static AbbrevEntry const abbr_classtype_nodata = { DW_TAG_class_type, YES, attr_classtype_nodata }; static AbbrevEntry const abbr_classtype_anon = { DW_TAG_class_type, YES, attr_classtype_anon }; static AbbrevEntry const abbr_classtype_nodata_anon = { DW_TAG_class_type, YES, attr_null }; static AbbrevEntry const abbr_classtype_fref = { DW_TAG_class_type, NO, attr_classtype_nodata }; static AttribDesc const attr_compileunit[] = { { DW_AT_name, DW_FORM_string }, { DW_AT_producer, DW_FORM_string }, { DW_AT_language, DW_FORM_data1 }, { DW_AT_low_pc, DW_FORM_addr }, { DW_AT_high_pc, DW_FORM_addr }, { DW_AT_stmt_list, DW_FORM_tref }, { 0, 0 } }; static AttribDesc const attr_compileunit_nostmt[] = { { DW_AT_name, DW_FORM_string }, { DW_AT_producer, DW_FORM_string }, { DW_AT_language, DW_FORM_data1}, { DW_AT_low_pc, DW_FORM_addr }, { DW_AT_high_pc, DW_FORM_addr }, { 0, 0 } }; static AttribDesc const attr_compileunit_nocode[] = { { DW_AT_name, DW_FORM_string }, { DW_AT_producer, DW_FORM_string }, { DW_AT_language, DW_FORM_data1 }, { 0, 0 } }; static AbbrevEntry const abbr_compileunit = { DW_TAG_compile_unit, YES, attr_compileunit }; static AbbrevEntry const abbr_compileunit_nostmt = { DW_TAG_compile_unit, YES, attr_compileunit_nostmt }; static AbbrevEntry const abbr_compileunit_nocode = { DW_TAG_compile_unit, YES, attr_compileunit_nocode }; static AttribDesc const attr_qualtype[] = { { DW_AT_type, DW_FORM_ref_udata }, { 0, 0 } }; static AbbrevEntry const abbr_consttype = { DW_TAG_const_type, NO, attr_qualtype }; static AttribDesc const attr_enum[] = { { DW_AT_name, DW_FORM_string }, { DW_AT_byte_size, DW_FORM_data1 }, { 0, 0 } }; static AttribDesc const attr_enum_anon[] = { { DW_AT_byte_size, DW_FORM_data1 }, { 0, 0 } }; static AbbrevEntry const abbr_enum = { DW_TAG_enumeration_type, YES, attr_enum }; static AbbrevEntry const abbr_enum_anon = { DW_TAG_enumeration_type, YES, attr_enum_anon }; static AttribDesc const attr_enumerator[] = { { DW_AT_name, DW_FORM_string }, { DW_AT_const_value, DW_FORM_udata }, { 0, 0 } }; static AttribDesc const attr_enumerator_signed[] = { { DW_AT_name, DW_FORM_string }, { DW_AT_const_value, DW_FORM_sdata }, { 0, 0 } }; static AbbrevEntry const abbr_enumerator = { DW_TAG_enumerator, NO, attr_enumerator }; static AbbrevEntry const abbr_enumerator_signed = { DW_TAG_enumerator, NO, attr_enumerator_signed }; static AttribDesc const attr_friend[] = { { DW_AT_friend, DW_FORM_ref_udata }, { 0, 0 } }; static AbbrevEntry const abbr_friend = { DW_TAG_friend, NO, attr_friend }; static AttribDesc const attr_inheritance[] = { { DW_AT_type, DW_FORM_ref_udata }, { DW_AT_data_member_location, DW_FORM_block }, { DW_AT_virtuality, DW_FORM_data1 }, { 0, 0 } }; static AbbrevEntry const abbr_inheritance = { DW_TAG_inheritance, NO, attr_inheritance }; static AttribDesc const attr_lexicalblock[] = { { DW_AT_low_pc, DW_FORM_addr }, { DW_AT_high_pc, DW_FORM_addr }, { 0, 0 } }; static AbbrevEntry const abbr_lexicalblock = { DW_TAG_lexical_block, YES, attr_lexicalblock }; static AbbrevEntry const abbr_emptylexicalblock = { DW_TAG_lexical_block, NO, attr_lexicalblock }; static AttribDesc const attr_member[] = { { DW_AT_name, DW_FORM_string }, { DW_AT_type, DW_FORM_ref_udata }, { DW_AT_data_member_location, DW_FORM_block }, { 0, 0 } }; static AttribDesc const attr_member_bitfield[] = { { DW_AT_name, DW_FORM_string }, { DW_AT_type, DW_FORM_ref_udata }, { DW_AT_data_member_location, DW_FORM_block }, { DW_AT_bit_size, DW_FORM_data1 }, { DW_AT_bit_offset, DW_FORM_data1 }, { 0, 0 } }; static AbbrevEntry const abbr_member = { DW_TAG_member, NO, attr_member }; static AbbrevEntry const abbr_member_bitfield = { DW_TAG_member, NO, attr_member_bitfield }; static AbbrevEntry const abbr_pointertype = { DW_TAG_pointer_type, NO, attr_qualtype }; static AttribDesc const attr_proctypeformal[] = { { DW_AT_type, DW_FORM_ref_udata }, { DW_AT_name, DW_FORM_string }, { 0, 0 } }; static AttribDesc const attr_proctypeformal_invented[] = { { DW_AT_type, DW_FORM_ref_udata }, { DW_AT_name, DW_FORM_string }, { DW_AT_artificial, DW_FORM_flag }, { 0, 0 } }; static AttribDesc const attr_proctypeformal_anon[] = { { DW_AT_type, DW_FORM_ref_udata }, { 0, 0 } }; static AttribDesc const attr_proctypeformal_default[] = { { DW_AT_type, DW_FORM_ref_udata }, { DW_AT_name, DW_FORM_string }, { DW_AT_default_value, DW_FORM_indirect }, { 0, 0 } }; static AbbrevEntry const abbr_proctypeformal = { DW_TAG_formal_parameter, NO, attr_proctypeformal }; static AbbrevEntry const abbr_proctypeformal_invented = { DW_TAG_formal_parameter, NO, attr_proctypeformal_invented }; static AbbrevEntry const abbr_proctypeformal_anon = { DW_TAG_formal_parameter, NO, attr_proctypeformal_anon }; static AbbrevEntry const abbr_proctypeformal_default = { DW_TAG_formal_parameter, NO, attr_proctypeformal_default }; static AttribDesc const attr_ptrtomembertype[] = { { DW_AT_containing_type, DW_FORM_ref_udata }, { DW_AT_type, DW_FORM_ref_udata }, { 0, 0 } }; static AbbrevEntry const abbr_ptrtomembertype = { DW_TAG_ptr_to_member_type, NO, attr_ptrtomembertype }; static AbbrevEntry const abbr_referencetype = { DW_TAG_reference_type, NO, attr_qualtype }; static AttribDesc const attr_structtype[] = { { DW_AT_name, DW_FORM_string }, { DW_AT_byte_size, DW_FORM_udata }, { 0, 0 } }; static AttribDesc const attr_structtype_nodata[] = { { DW_AT_name, DW_FORM_string }, { 0, 0 } }; static AttribDesc const attr_structtype_anon[] = { { DW_AT_byte_size, DW_FORM_udata }, { 0, 0 } }; static AbbrevEntry const abbr_structtype = { DW_TAG_structure_type, YES, attr_structtype }; static AbbrevEntry const abbr_structtype_nodata = { DW_TAG_structure_type, YES, attr_structtype_nodata }; static AbbrevEntry const abbr_structtype_anon = { DW_TAG_structure_type, YES, attr_structtype_anon }; static AbbrevEntry const abbr_structtype_nodata_anon = { DW_TAG_structure_type, YES, attr_null }; static AbbrevEntry const abbr_structtype_fref = { DW_TAG_structure_type, NO, attr_structtype_nodata }; static AttribDesc const attr_subprogram[] = { { DW_AT_low_pc, DW_FORM_addr }, { DW_AT_proc_body, DW_FORM_udata }, { DW_AT_high_pc, DW_FORM_addr }, { DW_AT_name, DW_FORM_string }, { DW_AT_external, DW_FORM_flag }, { DW_AT_type, DW_FORM_ref_udata }, { 0, 0 } }; static AttribDesc const attr_subprogram_void[] = { { DW_AT_low_pc, DW_FORM_addr }, { DW_AT_proc_body, DW_FORM_udata }, { DW_AT_high_pc, DW_FORM_addr }, { DW_AT_name, DW_FORM_string }, { DW_AT_external, DW_FORM_flag }, { 0, 0 } }; static AttribDesc const attr_subprogram_ref[] = { { DW_AT_low_pc, DW_FORM_addr }, { DW_AT_proc_body, DW_FORM_udata }, { DW_AT_high_pc, DW_FORM_addr }, { DW_AT_specification, DW_FORM_ref_udata }, { 0, 0 } }; static AttribDesc const attr_procdecl[] = { { DW_AT_name, DW_FORM_string }, { DW_AT_declaration, DW_FORM_flag }, { DW_AT_type, DW_FORM_ref_udata }, { DW_AT_external, DW_FORM_flag }, { 0, 0 } }; static AttribDesc const attr_procdecl_void[] = { { DW_AT_name, DW_FORM_string }, { DW_AT_declaration, DW_FORM_flag }, { DW_AT_external, DW_FORM_flag }, { 0, 0 } }; static AttribDesc const attr_procdecl_virtual[] = { { DW_AT_name, DW_FORM_string }, { DW_AT_declaration, DW_FORM_flag }, { DW_AT_type, DW_FORM_ref_udata }, { DW_AT_virtuality, DW_FORM_data1 }, { DW_AT_vtable_elem_location, DW_FORM_data1 }, { 0, 0 } }; static AttribDesc const attr_procdecl_virtual_void[] = { { DW_AT_name, DW_FORM_string }, { DW_AT_declaration, DW_FORM_flag }, { DW_AT_virtuality, DW_FORM_data1 }, { DW_AT_vtable_elem_location, DW_FORM_data1 }, { 0, 0 } }; static AbbrevEntry const abbr_subprogram = { DW_TAG_subprogram, YES, attr_subprogram }; static AbbrevEntry const abbr_subprogram_void = { DW_TAG_subprogram, YES, attr_subprogram_void }; static AbbrevEntry const abbr_subprogram_ref = { DW_TAG_subprogram, YES, attr_subprogram_ref }; static AbbrevEntry const abbr_procdecl = { DW_TAG_subprogram, YES, attr_procdecl }; static AbbrevEntry const abbr_procdecl_void = { DW_TAG_subprogram, YES, attr_procdecl_void }; static AbbrevEntry const abbr_procdecl_virtual = { DW_TAG_subprogram, YES, attr_procdecl_virtual }; static AbbrevEntry const abbr_procdecl_virtual_void = { DW_TAG_subprogram, YES, attr_procdecl_virtual_void }; static AttribDesc const attr_subroutinetype[] = { { DW_AT_type, DW_FORM_ref_udata }, { 0, 0 } }; static AbbrevEntry const abbr_subroutinetype = { DW_TAG_subroutine_type, YES, attr_subroutinetype }; static AbbrevEntry const abbr_subroutinetype_void = { DW_TAG_subroutine_type, YES, attr_null }; static AttribDesc const attr_typedef[] = { { DW_AT_name, DW_FORM_string }, { DW_AT_type, DW_FORM_ref_udata }, { 0, 0 } }; static AbbrevEntry const abbr_typedef = { DW_TAG_typedef, NO, attr_typedef }; static AttribDesc const attr_uniontype[] = { { DW_AT_name, DW_FORM_string }, { DW_AT_byte_size, DW_FORM_udata }, { 0, 0 } }; static AttribDesc const attr_uniontype_anon[] = { { DW_AT_byte_size, DW_FORM_udata }, { 0, 0 } }; static AttribDesc const attr_uniontype_nodata[] = { { DW_AT_name, DW_FORM_string }, { 0, 0 } }; static AbbrevEntry const abbr_uniontype = { DW_TAG_union_type, YES, attr_uniontype }; static AbbrevEntry const abbr_uniontype_anon = { DW_TAG_union_type, YES, attr_uniontype_anon }; static AbbrevEntry const abbr_uniontype_nodata = { DW_TAG_union_type, YES, attr_uniontype_nodata }; static AbbrevEntry const abbr_uniontype_fref = { DW_TAG_union_type, NO, attr_uniontype_nodata }; static AbbrevEntry const abbr_unspecifiedparameters = { DW_TAG_unspecified_parameters, NO, attr_null }; static AttribDesc const attr_variable[] = { { DW_AT_name, DW_FORM_string }, { DW_AT_type, DW_FORM_ref_udata }, { DW_AT_location, DW_FORM_block }, { 0, 0 } }; static AttribDesc const attr_variable_extern[] = { { DW_AT_name, DW_FORM_string }, { DW_AT_type, DW_FORM_ref_udata }, { DW_AT_location, DW_FORM_block }, { DW_AT_external, DW_FORM_flag }, { 0, 0 } }; static AbbrevEntry const abbr_variable = { DW_TAG_variable, NO, attr_variable }; static AbbrevEntry const abbr_formalparameter = { DW_TAG_formal_parameter, NO, attr_variable }; static AbbrevEntry const abbr_variable_extern = { DW_TAG_variable, NO, attr_variable_extern }; static AbbrevEntry const abbr_volatiletype = { DW_TAG_volatile_type, NO, attr_qualtype }; static AbbrevEntry const * const abbrevlist_c[] = { &abbr_null, &abbr_arraybound, &abbr_arraybound_open, &abbr_arraytype, &abbr_basetype, &abbr_compileunit, &abbr_compileunit_nostmt, &abbr_compileunit_nocode, &abbr_consttype, &abbr_enum, &abbr_enum_anon, &abbr_enumerator, &abbr_enumerator_signed, &abbr_formalparameter, &abbr_lexicalblock, &abbr_emptylexicalblock, &abbr_member, &abbr_member_bitfield, &abbr_pointertype, &abbr_proctypeformal, &abbr_proctypeformal_anon, &abbr_referencetype, &abbr_structtype, &abbr_structtype_nodata, &abbr_structtype_anon, &abbr_structtype_nodata_anon, &abbr_structtype_fref, &abbr_subprogram, &abbr_subprogram_void, &abbr_subprogram_ref, &abbr_procdecl, &abbr_procdecl_void, &abbr_subroutinetype, &abbr_subroutinetype_void, &abbr_typedef, &abbr_uniontype, &abbr_uniontype_anon, &abbr_uniontype_fref, &abbr_unspecifiedparameters, &abbr_variable, &abbr_variable_extern, &abbr_volatiletype, NULL }; static AbbrevEntry const * const abbrevlist_cpp[] = { &abbr_null, &abbr_arraybound, &abbr_arraybound_open, &abbr_arraytype, &abbr_basetype, &abbr_classtype, &abbr_classtype_nodata, &abbr_classtype_anon, &abbr_classtype_nodata_anon, &abbr_classtype_fref, &abbr_compileunit, &abbr_compileunit_nostmt, &abbr_compileunit_nocode, &abbr_consttype, &abbr_enum, &abbr_enum_anon, &abbr_enumerator, &abbr_enumerator_signed, &abbr_formalparameter, &abbr_friend, &abbr_inheritance, &abbr_lexicalblock, &abbr_emptylexicalblock, &abbr_member, &abbr_member_bitfield, &abbr_pointertype, &abbr_ptrtomembertype, &abbr_proctypeformal, &abbr_proctypeformal_invented, &abbr_proctypeformal_anon, &abbr_proctypeformal_default, &abbr_referencetype, &abbr_structtype, &abbr_structtype_nodata, &abbr_structtype_anon, &abbr_structtype_nodata_anon, &abbr_structtype_fref, &abbr_subprogram, &abbr_subprogram_void, &abbr_subprogram_ref, &abbr_procdecl, &abbr_procdecl_void, &abbr_procdecl_virtual, &abbr_procdecl_virtual_void, &abbr_subroutinetype, &abbr_subroutinetype_void, &abbr_typedef, &abbr_uniontype, &abbr_uniontype_anon, &abbr_uniontype_fref, &abbr_unspecifiedparameters, &abbr_variable, &abbr_variable_extern, &abbr_volatiletype, NULL }; static uint8 const block_reg[] = { 1, DW_FORM_data1, 0 }; static uint8 const block_extern[] = { 2, DW_FORM_data1, DW_FORM_addr, 0 }; static uint8 const block_auto_fb[] = { 4, DW_FORM_data1, DW_FORM_data1, DW_FORM_sdata, DW_FORM_data1, 0 }; static uint8 const block_auto[] = { 2, DW_FORM_data1, DW_FORM_sdata, 0 }; static uint8 const block_mem[] = { 2, DW_FORM_data1, DW_FORM_udata, 0 }; #define ATTRIBBUFSIZE 20 static uint32 Dw_WriteLEB128_U_3(uint32 u, uint32 offset) { uint8 b[3]; u &= ~0x80000000; b[0] = ((Uint)u & 0x7f) | 0x80; u = u >> 7; b[1] = ((Uint)u & 0x7f) | 0x80; u = u >> 7; b[2] = ((Uint)u & 0x7f); if ((u & ~0x7f) != 0) syserr("Dw_WriteLEB128_U_3"); return Dw_WriteBN(b, 3, offset); } static uint32 Dw_WriteLEB128_U(uint32 u, uint32 offset) { uint8 b[5]; uint32 n = 0; for (; ; n++) { b[n] = (Uint)u & 0x7f; u = u >> 7; if (u == 0) break; b[n] |= 0x80; } return Dw_WriteBN(b, ++n, offset); } static uint32 Dw_WriteLEB128_S(int32 u, uint32 offset) { uint8 b[5]; uint32 n = 0; for (; ; n++) { b[n] = (Uint)u & 0x7f; u = signed_rightshift_(u, 7); if (b[n] & 0x40) { if (u == -1) break; } else if (u == 0) break; b[n] |= 0x80; } return Dw_WriteBN(b, ++n, offset); } static uint32 Dw_SizeLEB128_U(uint32 u) { return u < 0x80 ? 1 : u < 0x80 << 7 ? 2 : u < 0x80 << 14 ? 3 : u < 0x80 << 21 ? 4 : 5; } static uint32 Dw_SizeLEB128_S(int32 u) { uint32 n = 1; for (; ; n++) { int32 k = u & 0x7f; u = signed_rightshift_(u, 7); if (k & 0x40) { if (u == -1) break; } else if (u == 0) break; } return n; } typedef struct { Uint form; uint32 i; void const *p; } AttribVal; #define blocksize_(p) ((p) & 0xff) #define blockix_(p) ((p) >> 8) static uint32 Dw_2_BlockArgs(AttribVal const *w, Uint n, uint8 const *block_mem) { uint32 size = 0; for (w += n; ; w++) switch (*++block_mem) { case 0: return size | ((uint32)n << 8); case DW_FORM_data1: size += 1; break; case DW_FORM_data2: size += 2; break; case DW_FORM_addr: case DW_FORM_data4: size += 4; break; case DW_FORM_udata: size += Dw_SizeLEB128_U(w->i); break; case DW_FORM_sdata: size += Dw_SizeLEB128_S(w->i); break; } } static AbbrevEntry const *Dw_2_ItemEntry(Dw_ItemList const *p, AttribVal *w) { switch (debsort_(p)) { case DW_TAG_compile_unit: w[0].p = sect_name_(p); w[1].p = version_banner(); w[2].i = (LanguageIsCPlusPlus) ? LANG_C_PLUS_PLUS : LANG_C89; if (dw_baseseg.len == 0) return &abbr_compileunit_nocode; else { w[3].i = 0; w[3].p = sect_codeseg_(p); w[4].i = dw_baseseg.len; w[4].p = sect_codeseg_(p); if (dw_coord_p == NULL) return &abbr_compileunit_nostmt; else { w[5].i = 0; w[5].p = dw_lineinfo_sym; return &abbr_compileunit; } } case DW_TAG_subprogram: w[0].i = proc_entry_(p); w[0].p = proc_codeseg_(p); w[1].i = proc_body_(p) - proc_entry_(p); w[2].i = high_pc_(p); w[2].p = proc_codeseg_(p); if (proc_decl_(p) != NULL) { w[3].i = dbgloc_(proc_decl_(p)); return &abbr_subprogram_ref; } w[3].p = Dw_Unmangle(proc_name_(p)); w[4].i = proc_global_(p); { Dw_ItemList *restype = proc_type_(p); if (is_void_type_(restype)) return &abbr_subprogram_void; else { w[5].i = dbgloc_(restype); return &abbr_subprogram; } } case DW_TAG_procdecl: { uint32 sort = 0, i = 2; static AbbrevEntry const * const pdsort[] = { &abbr_procdecl_void, &abbr_procdecl, &abbr_procdecl_virtual_void, &abbr_procdecl_virtual }; w[0].p = Dw_Unmangle(procdecl_name_(p)); w[1].i = YES; if (!is_void_type_(procdecl_type_(p))) { w[i++].i = dbgloc_(procdecl_type_(p)); sort |= 1; } if (procdecl_stg_(p) & bitofstg_(s_virtual)) { w[i++].i = DW_VIRTUALITY_virtual; w[i++].i = procdecl_voffset_(p); sort |= 2; } else w[i++].i = procdecl_global_(p); return pdsort[sort]; } case DW_TAG_unspecified_parameters: return &abbr_unspecifiedparameters; case DW_TAG_subroutine_type: { Dw_ItemList *restype = proctype_type_(p); if (is_void_type_(restype)) return &abbr_subroutinetype_void; else { w[0].i = dbgloc_(restype); return &abbr_subroutinetype; } } case DW_TAG_proctype_formal: w[0].i = dbgloc_(formal_type_(p)); if (formal_name_(p) == NULL) return &abbr_proctypeformal_anon; else { Expr *dflt = formal_defltexpr_(p); w[1].p = symname_(formal_name_(p)); if (formal_invented_(p)) { w[2].i = YES; return &abbr_proctypeformal_invented; } if (dflt == NULL) return &abbr_proctypeformal; switch (h0_(dflt)) { case s_integer: w[2].form = DW_FORM_udata; w[2].i = intval_(dflt); break; case s_string: w[2].form = DW_FORM_string_expr; w[2].p = ((String *)dflt)->strseg; break; case s_floatcon: if (mcrepofexpr(dflt) & MCR_SIZE_MASK < 8) { w[2].form = DW_FORM_data4; w[2].i = ((FloatCon *)dflt)->floatbin.fb.val; } else { w[2].form = DW_FORM_data8; w[2].p = ((FloatCon *)dflt)->floatbin.irep; } break; default: w[2].form = DW_FORM_ref_udata; w[2].i = dbgloc_(formal_defltfn_(p)); break; } return &abbr_proctypeformal_default; } case DW_TAG_ptr_to_member_type: w[0].i = dbgloc_(ptrtomem_container_(p)); w[1].i = dbgloc_(ptrtomem_type_(p)); return &abbr_ptrtomembertype; case DW_TAG_typedef: w[0].p = type_name_(p); w[1].i = dbgloc_(type_type_(p)); return &abbr_typedef; case DW_TAG_lexical_block: w[0].i = startscope_codeaddr_(p); w[0].p = startscope_codeseg_(p); w[1].i = endscope_codeaddr_(startscope_end_(p)); w[1].p = startscope_codeseg_(p); if (debsort_(cdr_(p)) == DW_TAG_end_lexical_block) return &abbr_emptylexicalblock; else return &abbr_lexicalblock; case DW_TAG_ignore: case DW_TAG_end_lexical_block: case DW_TAG_endproc: return NULL; case DW_TAG_enumerator: w[0].p = enumerator_name_(p); w[1].i = enumerator_val_(p); return &abbr_enumerator; case DW_TAG_enumeration_type: if (enum_name_(p) != NULL) { w[0].p = enum_name_(p); w[1].i = enum_size_(p); return &abbr_enum; } else { w[1].i = enum_size_(p); return &abbr_enum_anon; } case TAG_padding: /* null entry to terminate sibling chains */ return &abbr_null; case DW_TAG_member: w[0].p = member_name_(p); w[1].i = dbgloc_(member_type_(p)); w[2].p = block_mem; { Uint n = ATTRIBBUFSIZE - block_mem[0]; w[n].i = DW_OP_plus_uconst; w[n+1].i = member_offset_(p); w[2].i = Dw_2_BlockArgs(w, n, block_mem); } if (member_bsize_(p) == 0) return &abbr_member; else { w[3].i = member_bsize_(p); w[4].i = member_boffset_(p); return &abbr_member_bitfield; } case DW_TAG_variable: case DW_TAG_formal_parameter: { Uint n; uint8 const *b; w[0].p = symname_(var_sym_(p)); w[1].i = dbgloc_(var_type_(p)); switch (var_stgclass_(p)) { case Stg_Extern: case Stg_Static: b = block_extern; n = ATTRIBBUFSIZE - b[0]; w[n].i = DW_OP_addr; { Symstr *sym = var_base_(p).sym; obj_symref(sym, symext_(sym) == NULL ? xr_data|xr_weak : xr_data, 0); w[n+1].i = 0; w[n+1].p = sym; } break; case Stg_Reg: case Stg_ArgReg: if (var_base_(p).r == R_NOFPREG) return NULL; b = block_reg; n = ATTRIBBUFSIZE - b[0]; w[n].i = DW_OP_REG0 + var_loc_(p); break; case Stg_Auto: case Stg_ArgAuto: b = block_auto; n = ATTRIBBUFSIZE - b[0]; w[n].i = DW_OP_BREG0 + var_base_(p).r; w[n+1].i = var_loc_(p); break; default: syserr("Dw_2_ItemEntry var stgclass %d", var_stgclass_(p)); n = 0; b = NULL; } w[2].p = b; w[2].i = Dw_2_BlockArgs(w, n, b); } if (var_stgclass_(p) == Stg_Extern) { w[3].i = YES; return &abbr_variable_extern; } else return (debsort_(p) == DW_TAG_formal_parameter) ? &abbr_formalparameter : &abbr_variable; case DW_TAG_base_type: switch (basetype_typecode_(p)) { case FT_signed_char: w[0].i = 1; w[1].i = DW_ATE_signed; break; case FT_unsigned_char: w[0].i = 1; w[1].i = DW_ATE_unsigned; break; case FT_signed_short: w[0].i = sizeof_short; w[1].i = DW_ATE_signed; break; case FT_unsigned_short: w[0].i = sizeof_short; w[1].i = DW_ATE_unsigned; break; case FT_signed_integer: w[0].i = sizeof_int; w[1].i = DW_ATE_signed; break; case FT_unsigned_integer: w[0].i = sizeof_int; w[1].i = DW_ATE_unsigned; break; case FT_signed_long: w[0].i = sizeof_long; w[1].i = DW_ATE_signed; break; case FT_signed_long_long: w[0].i = sizeof_longlong; w[1].i = DW_ATE_signed; break; case FT_unsigned_long: w[0].i = sizeof_long; w[1].i = DW_ATE_unsigned; break; case FT_unsigned_long_long:w[0].i = sizeof_longlong; w[1].i = DW_ATE_unsigned; break; case FT_float: w[0].i = sizeof_float; w[1].i = DW_ATE_float; break; case FT_dbl_prec_float: w[0].i = sizeof_double; w[1].i = DW_ATE_float; break; case FT_void: w[0].i = 0; w[1].i = DW_ATE_signed; break; default: syserr("Dw_2_ItemEntry basetype %d", basetype_typecode_(p)); } return &abbr_basetype; case DW_TAG_pointer_type: w[0].i = dbgloc_(qualtype_qualifiedtype_(p)); return &abbr_pointertype; case DW_TAG_const_type: w[0].i = dbgloc_(qualtype_qualifiedtype_(p)); return &abbr_consttype; case DW_TAG_volatile_type: w[0].i = dbgloc_(qualtype_qualifiedtype_(p)); return &abbr_volatiletype; case DW_TAG_reference_type: w[0].i = dbgloc_(qualtype_qualifiedtype_(p)); return &abbr_referencetype; case DW_TAG_array_type: w[0].i = dbgloc_(array_basetype_(p)); return &abbr_arraytype; case DW_TAG_array_bound: if (arraybound_open_(p)) return &abbr_arraybound_open; else { w[0].i = arraybound_upperbound_(p); return &abbr_arraybound; } case DW_TAG_fref: w[0].p = struct_name_(p); if (struct_undefsort_(p) == DW_TAG_class_type) return &abbr_classtype_fref; else if (struct_undefsort_(p) == DW_TAG_structure_type) return &abbr_structtype_fref; else return &abbr_uniontype_fref; case DW_TAG_class_type: if (struct_name_(p) != NULL) { if (struct_size_(p) == 0) return &abbr_classtype_nodata_anon; else { w[0].i = struct_size_(p); return &abbr_classtype_anon; } } else { w[0].p = struct_name_(p); if (struct_size_(p) == 0) return &abbr_classtype_nodata; else { w[1].i = struct_size_(p); return &abbr_classtype; } } case DW_TAG_union_type: if (struct_name_(p) == NULL) { w[0].i = struct_size_(p); return &abbr_uniontype_anon; } else { w[0].p = struct_name_(p); if (struct_size_(p) == 0) return &abbr_uniontype_nodata; else { w[1].i = struct_size_(p); return &abbr_uniontype; } } case DW_TAG_structure_type: if (struct_name_(p) == NULL) { if (struct_size_(p) == 0) return &abbr_structtype_nodata_anon; else { w[0].i = struct_size_(p); return &abbr_structtype_anon; } } else { w[0].p = struct_name_(p); if (struct_size_(p) == 0) return &abbr_structtype_nodata; else { w[1].i = struct_size_(p); return &abbr_structtype; } } case DW_TAG_inheritance: w[0].i = dbgloc_(inherit_type_(p)); { Uint n = ATTRIBBUFSIZE - block_mem[0]; w[n].i = DW_OP_plus_uconst; w[n+1].i = inherit_offset_(p); w[1].i = Dw_2_BlockArgs(w, n, block_mem); w[1].p = block_mem; } w[2].i = inherit_virt_(p) ? DW_VIRTUALITY_virtual : DW_VIRTUALITY_none; return &abbr_inheritance; default: syserr("Dw_2_ItemEntry %d", debsort_(p)); return NULL; } } static Uint Dw_2_AbbrevLookup(AbbrevEntry const *abbrev) { Uint i; AbbrevEntry const * const *table = LanguageIsCPlusPlus ? abbrevlist_cpp : abbrevlist_c; for (i = 0; table[i] != NULL; i++) if (table[i] == abbrev) return i; syserr("Dw_2_AbbrevLookup %p (%d)", abbrev, abbrev->tag); return 0; } static uint32 Dw_2_InfoItemSize(Dw_ItemList const *p, AttribVal *w) { AbbrevEntry const *abbrev = Dw_2_ItemEntry(p, w); if (abbrev == NULL) return 0; { Uint abbrevindex = Dw_2_AbbrevLookup(abbrev); Uint i; uint32 size = Dw_SizeLEB128_U(abbrevindex); for (i = 0; ; i++) { Uint form = abbrev->attribs[i].form; indirect: switch (form) { case 0: return size; case DW_FORM_indirect: form = w[i].form; size += Dw_SizeLEB128_U(form); if (form == DW_FORM_indirect) syserr("Dw_2_InfoItemSize indirect indirect"); goto indirect; case DW_FORM_flag: case DW_FORM_data1: size += 1; break; case DW_FORM_data2: size += 2; break; case DW_FORM_tref: case DW_FORM_addr: case DW_FORM_data4: size += 4; break; case DW_FORM_data8: size += 8; break; case DW_FORM_ref_udata:if (w[i].i == 0 /* forward reference before writing */ || (w[i].i & 0x80000000)) /* forward reference after writing */ size += 3; else size += Dw_SizeLEB128_U(w[i].i); break; case DW_FORM_udata: size += Dw_SizeLEB128_U(w[i].i); break; case DW_FORM_string: size += (uint32)strlen((char const *)w[i].p)+1; break; case DW_FORM_block: size += blocksize_(w[i].i) + Dw_SizeLEB128_U(blocksize_(w[i].i)); break; case DW_FORM_string_expr: { StringSegList const *p = (StringSegList const *)w[i].p; for (; p != NULL; p = p->strsegcdr) size += p->strseglen; size += 1; } break; default: syserr("Dw_2_InfoItemSize form %d", abbrev->attribs[i].form); } } } } static void Dw_RoundUp(uint32 offset) { if ((offset & 3) != 0) { uint32 w = 0; obj_writedebug(&w, 4 - (offset & 3)); } } void Dw_2_WriteInfo(void) { Dw_ItemList *p; uint32 infosize, offset; AttribVal w[ATTRIBBUFSIZE]; dw_xrefs = NULL; obj_startdebugarea(Dwarf2DebugAreaName); for (infosize = 11, p = dw_list; p != NULL; p = cdr_(p)) { uint32 n = Dw_2_InfoItemSize(p, w); dbgloc_(p) = n == 0 ? 0 : infosize; infosize += n; } for (p = dw_list; p != NULL; p = cdr_(p)) { if (dbgloc_(p) != 0) dbgloc_(p) |= 0x80000000; } offset = Dw_WriteW(infosize-4, 0); offset = Dw_WriteH(2, offset); offset = Dw_WriteW_Relocated(0, dw_abbrev_sym, offset); offset = Dw_WriteB(4, offset); for (p = dw_list; p != NULL; p = cdr_(p)) { AbbrevEntry const *abbrev = Dw_2_ItemEntry(p, w); if (abbrev == NULL) continue; { Uint abbrevindex = Dw_2_AbbrevLookup(abbrev); Uint i; dbgloc_(p) &= ~0x80000000; if (offset != dbgloc_(p)) syserr("dw_2_writeinfo %lx != %lx", offset, dbgloc_(p)); offset = Dw_WriteLEB128_U(abbrevindex, offset); for (i = 0; ; i++) if (abbrev->attribs[i].form == 0) break; else { Uint form = abbrev->attribs[i].form; indirect: switch (form) { default: syserr("Dw_2_WriteInfo from %d", abbrev->attribs[i].form); case DW_FORM_flag: case DW_FORM_data1: offset = Dw_WriteB(w[i].i, offset); break; case DW_FORM_data2: offset = Dw_WriteH(w[i].i, offset); break; case DW_FORM_data4: offset = Dw_WriteW(w[i].i, offset); break; case DW_FORM_data8: offset = Dw_WriteL((uint32 const *)w[i].p, offset); break; case DW_FORM_ref_udata:if (w[i].i & 0x80000000) offset = Dw_WriteLEB128_U_3(w[i].i, offset); else offset = Dw_WriteLEB128_U(w[i].i, offset); break; case DW_FORM_udata: offset = Dw_WriteLEB128_U(w[i].i, offset); break; case DW_FORM_string: offset = Dw_WriteInlineString((char const *)w[i].p, offset); break; case DW_FORM_tref: case DW_FORM_addr: offset = Dw_WriteW_Relocated(w[i].i, (Symstr const *)w[i].p, offset); break; case DW_FORM_indirect: { uint32 n = form = w[i].form; if (n == DW_FORM_string_expr) n = DW_FORM_string; offset = Dw_WriteLEB128_U(n, offset); goto indirect; } case DW_FORM_string_expr: { StringSegList const *p = (StringSegList const *)w[i].p; for (; p != NULL; p = p->strsegcdr) offset = Dw_WriteBN((uint8 *)p->strsegbase, p->strseglen, offset); offset = Dw_WriteB(0, offset); } break; case DW_FORM_block: offset = Dw_WriteLEB128_U(blocksize_(w[i].i), offset); { uint8 const *p = (uint8 const *)w[i].p+1; uint32 j = blockix_(w[i].i); for (; *p != 0; p++, j++) switch (*p) { case DW_FORM_data1: offset = Dw_WriteB(w[j].i, offset); break; case DW_FORM_data2: offset = Dw_WriteH(w[j].i, offset); break; case DW_FORM_data4: offset = Dw_WriteW(w[j].i, offset); break; case DW_FORM_addr: offset = Dw_WriteW_Relocated(w[j].i, (Symstr const *)w[j].p, offset); break; case DW_FORM_udata: offset = Dw_WriteLEB128_U(w[j].i, offset); break; case DW_FORM_sdata: offset = Dw_WriteLEB128_S(w[j].i, offset); break; default: syserr("Dw_2_WriteInfo block op %d", *p); } } } } } } Dw_RoundUp(offset); obj_enddebugarea(Dwarf2DebugAreaName, dw_xrefs); } void Dw_2_WriteAbbrevs(void) { AbbrevEntry const * const *p = LanguageIsCPlusPlus ? abbrevlist_cpp : abbrevlist_c; Uint i; uint32 offset = 0; obj_startdebugarea(AbbrevAreaName); for (i = 1; p[i] != NULL; i++) { AbbrevEntry const *abbr = p[i]; offset = Dw_WriteLEB128_U(i, offset); offset = Dw_WriteLEB128_U(abbr->tag, offset); offset = Dw_WriteB(abbr->children, offset); { AttribDesc const *attr = abbr->attribs; for (; ; attr++) { offset = Dw_WriteLEB128_U(attr->attrib, offset); offset = Dw_WriteLEB128_U(attr->form == DW_FORM_tref ? DW_FORM_data4 : attr->form, offset); if (attr->attrib == 0) break; } } } offset = Dw_WriteLEB128_U(0, offset); Dw_RoundUp(offset); obj_enddebugarea(AbbrevAreaName, NULL); } void Dw_2_WriteMacros(void) { Dw_MacroList *p; uint32 offset; dw_xrefs = NULL; obj_startdebugarea(MacroAreaName); for (offset = 0, p = dw_macrolist; p != NULL; p = cdr_(p)) { offset = Dw_WriteB(p->sort, offset); switch (p->sort) { case DW_MACINFO_define: case DW_MACINFO_undef: offset = Dw_WriteLEB128_U(p->fl.l, offset); offset = Dw_WriteInlineString(p->data.s, offset); break; case DW_MACINFO_start_file: offset = Dw_WriteLEB128_U(p->fl.l, offset); offset = Dw_WriteLEB128_U(p->data.i, offset); break; case DW_MACINFO_end_file: break; } } offset = Dw_WriteB(0, offset); Dw_RoundUp(offset); obj_enddebugarea(MacroAreaName, dw_xrefs); } #ifdef TARGET_HAS_HALFWORD_INSTRUCTIONS # define AddressQuantum 2 #else # define AddressQuantum 4 #endif static uint8 const dw_lns_operands[DW_LNS_LAST] = DW_LNS_OPERANDS; static uint32 Dw_Write_LNS_OpU(Uint op, uint32 operand, uint32 offset) { offset = Dw_WriteB(op, offset); return Dw_WriteLEB128_U(operand, offset); } static uint32 Dw_Write_LNS_OpS(Uint op, int32 operand, uint32 offset) { offset = Dw_WriteB(op, offset); return Dw_WriteLEB128_S(operand, offset); } #define LNS_RANGE 6 #define LNS_CODERANGE ((255-DW_LNS_LAST) / LNS_RANGE) #define DW_LNS_Special_Op(linediff, codediff) \ ((Uint)((linediff) + LNS_RANGE * (codediff) + DW_LNS_LAST + 1)) #define LNS_SPECIAL_MAX_PC \ (DW_LNS_Special_Op(0, LNS_CODERANGE) <= 255 ? LNS_CODERANGE : LNS_CODERANGE-1) #define CanUseSpecialOp(linediff, codediff) \ ((codediff) < LNS_CODERANGE \ || ((codediff) == LNS_CODERANGE \ && DW_LNS_Special_Op((linediff), (codediff)) <= 255)) #define Write_LNS_OpU(op, arg, offset, write) \ ((write) ? Dw_Write_LNS_OpU(op, arg, offset) : (offset) + 1 + Dw_SizeLEB128_U(arg)) #define Write_LNS_OpS(op, arg, offset, write) \ ((write) ? Dw_Write_LNS_OpS(op, arg, offset) : (offset) + 1 + Dw_SizeLEB128_S(arg)) #define Write_LNS_NoOp(op, offset, write) \ ((write) ? Dw_WriteB(op, offset) : (offset) + 1) #define WriteB(b, offset, write) \ ((write) ? Dw_WriteB(b, offset) : (offset) + 1) #define WriteLEB128_U(n, offset, write) \ ((write) ? Dw_WriteLEB128_U(n, offset) : (offset) + Dw_SizeLEB128_U(n)) #define WriteW_Relocated(n, sym, offset, write) \ ((write) ? Dw_WriteW_Relocated(n, sym, offset) : (offset) + 4) static uint32 Dw_2_ProcessLineList(uint32 offset, bool write) { uint32 codeaddr = 0; Symstr *codeseg = NULL; int32 lineno = 1, column = 0; Dw_FileList *fp = NULL; Dw_FileCoord *lp; bool changed = NO; for (lp = dw_coord_p; lp != NULL; lp = cdr_(lp)) { int32 linediff = (int32)lp->line - lineno; uint32 codediff = (lp->codeaddr - codeaddr) / AddressQuantum; if (fp != lp->file) { offset = Write_LNS_OpU(DW_LNS_set_file, lp->file->index, offset, write); fp = lp->file; } if (lp->col != column) { offset = Write_LNS_OpU(DW_LNS_set_column, lp->col, offset, write); changed = YES; column = lp->col; } if (codeseg != lp->codeseg) { offset = WriteB(0, offset, write); /* extended opcode escape */ offset = WriteLEB128_U(5, offset, write); /* length */ offset = WriteB(DW_LNE_set_address, offset, write); offset = WriteW_Relocated(lp->codeaddr, lp->codeseg, offset, write); codeseg = lp->codeseg; codeaddr = lp->codeaddr; if (linediff != 0) { lineno += linediff; if (linediff > 0 && linediff < LNS_RANGE) { offset = Write_LNS_NoOp(DW_LNS_Special_Op(linediff, 0), offset, write); changed = NO; continue; } offset = Write_LNS_OpS(DW_LNS_advance_line, linediff, offset, write); } offset = Write_LNS_NoOp(DW_LNS_copy, offset, write); changed = NO; continue; } if (linediff < 0 || linediff >= LNS_RANGE) { offset = Write_LNS_OpS(DW_LNS_advance_line, linediff, offset, write); lineno += linediff; changed = YES; linediff = 0; } if (codediff > LNS_SPECIAL_MAX_PC && CanUseSpecialOp(linediff, codediff - LNS_SPECIAL_MAX_PC)) { offset = Write_LNS_NoOp(DW_LNS_const_add_pc, offset, write); codeaddr += LNS_SPECIAL_MAX_PC * AddressQuantum; codediff -= LNS_SPECIAL_MAX_PC; changed = YES; } if (!CanUseSpecialOp(linediff, codediff)) { offset = Write_LNS_OpU(DW_LNS_advance_pc, codediff, offset, write); codeaddr += codediff * AddressQuantum; codediff = 0; changed = YES; } if (linediff == 0 && codediff == 0) { if (changed) offset = Write_LNS_NoOp(DW_LNS_copy, offset, write); } else { lineno += linediff; codeaddr += codediff * AddressQuantum; offset = Write_LNS_NoOp(DW_LNS_Special_Op(linediff, codediff), offset, write); } changed = NO; if (cdr_(lp) == NULL || cdr_(lp)->codeseg != codeseg) { lineno = 1; column = 0; offset = WriteB(0, offset, write); /* extended opcode escape */ offset = WriteLEB128_U(1, offset, write); /* length */ offset = WriteB(DW_LNE_end_sequence, offset, write); } } return offset; } void Dw_2_WriteLineinfo(void) { uint32 offset, headerlen = 17+DW_LNS_LAST; uint32 infosize; Dw_FileList *fp; Dw_PathList *pp; if (dw_coord_p != NULL) { dw_coord_sentinel.codeseg = bindsym_(codesegment); *dw_coord_q = &dw_coord_sentinel; dw_coord_sentinel = *(Dw_FileCoord *)dw_coord_q; dw_coord_sentinel.cdr = NULL; dw_coord_sentinel.codeaddr = (LanguageIsCPlusPlus) ? dw_mapped_codebase+dw_mapped_codep : codebase+codep; } dw_pathlist = (Dw_PathList *)dreverse((List *)dw_pathlist); for (pp = dw_pathlist; pp != NULL; pp = cdr_(pp)) headerlen += (uint32)strlen(pp->name) + 1; dw_filelist = (Dw_FileList *)dreverse((List *)dw_filelist); if (dw_filelist->index == 0) dw_filelist = cdr_(dw_filelist); for (fp = dw_filelist; fp != NULL; fp = cdr_(fp)) { char const *name = fp->filename; Uint ix = 0; if (fp->dir != NULL) { name += fp->dir->len; ix = fp->dir->index; } headerlen += (uint32)strlen(name) + 1 + Dw_SizeLEB128_U(ix) + Dw_SizeLEB128_U(fp->timestamp) + Dw_SizeLEB128_U(fp->filelength); } infosize = Dw_2_ProcessLineList(headerlen, NO); dw_xrefs = NULL; obj_startdebugarea(Dwarf2LineInfoAreaName); offset = 0; offset = Dw_WriteW(infosize - 4, offset); /* end of area, relative to here */ offset = Dw_WriteH(1, offset); offset = Dw_WriteW(headerlen - 10, offset); /* end of header, relative to here */ offset = Dw_WriteB(AddressQuantum, offset); offset = Dw_WriteB(1, offset); /* all entries start a statement */ offset = Dw_WriteB(0, offset); /* line-base */ offset = Dw_WriteB(LNS_RANGE, offset); offset = Dw_WriteB(DW_LNS_LAST+1, offset); offset = Dw_WriteBN(dw_lns_operands, DW_LNS_LAST, offset); for (pp = dw_pathlist; pp != NULL; pp = cdr_(pp)) offset = Dw_WriteInlineString(pp->name, offset); offset = Dw_WriteB(0, offset); /* include directories */ for (fp = dw_filelist; fp != NULL; fp = cdr_(fp)) { char const *name = fp->filename; Uint ix = 0; if (fp->dir != NULL) { name += fp->dir->len; ix = fp->dir->index; } offset = Dw_WriteInlineString(name, offset); offset = Dw_WriteLEB128_U(ix, offset); offset = Dw_WriteLEB128_U(fp->timestamp, offset); offset = Dw_WriteLEB128_U(fp->filelength, offset); } offset = Dw_WriteB(0, offset); /* terminator */ offset = Dw_2_ProcessLineList(offset, YES); Dw_RoundUp(offset); obj_enddebugarea(Dwarf2LineInfoAreaName, dw_xrefs); } #else typedef int dummy; /* prevent translation unit from being empty */ #endif /* defined(TARGET_HAS_DWARF) && defined(TARGET_HAS_DEBUGGER) */ /* End of mip/dwarf2.c */
stardot/ncc
armthumb/armops.h
/* * C compiler file armthumb/armops.h, version 3 * Copyright (C) Codemist Ltd., 1987 * SPDX-Licence-Identifier: Apache-2.0 * (Was arm/ops.h) */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _armops_LOADED #define _armops_LOADED 1 /* AM some lines commented out temporarily and duplicated in mcspec.h */ /* ARM opcodes... */ /* Condition fields are defined relative to the default C_ALWAYS value */ #define C_ALWAYS 0xe0000000 #define C_CC (0x30000000^C_ALWAYS) #define C_LO (0x30000000^C_ALWAYS) #define C_CS (0x20000000^C_ALWAYS) #define C_HS (0x20000000^C_ALWAYS) #define C_EQ (0x00000000^C_ALWAYS) #define C_GE (0xa0000000^C_ALWAYS) #define C_GT (0xc0000000^C_ALWAYS) #define C_HI (0x80000000^C_ALWAYS) #define C_LE (0xd0000000^C_ALWAYS) #define C_LS (0x90000000^C_ALWAYS) #define C_LT (0xb0000000^C_ALWAYS) #define C_MI (0x40000000^C_ALWAYS) #define C_NE (0x10000000^C_ALWAYS) #define C_NEVER (0xf0000000^C_ALWAYS) #define C_PL (0x50000000^C_ALWAYS) #define C_VC (0x70000000^C_ALWAYS) #define C_VS (0x60000000^C_ALWAYS) /* Major opcode groups */ #define OP_RXR 0x00000000L /* 0x01000000L part of RXR */ #define OP_MUL 0x00000090L #define OP_MLA 0x00200090L #define OP_UMULL 0x00800090L #define OP_SMULL 0x00C00090L #define OP_UMLAL 0x00A00090L #define OP_SMLAL 0x00E00090L #define OP_RXN 0x02000000L /* 0x03000000L part of RXN */ #define OP_POSTN 0x04000000L #define OP_PREN 0x05000000L #define OP_POSTR 0x06000000L #define OP_PRER 0x07000000L #define OP_H_POSTN 0x00400090L #define OP_H_PREN 0x01400090L #define OP_H_POSTR 0x00000090L #define OP_H_PRER 0x01000090L #define OP_BX 0x012fff10L /* 0x08000000L part of LDM/STM */ /* 0x09000000L part of LDM/STM */ #define OP_B 0x0a000000L #define OP_BL 0x0b000000L #define OP_CPPOST 0x0c000000L /* needed for floating point */ #define OP_CPPRE 0x0d000000L #define OP_CPOP 0x0e000000L #define OP_SWI 0x0f000000L #define OP_CLASS 0x0f000000L /* Subfields for the data processing opcodes */ #define F_ADC (0x5L<<21L) #define F_ADD (0x4L<<21L) #define F_AND (0x0L<<21L) #define F_BIC (0xeL<<21L) #define F_CMN (0xbL<<21L) #define F_CMP (0xaL<<21L) #define F_EOR (0x1L<<21L) #define F_MOV (0xdL<<21L) #define F_MVN (0xfL<<21L) #define F_ORR (0xcL<<21L) #define F_RSB (0x3L<<21L) #define F_RSC (0x7L<<21L) #define F_SBC (0x6L<<21L) #define F_SUB (0x2L<<21L) #define F_TEQ (0x9L<<21L) #define F_TST (0x8L<<21L) #define F_DPOP (0xfL<<21) #define OP_MRS 0x010F0000L #define OP_MSR 0x0120F000L #define K_SPSR (1<<22) /* CPSR/SPSR bit */ #define OP_SWP 0x01000090L #define OP_SWPB 0x01400090L #define OP_CDP 0x0E000000L #define OP_MRC 0x0E100010L #define OP_MCR 0x0E000010L #define OP_LDC 0x0C100000L #define OP_STC 0x0C000000L #define F_WB (1<<21) #define F_LONG (1<<22) /* #define F_UP (1<<23) already defined */ #define F_PRE (1<<24) #define F_SCC 0x00100000L #define F_RN(n) (((int32)(n))<<16L) #define F_RD(n) (((int32)(n))<<12L) #define F_RM(n) ((int32)(n)) /* The next few are for use with RXR format (and corresponding memory */ /* access instructions) */ #define K_NOSHIFT 0L #define K_LSL(n) (((int32)(n))<<7L) /* 0 to 31 */ #define K_LSR(n) (((((int32)(n))&0x1fL)<<7L)|0x20L) /* 1 to 32 */ #define K_ASR(n) (((((int32)(n))&0x1fL)<<7L)|0x40L) /* 1 to 32 */ #define K_ROR(n) ((((int32)(n))<<7L)|0x60L) /* 1 to 31 */ #define K_RRX 0x60L /* one bit with extend */ #define R_LSL(r) ((((int32)(r))<<8L)|0x10L) /* register shift value */ #define R_LSR(r) ((((int32)(r))<<8L)|0x30L) /* register shift value */ #define R_ASR(r) ((((int32)(r))<<8L)|0x50L) /* register shift value */ #define R_ROR(r) ((((int32)(r))<<8L)|0x70L) /* register shift value */ /* subfields for memory reference instructions */ #define F_LDR 0x00100000L #define F_STR 0x00000000L #define F_LDRSTR_FIELD F_LDR #define F_WRITEBACK 0x00200000L /* = T bit in postindexed modes */ #define F_BYTE 0x00400000L #define F_WORD 0x00000000L #define F_BYTEWORD_FIELD F_BYTE #define F_SBYTE 0x00000040L #define F_UHALF 0x00000020L #define F_SHALF 0x00000060L #define F_UP 0x00800000L #define F_DOWN 0x00000000L #define F_UPDOWN_FIELD F_UP /* Block data subfields */ #define OP_LDMFA 0x08100000L #define OP_LDMEA 0x09100000L #define OP_LDMFD 0x08900000L #define OP_LDMED 0x09900000L #define OP_STMFA 0x09800000L #define OP_STMEA 0x08800000L #define OP_STMFD 0x09000000L #define OP_STMED 0x08000000L /* Versions for use when I am not thinking in stack terms */ #define OP_LDMDA 0x08100000L #define OP_LDMDB 0x09100000L #define OP_LDMIA 0x08900000L #define OP_LDMIB 0x09900000L #define OP_STMIB 0x09800000L #define OP_STMIA 0x08800000L #define OP_STMDB 0x09000000L #define OP_STMDA 0x08000000L #define OP_LDR (OP_PREN|F_LDR|F_WORD) #define OP_LDRB (OP_PREN|F_LDR|F_BYTE) #define OP_STR (OP_PREN|F_STR|F_WORD) #define OP_STRB (OP_PREN|F_STR|F_BYTE) #define OP_LDRR (OP_PRER|F_LDR|F_WORD) #define OP_LDRBR (OP_PRER|F_LDR|F_BYTE) #define OP_STRR (OP_PRER|F_STR|F_WORD) #define OP_STRBR (OP_PRER|F_STR|F_BYTE) #define OP_ADDR (OP_RXR | F_ADD) #define OP_ADCR (OP_RXR | F_ADC) #define OP_ANDR (OP_RXR | F_AND) #define OP_BICR (OP_RXR | F_BIC) #define OP_CMPR (OP_RXR | F_CMP | F_SCC) #define OP_CMNR (OP_RXR | F_CMN | F_SCC) #define OP_EORR (OP_RXR | F_EOR) #define OP_MOVR (OP_RXR | F_MOV) #define OP_MVNR (OP_RXR | F_MVN) #define OP_ORRR (OP_RXR | F_ORR) #define OP_RSBR (OP_RXR | F_RSB) #define OP_RSCR (OP_RXR | F_RSC) #define OP_SUBR (OP_RXR | F_SUB) #define OP_SBCR (OP_RXR | F_SBC) #define OP_TEQR (OP_RXR | F_TEQ | F_SCC) #define OP_TSTR (OP_RXR | F_TST | F_SCC) #define OP_ADDN (OP_RXN | F_ADD) #define OP_ADCN (OP_RXN | F_ADC) #define OP_ANDN (OP_RXN | F_AND) #define OP_BICN (OP_RXN | F_BIC) #define OP_CMNN (OP_RXN | F_CMN | F_SCC) #define OP_CMPN (OP_RXN | F_CMP | F_SCC) #define OP_EORN (OP_RXN | F_EOR) #define OP_MOVN (OP_RXN | F_MOV) #define OP_MVNN (OP_RXN | F_MVN) #define OP_ORRN (OP_RXN | F_ORR) #define OP_RSBN (OP_RXN | F_RSB) #define OP_RSCN (OP_RXN | F_RSC) #define OP_SUBN (OP_RXN | F_SUB) #define OP_SBCN (OP_RXN | F_SBC) #define OP_TEQN (OP_RXN | F_TEQ | F_SCC) #define OP_TSTN (OP_RXN | F_TST | F_SCC) #define F_PSR 0x00400000L /* #define regbit(n) (1<<(n)) */ /* Support here for second version of floating point (FPE2). */ /* options within LDF/STF CPDT group */ /* ONE OF THESE MUST BE USED WITH ANY FLOATING POINT OPERATION. */ #define F_SINGLE 0x00000100L #define F_DOUBLE 0x00008100L #define F_EXTENDED 0x00400100L #define F_PACKED 0x00408100L #define CPDT_FLTOFJ(x) (J_double(x) ? F_DOUBLE : F_SINGLE) #define F_FM_1 0x00008200L #define F_FM_2 0x00400200L #define F_FM_3 0x00408200L #define F_FM_4 0x00000200L /* opcodes for CPDO group */ #define CPDO_SINGLE 0x00000100L #define CPDO_DOUBLE 0x00000180L #define CPDO_FLTOFJ(x) (J_double(x) ? CPDO_DOUBLE : CPDO_SINGLE) #define CPDO_RNDUP 0x00000020L /* Without one of these it rounds to nearest */ #define CPDO_RNDDN 0x00000040L #define CPDO_RNDZ 0x00000060L #define F_REGOP 0x00000000L #define F_CONSTOP 0x00000008L #define F_ADF 0x00000000L #define F_MUF 0x00100000L #define F_SUF 0x00200000L #define F_RSF 0x00300000L #define F_DVF 0x00400000L #define F_RDF 0x00500000L #define F_POW 0x00600000L #define F_RPW 0x00700000L #define F_RMF 0x00800000L #define F_FML 0x00900000L #define F_FDV 0x00a00000L #define F_FRD 0x00b00000L #define F_POL 0x00c00000L #define F_XX1 0x00d00000L #define F_XX2 0x00e00000L #define F_XX3 0x00f00000L #define F_MVF 0x00008000L #define F_MNF 0x00108000L #define F_ABS 0x00208000L #define F_RND 0x00308000L #define F_SQT 0x00408000L #define F_LOG 0x00508000L #define F_LGN 0x00608000L #define F_EXP 0x00708000L #define F_SIN 0x00808000L #define F_COS 0x00908000L #define F_TAN 0x00a08000L #define F_ASN 0x00b08000L #define F_ACS 0x00c08000L #define F_ATN 0x00d08000L #define F_YY1 0x00e08000L #define F_YY2 0x00f08000L /* opcodes for more floating point operations */ #define F_FLT 0x00000110L #define F_FIX 0x00100110L #define F_WFS 0x00200110L #define F_RFS 0x00300110L #define F_WFC 0x00400110L #define F_RFC 0x00500110L #define F_CMF 0x0090f110L /* Use for == tests */ #define F_CNF 0x00b0f110L #define F_CMFE 0x00d0f110L /* Use for >, >= etc tests */ #define F_CNFE 0x00f0f110L /* * Register names - some defined in target.h. */ /* #define R_A1 0x0L * arg 1 & main result register */ #define R_A2 0x1L /* arg 2 */ #define R_A3 0x2L /* arg 3 */ #define R_A4 0x3L /* arg 4 */ /* #define R_V1 0x4L * register variable 1 */ #define R_V2 0x5L /* register variable 2 */ #define R_V3 0x6L /* register variable 3 */ #define R_V4 0x7L /* register variable 4 */ #define R_V5 0x8L /* register variable 5 */ #define R_V6 0x9L /* register variable 6 */ #define R_SB 0x9L /* (in reentrant APCS_3 code) */ #define R_FP 0xbL /* Frame pointer */ /* #define R_IP 0xcL * temp + used in call */ /* #define R_SP 0xdL * main stack pointer */ #define R_SL 0xaL /* stack limit (usually not checked) */ /* #define R_LR 0xeL * link address in function calls + workspace */ #define R_PC 0xfL /* program counter */ /* #define R_PSR R_PC * program status register */ /* Calling a function can disturb r_a1 to r_a4, r_ip, r_lk but must */ /* preserve r_v1 to r_v6, r_fp and r_sp. r_sl must always be a valid */ /* stack limit value - it may be changed during a call is a stack */ /* has its size changed. */ /* LDM/STM masks for real registers. */ #define M_LR regbit(R_LR) #define M_PC regbit(R_PC) #define M_PSR regbit(R_PSR) #define M_ARGREGS (regbit(R_A1+NARGREGS)-regbit(R_A1)) #define M_VARREGS (regbit(R_V1+NVARREGS)-regbit(R_V1)) #define M_FARGREGS (regbit(R_F0+NFLTARGREGS)-regbit(R_F0)) #define M_FVARREGS (regbit(R_F0+NFLTVARREGS+NFLTARGREGS) - \ regbit(R_F0+NFLTARGREGS)) /* #define R_F0 0x10L / * 16 added to avoid muddle with integer regs. */ #define R_F1 0x11L #define R_F2 0x12L #define R_F3 0x13L #define R_F4 0x14L #define R_F5 0x15L #define R_F6 0x16L #define R_F7 0x17L #endif /* end of arm/ops.h */
stardot/ncc
util/toansi.c
<reponame>stardot/ncc<gh_stars>0 /* * Tool to translate between ANSI and pcc-style function headers. * Copyright (C) <NAME>, 1988, 1989. * SPDX-Licence-Identifier: Apache-2.0 */ #include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <stdarg.h> #define SELF "toansi" #define VSN "3.00/013" #define BRIEF "convert a C program from PCC to ANSI dialect" #ifdef __STDC__ #define DATE __DATE__ #else #define DATE "Jun 16 1989" #endif #define OK 0 #define BAD 1 /* * BEWARE: id, lookaside_buf, depth_stack and other arrays are not * checked for potential overflow. If you over-run the limits * listed below then the program will fail. This is, of course, * extremely sloppy programming practice. */ #define ID_MAX 256 /* At most this no of chars in an identifier */ #define ID_START_CL 1 /* Class of chars starting an identifier */ #define NUM_CL 2 /* Decimal digit class */ #define ID_CL (ID_START_CL + NUM_CL) #define ID_TOKEN 1 #define NUM_TOKEN 2 #define ID_OR_NUM (ID_TOKEN + NUM_TOKEN) #define ROUND 32 #define MAX_ARGS 128 #define MAX_LOOKASIDE 2048 #define HEADER_BRKLEN 72 #define DEPTH_STACKSZ 50 static FILE *in_file, *out_file; static int next_ch, copied_line_len, line_no, brace_depth, depth_sp; static int depth_stack[DEPTH_STACKSZ]; static char id[ID_MAX], cur_fn[ID_MAX]; static char char_class[256]; static char *arg_id[MAX_ARGS]; static char *ansi_decl[MAX_ARGS]; static int narg_ids; static char *lookaside, *la_id_start, *cur_name; static char lookaside_buf[MAX_LOOKASIDE]; static void set_char_class(s, class) char *s; int class; { /* Make every char of 's' (other than \0) a member of 'class' */ while (*s) char_class[*s++] |= class; } static void init_char_class(void) { int j; for (j = 0; j < sizeof(char_class); ++j) char_class[j] = 0; set_char_class("ABCDEFGHIJKLMNOPQRSTUVWXYZ", ID_START_CL); set_char_class("abcdefghijklmnopqrstuvwxyz_", ID_START_CL); set_char_class("0123456789", ID_START_CL + NUM_CL); } static void errf(char *fmt, ...) { va_list ap; fprintf(stderr, "%s, %4d: ", cur_name, line_no); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); } static int getch(int last_ch) { /* * Get the next character, possibly copying the previous character * to stdout or to a lookaside buffer. */ if (line_no != 0) { if (lookaside) *lookaside++ = last_ch; else { if (last_ch == '\n') { copied_line_len = 0; } else ++copied_line_len; putc(last_ch, out_file); } } if (last_ch == '\n') ++line_no; return getc(in_file); } static int skip_blanks(int ch) { while (ch == ' ' || ch == '\t') ch = getch(ch); return ch; } static int skip1_blanks(int ch) { do {ch = getch(ch);} while (ch == ' ' || ch == '\t'); return ch; } static void pp_directive(char *pp) { int temp; if (strcmp(pp, "if") == 0 || strcmp(pp, "ifdef") == 0 || strcmp(pp, "ifndef") == 0) { depth_stack[depth_sp++] = brace_depth; } else if (strcmp(pp, "else") == 0) { temp = brace_depth; if (depth_sp > 0) brace_depth = depth_stack[depth_sp-1]; else brace_depth = depth_sp = 1; depth_stack[depth_sp-1] = temp; } else if (strcmp(pp, "endif") == 0) { if (depth_sp == 0) temp = 1; else temp = depth_stack[--depth_sp]; if (brace_depth != temp) errf("confused by mismatched, conditionally included braces...\n"); } } static int get_tokch(int ch) { /* * Get the next token-starting character. * next_ch is used to buffer a character of look ahead. */ next_ch = 0; for (;;) { /* * skip pre-processor lines. */ if (ch == '\n') { ch = skip1_blanks(ch); if (ch == '#') { /* pre-processor directive */ int j = 0, last_ch; char pp[ID_MAX]; ch = skip1_blanks(ch); do {pp[j++] = ch; ch = getch(ch);} while (char_class[ch] & ID_CL); pp[j] = 0; pp_directive(pp); last_ch = 0; while ((ch != '\n' || last_ch == '\\') && ch != EOF) last_ch = ch, ch = getch(ch); continue; } } else ch = skip_blanks(ch); /* * skip comments */ if (ch == '/') { ch = getch(ch); if (ch == '*') { /* found '/' '*' ... */ ch = getch(ch); do { while (ch != '*') ch = getch(ch); ch = getch(ch); } while (ch != '/'); /* ... then get character following '*' '/' */ ch = getch(ch); } else { /* save char following '/' and return '/' */ next_ch = ch; return '/'; } } else if (ch != '\n') { /* got a non-preprocessor-line, non-comment, non-space character */ return ch; } } } static int skip_string(int quote) { int ch = quote; /* * Skip a quoted string - beware '\'quote within the string. */ for (;;) { ch = getch(ch); if (ch == quote) break; if (ch == '\\') ch = getch(ch); } /* ... and get the character beyond the end of the string */ return getch(ch); } static int get_token() { int j, class; int ch = next_ch; /* * Here, we're looking for identifiers, brackets, etc. * Strings are skipped as being uninteresting. */ while (ch != EOF) { ch = get_tokch(ch); if (ch == '\'' || ch == '"') { ch = skip_string(ch); } else if ((class = char_class[ch]) & ID_CL) { la_id_start = lookaside; j = 0; do {id[j++] = ch; ch = getch(ch);} while (char_class[ch] & ID_CL); id[j] = 0; next_ch = ch; return (class == ID_START_CL ? ID_TOKEN : NUM_TOKEN); } else { /* non-identifier, non-string token... ch is just beyond it */ if (!next_ch && ch != EOF) next_ch = getch(ch); return ch; } } return EOF; } static void skip_fn_body(void) { int tok, depth = depth_sp; brace_depth = 1; do { tok = get_token(); if (tok == '{') { ++brace_depth; } else if (tok == '}') { --brace_depth; } } while ((brace_depth > 0 || depth_sp > depth) && (tok != EOF)); /* Assert: brace_depth == 0 && depth_sp == depth || tok == EOF */ if (tok == EOF && (brace_depth || depth_sp)) errf("missing '}' or conditional #include confusion at EOF\n"); } static char *savestr(str) char *str; { int l = strlen(str); char *s; l = (l + (ROUND-1)) & ~(ROUND-1); s = malloc(l); if (s == NULL) { errf("can't allocate space for %s\n", id); exit(1); } return strcpy(s, str); } static int formal_argument_list(void) { int tok, is_ansi; /* check for id, id, ... */ narg_ids = 0; is_ansi = 0; tok = get_token(); while (tok != ')') { if (tok == ID_TOKEN) { ansi_decl[narg_ids] = NULL; arg_id[narg_ids++] = savestr(id); } tok = get_token(); if (tok == ',') { tok = get_token(); } else if (tok != ')') { is_ansi = 1; } } if (is_ansi) tok = get_token(); /* often ';' or '{' */ if ((tok != ')') || (narg_ids == 1) && (strcmp(id, "void") == 0)) { /* cleanup */ while (narg_ids > 0) {free(arg_id[--narg_ids]); arg_id[narg_ids] = NULL;}; } return tok; } static void process_decl(prefix, str, id) char * prefix; char *str; char *id; { int j; char *decl, *s; char buf[ID_MAX+ID_MAX]; /* * Trim trailing blanks from id */ s = id + strlen(id); while (*--s == ' '); s[1] = 0; /* * Trim leading and trailing blanks from prefix and str. */ while (*prefix == ' ') ++prefix; s = prefix + strlen(prefix) - 1; while (*s == ' ') --s; s[1] = 0; while (*str == ' ') ++str; s = str + strlen(str) - 1; while (*s == ' ') --s; s[1] = 0; for (j = 0; j < narg_ids; ++j) { if (strcmp(arg_id[j], id) == 0) { decl = ansi_decl[j]; if (decl != NULL) { errf("duplicate definition of argument '%s' to '%s' ignored\n", id, cur_fn); } else { while ((char_class[*prefix] & ID_START_CL) == 0) ++prefix; sprintf(buf, "%s %s", prefix, str); ansi_decl[j] = savestr(buf); } return; } } errf("'%s' is not an argument to '%s'\n", id, cur_fn); } static int match_argument_decl(void) { int tok, l; char *p, *d, *s; char prefix[ID_MAX], decl[ID_MAX], decl_id[ID_MAX]; /* * An approximation which often works is:- * <decl> ::= <id> (<id>)* <thing> ( "," <thing> )* * <thing>::= ("*")* <id> ("[" [<id>|<num>] "]")* * Assert: enter with id found; */ p = NULL; d = la_id_start; for (;;) { s = lookaside; tok = get_token(); if (tok != ID_TOKEN) break; if (p == NULL) p = d; d = la_id_start; } if (tok != '*') { if (p) { l = d - p; strncpy(prefix, p, l); prefix[l] = 0; } else { strcpy(prefix, "int "); } l = lookaside - d - 1; strncpy(decl_id, d, l); decl_id[l] = 0; strcpy(decl, decl_id); } else { if (p) d = p; s = lookaside -1; l = s - d; strncpy(prefix, d, l); prefix[l] = 0; d = s; } again: while (tok == '*') tok = get_token(); if (tok == ID_TOKEN) { strcpy(decl_id, id); tok = get_token(); } while (tok == '[') { tok = get_token(); while (tok == ID_TOKEN || tok == NUM_TOKEN) { tok = get_token(); if (tok == ',') tok = get_token(); } if (tok != ']') { errf("missing ']' in declaration of %s in %s\n", decl_id, cur_fn); return 0; } else { tok = get_token(); } } if (tok == ',' || tok == ';') { l = lookaside - d - 1; strncpy(decl, d, l); decl[l] = 0; process_decl(prefix, decl, decl_id); if (tok == ',') { d = lookaside; tok = get_token(); goto again; } } if (tok != ';') errf("failed matching arg list for %s (missing ';')\n", cur_fn); return tok; } static int match_argument_decls() { int tok; /* * Match:- * ( <decl> ";")* * <decl> ::= <id> (<id>)* ... */ tok = get_token(); if (tok == ';') return ';'; /* a declaration! */ while (tok == ID_TOKEN) { tok = match_argument_decl(); if (tok != ';') { return 0; } else { tok = get_token(); } } if (tok != '{') { errf("failed matching arg list for %s (missing '{')\n", cur_fn); } return tok; } static void put_spaces(n) int n; { while (n-- > 0) putc(' ', out_file); } static void rewrite_fn_defn(void) { int j, width; char *decl, *s; char buf[ID_MAX]; if (narg_ids == 0) fprintf(out_file, "void)\n"); width = copied_line_len; for (j = 0; j < narg_ids; ++j) { decl = ansi_decl[j]; if (decl == NULL) { if (strcmp(arg_id[j], "va_alist") == 0) { decl = "..."; } else { decl = buf; sprintf(decl, "int %s", arg_id[j]); } } if ((width + strlen(decl) + 2) > HEADER_BRKLEN) { width = copied_line_len; putc('\n', out_file); put_spaces(width); } width += fprintf(out_file, "%s", decl); free(ansi_decl[j]); free(arg_id[j]); ansi_decl[j] = arg_id[j] = NULL; width += fprintf(out_file, "%s", (j < (narg_ids-1) ? ", " : ")\n")); } /* * Now see if any comments lie between the args and the '{'. */ s = lookaside; *s = 0; s -= 2; for (;;) { while (s > lookaside_buf && *s != ';' && *s != ')' && *s != '/') --s; /* Assert: *s == ';', ')' or '/' */ if (*s != '/') break; if (*s == '/' && s[-1] == '*') { s -= 2; while (*s != '*' || s[-1] != '/') --s; s -= 2; } else { --s; } } ++s; while (isspace(*s) && *s != '\n') ++s; if (*s == '\n') ++s; fputs(s, out_file); } static int rewrite_fn_decl(char *endp) { /* * Strip out enclosing comment brackets if there are any... * This ussumes that that which is so enclosed is a valid ANSI argument list. */ char *s, *e; s = lookaside_buf; while (isspace(*s)) ++s; /* Assert: *s != <space> */ if (*s != '/' || s[1] != '*') return 0; s += 2; while (isspace(*s)) ++s; e = endp; while (e != s && *e-- != '/'); if (e == s || *e != '*') return 0; while (isspace(e[-1])) --e; *e = 0; fputs(s, out_file); *lookaside = 0; fputs(endp, out_file); return 1; } static int is_basic_type(char *s) { static char *keywds[] = { /* MUST be in alphabetic order */ "char", "double", "enum", "extern", "float", "int", "long", "short", "static", }; int j, s0 = s[0], k0; char *k; for (j = 0; j < sizeof(keywds)/sizeof(char *); ++j) { k = keywds[j]; k0 = k[0]; if (k0 > s0) return 0; if (k0 < s0) continue; if (strcmp(s, k) == 0) return 1; } return 0; } static void translate(void) { int tok, last_tok; init_char_class(); lookaside = NULL; copied_line_len = 0; brace_depth = 0; depth_sp = 0; line_no = 0; next_ch = '\n'; /* fake being just past a new-line */ last_tok = get_token(); while (last_tok != EOF) { tok = get_token(); if (last_tok == ID_TOKEN && tok == '(' && !is_basic_type(id)) { lookaside = lookaside_buf; strcpy(cur_fn, id); tok = formal_argument_list(); if (tok == ')') { char *endp = lookaside-1; tok = match_argument_decls(); if (tok == '{') { rewrite_fn_defn(); } else if (tok == ';' && narg_ids == 0 && rewrite_fn_decl(endp)) { /* do nothing */ } else { *lookaside = 0; fputs(lookaside_buf, out_file); } } else { *lookaside = 0; fputs(lookaside_buf, out_file); } lookaside = NULL; if (tok == '{') {skip_fn_body(); tok = '}';} } last_tok = tok; } } static void handle_escape(int signo) { signal(signo, handle_escape); exit(EXIT_FAILURE); } static void describe_function(void) { fprintf(stderr, "\n%s \ translates a (suitable) K&R-style or PCC-style C source program to a\n\ form acceptable to an ANSI-C compiler. Top-level function declarations with\n\ comments imbedded within their '()'s have the '/*'s and '*/'s removed on the\n\ assumption that they contain ANSI-style formal argument lists. Function\n\ definition prototypes are re-written the ANSI way (e.g. void foo(x) int x;\n\ {...} is re-written as void foo(int x) {...}).\n\n\ Other differences between the dialects must be addressed in the source\n\ before or after translation.\n\n", SELF); } static void give_help(void) { fprintf(stderr, "\n%s vsn %s [%s] - %s\n", SELF, VSN, DATE, BRIEF); fprintf(stderr, "\n%s [options] [infile [outfile]]\n", SELF); fprintf(stderr, " outfile defaults to stdout\n"); fprintf(stderr, " infile defaults to stdin\n"); fprintf(stderr, "\nOptions:-\n"); fprintf(stderr, "-d describe what the program does\n"); fprintf(stderr, "\nExample:-\n"); fprintf(stderr, " %s c.pccprog c.ansiprog\n", SELF); exit(EXIT_SUCCESS); } int main(argc, argv) int argc; char *argv[]; { char *arg, *in_name, *out_name; int j, nerr; signal(SIGINT, handle_escape); /* parse help or identify args */ for (j = 1; j < argc; ++j) { arg = argv[j]; if (strcmp("-help", arg) == 0 || strcmp("-h", arg) == 0 || strcmp("-HELP", arg) == 0 || strcmp("-H", arg) == 0) give_help(); } in_name = out_name = NULL; nerr = 0; for (j = 1; j < argc; ++j) { arg = argv[j]; if (arg[0] == '-') { if (arg[1] == 'd' || arg[1] == 'D') { describe_function(); exit(OK); } else { fprintf(stderr, "%s: unknown flag '%s'\n", SELF, arg); ++nerr; } } else { if (in_name == NULL) in_name = arg; else if (out_name == NULL) out_name = arg; else { fprintf(stderr, "%s: too many filenames ('%s' ignored)\n", SELF, arg); ++nerr; } } } if (nerr) exit(BAD); if (in_name) { in_file = fopen(in_name, "r"); if (in_file == NULL) { fprintf(stderr, "%s: can't open input file '%s' - assuming <stdin>\n", SELF, in_name); fprintf(stderr, "%s: (press CTRL+D to end input)\n", SELF); } } else in_file = NULL; if (in_file == NULL) { in_file = stdin; cur_name = "<stdin>"; } else cur_name = in_name; if (out_name) out_file = fopen(out_name, "w"); else out_file = NULL; if (out_file == NULL) out_file = stdout; translate(); return 0; }
stardot/ncc
tests/2232.c
<gh_stars>0 /* * ARM C compiler regression test $RCSfile$ * Copyright (C) 1997 Advanced Risc Machines Ltd. All rights reserved. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include "testutil.h" /********************* 2232 ***********************/ /* may syserr */ __inline float f_2232() { return 0; } float g_2232() { return f_2232(); } void t_2232() { EQD(g_2232(), 0.0); } /********************* ***********************/ int main(void) { BeginTest(); t_2232(); EndTest(); return 0; }
stardot/ncc
cfe/vargen.h
/* * cfe/vargen.h: * Copyright (C) Acorn Computers Ltd., 1988 * Copyright (C) Codemist Ltd., 1988. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 4 * Checkin $Date$ * Revising $Author$ */ #ifndef _vargen_h #define _vargen_h #ifndef _defs_LOADED # include "defs.h" #endif #if !defined(CALLABLE_COMPILER) /* * ****** NASTY EXPORT - RECONSIDER ****** * Should be static except for initstaticvar(datasegment) in compiler.c */ extern void initstaticvar(Binder *b, bool topflag); /* The following routine generates statics, which MUST have been instated with instate_declaration(). Dynamic initialistions are turned into assignments for rd_block() by returning the expression tree; NULL means no dynamic initialization. Top-level dynamic initialization code (for C++) is also generated in the module initialization function. Ensure type errors are noticed here (for line numbers etc.) */ extern Expr *genstaticparts(DeclRhsList * const d, bool topflag, bool dummy_call, Expr *dyninit); /* @@@ since the 'const' isn't part of the function type in the line */ /* @@@ above, AM wonders why it has been added. C++ namemunge oddity! */ #else #define initstaticvar(b,f) ((void)0) #define genstaticparts(d,f,dc,e) ((Expr *)0) #endif #ifdef CALLABLE_COMPILER #define vg_generate_deferred_const(a) ((void)(a)) #else extern void vg_generate_deferred_const(Binder *); #endif #if (defined(CPLUSPLUS) && !defined(CALLABLE_COMPILER)) extern void vg_note_vtable(TagBinder *cl, int32 sz, Symstr *name); extern Binder *generate_wrapper(Binder *a); extern TopDecl *vg_dynamic_init(void); extern void vg_ref_dynamic_init(void); extern void vargen_init(void); extern int32 ddtor_vecsize(void); #else #define generate_wrapper(a) ((void)(a), (Binder *)0) #define vg_note_vtable(cl,sz,name) ((void)0) #define vg_dynamic_init() ((TopDecl *)0) #define vg_ref_dynamic_init() ((void)0) #define vargen_init() ((void)0) #define vg_currentdecl_inits 0 #define ddtor_vecsize() ((int32)0) #endif #endif /* end of cfe/vargen.h */
stardot/ncc
armthumb/asmcg.c
<filename>armthumb/asmcg.c /* * asmcg.c: code generation for ARM/Thumb inline assembler * Copyright (C) Advanced Risc Machines Ltd., 1997. All rights reserved. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <stddef.h> #include <stdlib.h> #include <string.h> #include "globals.h" #include "cg.h" #include "store.h" #include "codebuf.h" #include "aeops.h" #include "util.h" #include "xrefs.h" #include "jopcode.h" #include "regalloc.h" #include "regsets.h" #include "cse.h" #include "sr.h" #include "flowgraf.h" #include "mcdep.h" #include "aetree.h" #include "builtin.h" #include "sem.h" /* typeofexpr */ #include "syn.h" #include "simplify.h" /* mcrepofexpr */ #include "bind.h" #include "errors.h" #include "inline.h" #include "armops.h" #include "lex.h" #include "defs.h" #include "cgdefs.h" #include "mcdpriv.h" #include "arminst.h" #include "inlnasm.h" int32 trans_cc_tab [16] = { Q_EQ, Q_NE, Q_HS, Q_LO, Q_MI, Q_PL, Q_VS, Q_VC, Q_HI, Q_LS, Q_GE, Q_LT, Q_GT, Q_LE, Q_AL, Q_NOT /* not used */ }; #ifdef ARM_INLINE_ASSEMBLER J_OPCODE arm_op_tab [NUM_ARM_OPCODES] = { J_ANDK, J_EORK, J_SUBK, J_RSBK, J_ADDK, J_ADCK, J_SBCK, J_RSCK, J_TSTK, J_TEQK, J_CMPK, J_CMNK, J_ORRK, J_MOVK, J_BICK, J_MVNK }; #endif J_OPCODE thumb_op_tab [NUM_ARM_OPCODES] = { J_ANDR, J_EORR, J_SUBR, J_NOOP, J_ADDR, J_ADCR, J_SBCR, J_NOOP, J_TSTR, J_NOOP, J_CMPR, J_CMNR, J_ORRR, J_MOVR, J_BICR, J_MVNR, J_NOOP, J_NOOP, J_MULR }; static bool ccflags_altered; static uint32 cur_cond; static LabelNumber *cur_label; static void cg_asm_init(void) { procflags |= PROC_INLNASM; ccflags_altered = NO; cur_label = NULL; cur_cond = CC_AL; } static void cg_asm_finish(void) { if (cur_label != NULL) { emitbranch (J_B, cur_label); start_new_basic_block (cur_label); } } static void asm_err(msg_t msg) { cc_err(msg); } static VRegnum expr_reg(Expr *e) { if (e == 0) return GAP; if (h0_(e) == s_register) return intval_(e); return cg_expr(e); } static void free_reg(Expr *e, VRegnum r) { if (e == 0 || h0_(e) == s_register || r == GAP) return; bfreeregister(r); } static VRegnum get_reg(Expr *e) { if (e == 0) return GAP; if (h0_(e) == s_register) return intval_(e); return fgetregister(INTREG); } static VRegnum expr_loreg(Expr *e) { /* Version which only allows low registers */ if (e == 0) return GAP; if (h0_(e) == s_register) { if (intval_(e) >= 8) { cc_err(asm_err_thumb_highreg, intval_(e)); return 0; } return intval_(e); } return cg_expr(e); } static VRegnum expr_reg_sp(Expr *e) { /* Version which only allows low registers, and SP */ if (e == 0) return GAP; if (h0_(e) == s_register) { if (intval_(e) >= 8 && intval_(e) != R_SP) { cc_err(asm_err_thumb_highreg, intval_(e)); return 0; } return intval_(e); } return cg_expr(e); } static void store_reg(Expr *e, VRegnum r) { /* Store a register into variable 'e'. */ if (e == 0 || h0_(e) == s_register) { if (r == R_PC) cc_err(asm_err_write_pc); return; } cg_storein(r, NULL, e, s_assign); bfreeregister(r); } static void store_reg_psr(Expr *e, VRegnum r) { /* Version for MRC which may write to PC (PSR part) */ if (e == 0 || h0_(e) == s_register) return; cg_storein(r, NULL, e, s_assign); bfreeregister(r); } static void store_reg_pc(Expr *e, VRegnum r) { /* Version for instructions which may write to pc. * We don't allow it... */ if (e == 0 || h0_(e) == s_register) { if (r == R_PC) cc_err(asm_err_branch_pc); return; } cg_storein(r, NULL, e, s_assign); bfreeregister(r); } static void store_loreg(Expr *e, VRegnum r) { /* Do not allow high registers. */ if (e == 0 || h0_(e) == s_register) { if (r >= 8) cc_err(asm_err_thumb_highreg, r); return; } cg_storein(r, NULL, e, s_assign); bfreeregister(r); } static void store_reg_sp(Expr *e, VRegnum r) { /* Allow SP, but no other high reg. */ if (e == 0 || h0_(e) == s_register) { if (r >= 8 && r != R_SP) cc_err(asm_err_thumb_highreg, r); return; } cg_storein(r, NULL, e, s_assign); bfreeregister(r); } static void cg_asm_data(const AsmInstr * const a) { J_OPCODE op; VRegnum r1, r2, r3, r4; int opnd2_type = asmopcode_(a) & RN_OPND_MASK; r1 = get_reg(asmopnd1_(a)); r2 = expr_reg(asmopnd2_(a)); switch (INSTRCL(asmopcode_(a))) { case CL_MOV: op = J_AMOVK; r2 = 0; if ((opnd2_type == RN_REG || opnd2_type == RN_CONST) && !(asmopcode_(a) & SET_CC) && OPCODE(asmopcode_(a)) == A_MOV) { op = J_MOVK; r2 = GAP; } break; case CL_CMP: op = J_ACMPK; r1 = asmopcode_(a) & SET_PSR ? 15 : 0; break; case CL_BIN: op = J_ABINRK; break; } switch (opnd2_type) { case RN_CONST: r3 = intval_(asmopnd3_(a)); emitreg4(op, asmopcode_(a), r1, r2, r3, GAP); free_reg(asmopnd2_(a), r2); break; case RN_REG: r3 = expr_reg(asmopnd3_(a)); emitreg4(op+1, asmopcode_(a), r1, r2, r3, GAP); free_reg(asmopnd3_(a), r3); break; case RN_SHIFT: r3 = expr_reg(asmopnd3_(a)); emitreg4(op+2, asmopcode_(a), r1, r2, r3, intval_(asmopnd4_(a))); /* CHECK RANGE!!!! */ bfreeregister(r3); break; case RN_SHIFT_REG: r3 = expr_reg(asmopnd3_(a)); r4 = expr_reg(asmopnd4_(a)); emitreg4(op+3, asmopcode_(a), r1, r2, r3, r4); free_reg(asmopnd3_(a), r3); free_reg(asmopnd4_(a), r4); break; default: break; } free_reg(asmopnd2_(a), r2); if (asmopcode_(a) & SET_PSR) store_reg_psr(asmopnd1_(a), r1); else store_reg_pc(asmopnd1_(a), r1); } static void cg_asm_mul(const AsmInstr * const a) { VRegnum r1, r2, r3, r4; switch (OPCODE (asmopcode_(a))) { case A_MUL: r1 = get_reg(asmopnd1_(a)); r2 = expr_reg(asmopnd2_(a)); if (h0_(asmopnd3_(a)) == s_integer) emitreg4(J_MULK, asmopcode_(a), r1, r2, intval_(asmopnd3_(a)), 0); else { r3 = expr_reg(asmopnd3_(a)); emitreg4(J_MULR, asmopcode_(a), r1, r3, r2, GAP); /* J_MUL has r2 & r3 swapped */ free_reg(asmopnd3_(a), r3); if (r1 == r2) asm_err(asm_err_mul_conflict); if (r3 == R_PC) asm_err(asm_err_pc); } free_reg(asmopnd2_(a), r2); store_reg(asmopnd1_(a), r1); if (r1 == R_PC || r2 == R_PC) asm_err(asm_err_pc); break; case A_MLA: r1 = get_reg(asmopnd1_(a)); r2 = expr_reg(asmopnd2_(a)); r3 = expr_reg(asmopnd3_(a)); r4 = expr_reg(asmopnd4_(a)); emitreg4(J_MLAR, asmopcode_(a), r1, r3, r2, r4); /* J_MLA has r2 & r3 swapped */ free_reg(asmopnd2_(a), r2); free_reg(asmopnd3_(a), r3); free_reg(asmopnd4_(a), r4); store_reg(asmopnd1_(a), r1); if (r1 == r2) asm_err(asm_err_mul_conflict); if (r1 == R_PC || r2 == R_PC || r3 == R_PC || r4 == R_PC) asm_err(asm_err_pc); break; case A_MULL: { int32 op; r1 = get_reg(asmopnd1_(a)); r2 = get_reg(asmopnd2_(a)); r3 = expr_reg(asmopnd3_(a)); r4 = expr_reg(asmopnd4_(a)); op = J_MULL; if (asmopcode_(a) & M_SIGNED) op |= J_SIGNED; emitreg4(op, asmopcode_(a), r1, r2, r3, r4); free_reg(asmopnd3_(a), r3); free_reg(asmopnd4_(a), r4); store_reg(asmopnd1_(a), r1); store_reg(asmopnd2_(a), r2); if (r1 == r2 || r1 == r3 || r2 == r3) asm_err(asm_err_mul_conflict); if (r1 == R_PC || r2 == R_PC || r3 == R_PC || r4 == R_PC) asm_err(asm_err_pc); break; } case A_MLAL: { int32 op; r1 = expr_reg(asmopnd1_(a)); r2 = expr_reg(asmopnd2_(a)); r3 = expr_reg(asmopnd3_(a)); r4 = expr_reg(asmopnd4_(a)); op = J_MLAL; if (asmopcode_(a) & M_SIGNED) op |= J_SIGNED; emitreg4(op, asmopcode_(a), r1, r2, r3, r4); free_reg(asmopnd3_(a), r3); free_reg(asmopnd4_(a), r4); store_reg(asmopnd1_(a), r1); store_reg(asmopnd2_(a), r2); if (r1 == R_PC || r2 == R_PC || r3 == R_PC || r4 == R_PC) asm_err(asm_err_pc); break; } } } static void cg_asm_ldmstm(const AsmInstr * const a) { VRegnum r1, r3; uint32 op; op = OPCODE(asmopcode_(a)) == A_LDM ? J_LDM : J_STM; if (asmopcode_(a) & M_WB) op += J_LDMW - J_LDM; r1 = expr_reg(asmopnd1_(a)); r3 = intval_(asmopnd3_(a)); emitreg4(op, asmopcode_(a), r1, GAP, r3, GAP); if (r3 == 0) asm_err(asm_err_ldm_empty); if (r1 == R_PC /* WD; temporary - swallis || ((op == J_LDM || op == J_LDMW) && (r3 & regbit(R_PC))) */ ) asm_err(asm_err_pc); if (asmopcode_(a) & M_WB) { if (r1 < 16 && regbit(r1) & r3) asm_err(asm_err_ldm_base_list); store_reg(asmopnd1_(a), r1); } else free_reg(asmopnd1_(a), r1); } static void cg_asm_ldrstr(const AsmInstr * const a) { VRegnum r1, r2, r3; bool is_load = OPCODE(asmopcode_(a)) == A_LDR; uint32 op = is_load ? J_ALDRK : J_ASTRK; if (is_load) r1 = get_reg(asmopnd1_(a)); else r1 = expr_reg(asmopnd1_(a)); r2 = expr_reg(asmopnd2_(a)); if (asmopcode_(a) & M_WB) op += J_ALDRKW - J_ALDRK; switch (asmopcode_(a) & RN_OPND_MASK) { case RN_CONST: r3 = intval_(asmopnd3_(a)); emitreg4(op, asmopcode_(a), r1, r2, r3, GAP); break; case RN_REG: op = J_KTOR(op); r3 = expr_reg(asmopnd3_(a)); emitreg4(op, asmopcode_(a), r1, r2, r3, GAP); free_reg(asmopnd3_(a), r3); break; case RN_SHIFT: op = J_KTOR(op); r3 = expr_reg(asmopnd3_(a)); emitreg4(op, asmopcode_(a), r1, r2, r3, intval_(asmopnd4_(a))); free_reg(asmopnd3_(a), r3); break; default: ;/* Error */ } if (asmopcode_(a) & M_WB) { if (r1 == r2 && r1 < 16) asm_err(asm_err_ldr_base_wb); store_reg(asmopnd2_(a), r2); } else free_reg(asmopnd2_(a), r2); if (is_load) store_reg(asmopnd1_(a), r1); else free_reg(asmopnd1_(a), r1); if (r1 == R_PC && asmopcode_(a) & (M_BYTE | M_HALF)) asm_err(asm_err_pc); } static void cg_psr(const AsmInstr *const a) { VRegnum psr = intval_(asmopnd2_(a)); if (OPCODE(asmopcode_(a)) == A_MRS) { VRegnum r1 = get_reg(asmopnd1_(a)); emitreg4(J_MRS, 0, r1, psr, GAP, GAP); store_reg(asmopnd1_(a), r1); } else if ((psr & PSR_FLAGS) == PSR_F && h0_(asmopnd3_(a)) == s_integer && Arm_EightBits(intval_(asmopnd3_(a))) >= 0) /* MSR PSR_f, #8 bit const */ { emitreg4(J_MSK, 0, GAP, psr, intval_(asmopnd3_(a)), GAP); } else /* MSR PSR, reg */ { VRegnum r3 = expr_reg(asmopnd3_(a)); emitreg4(J_MSR, 0, GAP, psr, r3, GAP); free_reg(asmopnd3_(a), r3); } } static void cg_swi(const AsmInstr *const a) { emitreg4(J_SWI, 0, intval_(asmopnd1_(a)), intval_(asmopnd2_(a)), intval_(asmopnd3_(a)), intval_(asmopnd4_(a))); } static void cg_swp(const AsmInstr *const a) { VRegnum r1, r2, r3; r1 = get_reg(asmopnd1_(a)); r2 = expr_reg(asmopnd2_(a)); r3 = expr_reg(asmopnd3_(a)); emitreg4((asmopcode_(a) & M_BYTE ? J_SWPB : J_SWP), 0, r1, r2, r3, GAP); store_reg(asmopnd1_(a), r1); free_reg(asmopnd2_(a), r2); free_reg(asmopnd3_(a), r3); if (r1 == r3 || r2 == r3) asm_err(asm_err_swp_conflict); if (r1 == R_PC || r2 == R_PC || r3 == R_PC) asm_err(asm_err_pc); } static void cg_bl(const AsmInstr *const a) { /* Branches are already handled */ if (OPCODE(asmopcode_(a)) == A_BL) { emitreg4(J_BL, 0, (int) asmopnd1_(a), intval_(asmopnd2_(a)), intval_(asmopnd3_(a)), intval_(asmopnd4_(a))); } } static void cg_cop(const AsmInstr *const a) { uint32 coproc = intval_(asmopnd4_(a)) | intval_(asmopnd3_(a)) | (intval_(asmopnd2_(a)) << 16); VRegnum r1; switch (OPCODE(asmopcode_(a))) { case A_CDP: coproc |= intval_(asmopnd1_(a)) << 12; emitreg4(J_CDP, 0, GAP, GAP, 0, coproc); break; case A_MRC: r1 = get_reg(asmopnd1_(a)); emitreg4(J_MRC, 0, r1, GAP, 0, coproc); store_reg_psr(asmopnd1_(a), r1); break; case A_MCR: r1 = expr_reg(asmopnd1_(a)); emitreg4(J_MCR, 0, r1, GAP, 0, coproc); free_reg(asmopnd1_(a), r1); break; } } static void cg_cmem(const AsmInstr *const a) { uint32 coproc = intval_(asmopnd4_(a)) | (intval_(asmopnd1_(a)) << 12); uint32 op; VRegnum r2; op = (OPCODE(asmopcode_(a)) == A_STC) ? J_STC : J_LDC; if (asmopcode_(a) & M_WB) op += J_LDCW - J_LDC; r2 = expr_reg(asmopnd2_(a)); emitreg4(op, asmopcode_(a), GAP, r2, intval_(asmopnd3_(a)) >> 2, coproc); if (asmopcode_(a) & M_WB) store_reg(asmopnd2_(a), r2); else free_reg(asmopnd2_(a), r2); } /* TODO: cleanup branches and labels -> can be a lot simpler! */ void cg_arm_instr(const AsmInstr *const a) { uint32 cond = GETCC(asmopcode_(a)); if (usrdbg(DBG_LINE)) emitfl(J_INFOLINE, a->fl); curlex.fl = a->fl; if (OPCODE(asmopcode_(a)) == A_B) { LabBind *lab = (LabBind*) asmopnd1_(a); LabelNumber *l = lab->labinternlab; if (l == NULL) l = lab->labinternlab = nextlabel(); if (lab->labuses & l_defined) { if (cond == cur_cond) emitbranch(J_B, l); } else cond = cur_cond; } if (cond != cur_cond && cur_label != NULL) { /* finish current conditional block */ emitbranch(J_B, cur_label); start_new_basic_block(cur_label); cur_label = NULL; cur_cond = CC_AL; } if (OPCODE(asmopcode_(a)) == A_LABEL) /* create a new block with the label */ { LabBind *lab = (LabBind*) asmopnd1_(a); LabelNumber *l = lab->labinternlab; if (l == NULL) l = lab->labinternlab = nextlabel(); emitbranch(J_B, l); start_new_basic_block(l); cur_cond = cond = CC_AL; } if (cond != cur_cond && cond != CC_AL) { /* create a new block if instr is conditional */ LabelNumber *l; if (OPCODE(asmopcode_(a)) == A_B) { uint32 branch_cond; LabBind *lab = (LabBind*) asmopnd1_(a); l = lab->labinternlab; if (l == NULL) l = lab->labinternlab = nextlabel(); if (lab->labuses & l_defined) { branch_cond = cond; emitbranch(J_B + translate_cc(branch_cond), l); l = nextlabel(); cur_label = nextlabel(); emitbranch(J_B, l); start_new_basic_block (l); cur_cond = cond = CC_AL; } } else { l = nextlabel(); cur_label = nextlabel(); emitbranch(J_B + translate_cc(INVCC(cond)), cur_label); emitbranch(J_B, l); start_new_basic_block (l); cur_cond = cond; } } if (asmopcode_(a) & SET_CC) cur_cond = CC_NOT; switch (INSTRCL(asmopcode_(a))) { case CL_MOV: case CL_CMP: case CL_BIN: cg_asm_data(a); break; case CL_MUL: cg_asm_mul(a); break; case CL_LDM: cg_asm_ldmstm(a); break; case CL_MEM: cg_asm_ldrstr(a); break; case CL_PSR: cg_psr(a); break; case CL_SWI: cg_swi(a); break; case CL_SWP: cg_swp(a); break; case CL_BR: cg_bl(a); break; case CL_COP: cg_cop(a); break; case CL_CMEM: cg_cmem(a); break; case CL_NOP: emitreg4(J_NULLOP, 0, 0, 0, 0, 0); break; default: break; } } static void cg_thumb_data(const AsmInstr *a) { J_OPCODE op; VRegnum r1, r2, r3; bool const_opnd = h0_(asmopnd3_(a)) == s_integer; bool hireg_ok; if (const_opnd) r3 = intval_(asmopnd3_(a)); switch (INSTRCL(asmopcode_(a))) { case CL_MOV: switch (OPCODE(asmopcode_(a))) { case T_NEG: if (const_opnd) op = J_MOVR, r3 = -r3; else op = J_NEGR; break; case A_MVN: if (const_opnd) op = J_MOVR, r3 = ~r3; else op = J_NOTR; break; case A_MOV: op = J_MOVR; break; } break; case CL_SH: switch (OPCODE(asmopcode_(a))) { case T_ASR: op = J_SHRR + J_SIGNED; break; case T_LSR: op = J_SHRR + J_UNSIGNED; break; case T_LSL: op = J_SHLR + J_SIGNED; break; case T_ROR: op = J_RORR + J_UNSIGNED; break; } break; case CL_BIN: case CL_CMP: op = thumb_op_tab[OPCODE(asmopcode_(a))]; break; } if (const_opnd) op = J_RTOK(op); hireg_ok = (op == J_ADDR || op == J_CMPR || op == J_MOVR); r1 = get_reg(asmopnd1_(a)); if (hireg_ok) r2 = expr_reg(asmopnd2_(a)); else r2 = expr_loreg(asmopnd2_(a)); if (!const_opnd) { if (hireg_ok) r3 = expr_reg(asmopnd3_(a)); else r3 = expr_loreg(asmopnd3_(a)); } emitreg4(op, asmopcode_(a), r1, r2, r3, GAP); if (!const_opnd) free_reg(asmopnd3_(a), r3); free_reg(asmopnd2_(a), r2); if (hireg_ok) store_reg_pc(asmopnd1_(a), r1); else store_loreg(asmopnd1_(a), r1); } static void cg_thumb_mul(const AsmInstr *a) { VRegnum r1, r2, r3; r1 = get_reg(asmopnd1_(a)); r2 = expr_loreg(asmopnd2_(a)); if (h0_(asmopnd3_(a)) == s_integer) emitreg4(J_MULK, asmopcode_(a), r1, r2, intval_(asmopnd3_(a)), 0); else { r3 = expr_loreg(asmopnd3_(a)); emitreg4(J_MULR, asmopcode_(a), r1, r2, r3, GAP); free_reg(asmopnd3_(a), r3); if (r1 == r3) cc_err(asm_err_mul_conflict); } free_reg(asmopnd2_(a), r2); store_loreg(asmopnd1_(a), r1); } static void cg_thumb_ldmstm(const AsmInstr *a) { VRegnum r1, r3; uint32 op; op = OPCODE(asmopcode_(a)) == A_LDM ? J_LDM : J_STM; if (asmopcode_(a) & M_WB) op += J_LDMW - J_LDM; r1 = expr_reg_sp(asmopnd1_(a)); r3 = intval_(asmopnd3_(a)); emitreg4(op, asmopcode_(a), r1, GAP, r3, GAP); if (r3 == 0) cc_err(asm_err_ldm_empty); store_reg(asmopnd1_(a), r1); } static void cg_thumb_ldrstr(const AsmInstr *a) { VRegnum r1, r2, r3; bool is_load = OPCODE(asmopcode_(a)) == A_LDR; uint32 op; if (asmopcode_(a) & M_BYTE) op = J_LDRBR+J_ALIGN1; else if (asmopcode_(a) & M_HALF) op = J_LDRWR+J_ALIGN2; else op = J_LDRR+J_ALIGN4; if (!is_load) op += J_STRR - J_LDRR; if (asmopcode_(a) & M_SIGNED) op |= J_SIGNED; else if (is_load && op != J_LDRR+J_ALIGN4) op |= J_UNSIGNED; if (is_load) r1 = get_reg(asmopnd1_(a)); else r1 = expr_loreg(asmopnd1_(a)); r2 = expr_reg_sp(asmopnd2_(a)); /* always allow SP as base */ if (h0_(asmopnd3_(a)) == s_integer) { r3 = intval_(asmopnd3_(a)); emitreg4(J_RTOK(op), asmopcode_(a), r1, r2, r3, GAP); } else { r3 = expr_loreg(asmopnd3_(a)); emitreg4(op, asmopcode_(a), r1, r2, r3, GAP); free_reg(asmopnd3_(a), r3); } free_reg(asmopnd2_(a), r2); if (is_load) store_loreg(asmopnd1_(a), r1); else free_reg(asmopnd1_(a), r1); } /* TODO: cleanup branches and labels -> can be a lot simpler! */ void cg_thumb_instr(const AsmInstr *a) { uint32 cond = GETCC(asmopcode_(a)); if (usrdbg(DBG_LINE)) emitfl(J_INFOLINE, a->fl); curlex.fl = a->fl; if (OPCODE(asmopcode_(a)) == A_B) { LabBind *lab = (LabBind*) asmopnd1_(a); LabelNumber *l = lab->labinternlab; if (l == NULL) l = lab->labinternlab = nextlabel(); if (lab->labuses & l_defined) { if (cond == cur_cond) emitbranch(J_B, l); } else cond = cur_cond; } if (cond != cur_cond && cur_label != NULL) { /* finish current conditional block */ emitbranch(J_B, cur_label); start_new_basic_block(cur_label); cur_label = NULL; cur_cond = CC_AL; } if (OPCODE(asmopcode_(a)) == A_LABEL) /* create a new block with the label */ { LabBind *lab = (LabBind*) asmopnd1_(a); LabelNumber *l = lab->labinternlab; if (l == NULL) l = lab->labinternlab = nextlabel(); emitbranch(J_B, l); start_new_basic_block(l); cur_cond = cond = CC_AL; } if (cond != cur_cond && cond != CC_AL) { /* create a new block if instr is conditional */ LabelNumber *l; if (OPCODE(asmopcode_(a)) == A_B) { uint32 branch_cond; LabBind *lab = (LabBind*) asmopnd1_(a); l = lab->labinternlab; if (l == NULL) l = lab->labinternlab = nextlabel(); if (lab->labuses & l_defined) { branch_cond = cond; emitbranch(J_B + translate_cc(branch_cond), l); l = nextlabel(); cur_label = nextlabel(); emitbranch(J_B, l); start_new_basic_block (l); cur_cond = cond = CC_AL; } } else { l = nextlabel(); cur_label = nextlabel(); emitbranch(J_B + translate_cc(INVCC(cond)), cur_label); emitbranch(J_B, l); start_new_basic_block (l); cur_cond = cond; } } if (asmopcode_(a) & SET_CC) cur_cond = CC_NOT; switch (INSTRCL(asmopcode_(a))) { case CL_MOV: case CL_CMP: case CL_BIN: case CL_SH: cg_thumb_data(a); break; case CL_MUL: cg_thumb_mul(a); break; case CL_LDM: cg_thumb_ldmstm(a); break; case CL_MEM: cg_thumb_ldrstr(a); break; case CL_SWI: cg_swi(a); break; case CL_BR: cg_bl(a); break; case CL_NOP: emitreg4(J_NULLOP, 0, 0, 0, 0, 0); break; default: break; } } void cg_asm(Cmd * c) { AsmInstr *a = (AsmInstr *) cmd1e_(c); cg_asm_init(); for ( ; a != NULL; a = a->cdr) { #ifdef ARM_INLINE_ASSEMBLER cg_arm_instr(a); #endif #ifdef THUMB_INLINE_ASSEMBLER cg_thumb_instr(a); #endif } cg_asm_finish(); } #ifdef ARM_INLINE_ASSEMBLER static void gen_data(PendingOp *cur) { J_OPCODE op; uint32 shift; switch (cur->ic.flags & RN_OPND_MASK) { case RN_CONST: op = arm_op_tab [asminstr(cur->ic.flags)]; break; case RN_REG: op = J_KTOR (arm_op_tab [asminstr(cur->ic.flags)]); break; case RN_SHIFT: op = J_KTOR (arm_op_tab [asminstr(cur->ic.flags)]); switch (cur->ic.flags & SH_MASK) { case SH_LSL: shift = cur->ic.r4.i; break; case SH_LSR: shift = cur->ic.r4.i | SHIFT_RIGHT; break; case SH_ASR: shift = cur->ic.r4.i | SHIFT_RIGHT | SHIFT_ARITH; break; case SH_ROR: shift = cur->ic.r4.i | SHIFT_ARITH; break; case SH_RRX: shift = SHIFT_ARITH; break; /* RRX = ROR 0 */ } op |= shift << J_SHIFTPOS; break; case RN_SHIFT_REG: op = J_KTOR (arm_op_tab [asminstr(cur->ic.flags)]); switch (cur->ic.flags & SH_MASK) { case SH_LSL: shift = P_LSL; break; case SH_LSR: shift = P_LSR; break; case SH_ASR: shift = P_ASR; break; case SH_ROR: shift = P_ROR; break; case SH_RRX: ;/* Error */ } cur->peep |= shift; break; } cur->ic.op = (cur->ic.op & ~J_TABLE_BITS) | op; if (cur->ic.flags & SET_CC) cur->peep |= P_CMPZ | P_SETCC; } static void gen_move(PendingOp *cur) { uint32 shift = (cur->ic.op & J_SHIFTMASK) >> J_SHIFTPOS; if ((cur->ic.op & J_TABLE_BITS) == J_MVNR) { cur->ic.op += J_NOTR - J_MVNR; return; } switch (cur->ic.flags & RN_OPND_MASK) { case RN_CONST: if ((cur->ic.op & J_TABLE_BITS) == J_MVNK) { cur->ic.op += J_MOVK - J_MVNK; cur->ic.r3.i = ~cur->ic.r3.i; } break; case RN_REG: break; case RN_SHIFT: cur->ic.r2.r = cur->ic.r3.r; if (cur->dataflow & J_DEAD_R3) cur->dataflow ^= J_DEAD_R3 + J_DEAD_R2; if (shift & SHIFT_RIGHT) { if (shift & SHIFT_ARITH) cur->ic.op = J_SHRK+J_SIGNED; else cur->ic.op = J_SHRK+J_UNSIGNED; } else if (shift & SHIFT_ARITH) cur->ic.op = J_RORK; else cur->ic.op = J_SHLK+J_UNSIGNED; if ((shift & 31) == 0 && (cur->ic.op == J_SHRK+J_UNSIGNED || cur->ic.op == J_SHRK+J_SIGNED)) cur->ic.r3.i = 32; else cur->ic.r3.i = shift & 31; break; case RN_SHIFT_REG: cur->ic.r2.r = cur->ic.r3.r; cur->ic.r3.r = cur->ic.r4.r; if (cur->dataflow & J_DEAD_R3) cur->dataflow ^= J_DEAD_R3 + J_DEAD_R2; if (cur->dataflow & J_DEAD_R4) cur->dataflow ^= J_DEAD_R4 + J_DEAD_R3; switch (cur->peep & P_RSHIFT) { case P_LSR: cur->ic.op = J_SHRR+J_UNSIGNED; break; case P_ASR: cur->ic.op = J_SHRR+J_SIGNED; break; case P_LSL: cur->ic.op = J_SHLR+J_UNSIGNED; break; case P_ROR: cur->ic.op = J_RORR; break; default: ;/* Error */ } cur->peep &= ~(P_LSR | P_LSL | P_ASR | P_ROR); break; } } static void gen_ldrstr(PendingOp *cur) { uint32 op, shift; bool is_load = OPCODE(cur->ic.flags) == A_LDR; if (cur->ic.flags & M_BYTE) op = J_LDRBR+J_ALIGN1; else if (cur->ic.flags & M_HALF) op = J_LDRWR+J_ALIGN2; else op = J_LDRR+J_ALIGN4; if (!is_load) op += J_STRR - J_LDRR; if (cur->ic.flags & M_SIGNED) op |= J_SIGNED; else if (is_load && op != J_LDRR+J_ALIGN4) op |= J_UNSIGNED; if (cur->ic.flags & M_WB) if (cur->ic.flags & M_PREIDX) cur->peep |= P_PRE; else cur->peep |= P_POST; if (!cur->ic.flags & M_UPIDX) op += J_NEGINDEX; if (cur->ic.flags & M_TRANS) cur->peep |= P_TRANS; switch (cur->ic.flags & RN_OPND_MASK) { case RN_CONST: op = J_RTOK(op); break; case RN_REG: break; case RN_SHIFT: switch (cur->ic.flags & SH_MASK) { case SH_LSL: shift = cur->ic.r4.i; break; case SH_LSR: shift = cur->ic.r4.i | SHIFT_RIGHT; break; case SH_ASR: shift = cur->ic.r4.i | SHIFT_RIGHT | SHIFT_ARITH; break; case SH_ROR: shift = cur->ic.r4.i | SHIFT_ARITH; break; case SH_RRX: shift = SHIFT_ARITH; break; /* RRX = ROR 0 */ } op |= shift << J_SHIFTPOS; break; default: ;/* Error */ } cur->ic.op = op; } void translate_asm_instr (PendingOp *cur) { switch (INSTRCL (cur->ic.flags)) { case CL_BIN: gen_data(cur); break; case CL_CMP: gen_data(cur); if (cur->ic.r1.r == 15) /* TEQP & friends */ cur->peep |= P_SETPSR; break; case CL_MOV: gen_data(cur); gen_move(cur); /* extra translation for moves */ break; case CL_MEM: gen_ldrstr(cur); break; } } #endif
stardot/ncc
mip/coff.h
<gh_stars>0 /* mip/coff.h: data structures and constants for COFF, */ /* loosely taken from Unix sysV operating system programmer's guide. */ /* version 1d. */ /* Copyright (C) Codemist Ltd, 1988, 1991. */ /* SPDX-Licence-Identifier: Apache-2.0 */ /* MIPS parts: (C) Copyright 1984 by Third Eye Software, Inc. */ /* Third Eye Software, Inc. grants reproduction and use rights to */ /* all parties, PROVIDED that this comment is maintained in the copy. */ /* The following is NOT a full definition of COFF -- it includes */ /* only those parts required by the Norcroft compiler suite. */ struct filehdr { unsigned short f_magic; unsigned short f_nscns; long f_timdat; long f_symptr; /* beware: MIPS is symbolic header ptr */ long f_nsyms; /* on MIPS is sizeof symbolic header. */ unsigned short f_opthdr; unsigned short f_flags; }; #ifdef TARGET_IS_MIPS /* On MIPS targets, there must be an 'optional' header... */ #define OMAGIC 0407 #ifdef TARGET_IS_STARDENT #define MIPSvstamp 0x1a00 #else #define MIPSvstamp 0x011f #endif typedef struct aouthdr { short magic; /* see above */ short vstamp; /* version stamp */ long tsize; /* text size in bytes, padded to DW bdry*/ long dsize; /* initialized data " " */ long bsize; /* uninitialized data " " */ long entry; /* entry pt. */ long text_start; /* base of text used for this file */ long data_start; /* base of data used for this file */ long bss_start; /* base of bss used for this file */ #ifdef TARGET_IS_STARDENT long FIX_flags; /* bits describing h'ware fixes applied */ long tlsize; /* thread-local data area size */ long tl_start; /* starting address of thread-local */ long stack_start; /* starting address of stack */ long stamp; /* version/testing stamp */ #else long gprmask; /* general purpose register mask */ long cprmask[4]; /* co-processor register masks */ #endif long gp_value; /* the gp value used for this object */ } AOUTHDR; #define GP_DISP 0x8000 #endif struct scnhdr { char s_name[8]; long s_paddr; long s_vaddr; long s_size; long s_scnptr; long s_relptr; #ifndef TARGET_IS_STARDENT long s_lnnoptr; #ifdef TARGET_IS_88000 unsigned long s_nreloc; unsigned long s_nlnno; #else unsigned short s_nreloc; unsigned short s_nlnno; #endif #else unsigned s_nreloc; /* the (new) number of reloc. entries */ unsigned short o_nreloc; /* the old nreloc */ unsigned short filler2; /* number of line numbers (not used) */ #endif long s_flags; }; #define STYP_TEXT 0x20 #define STYP_DATA 0x40 #define STYP_BSS 0x80 /* relocation records ... */ struct reloc { long r_vaddr; #ifdef TARGET_IS_MIPS unsigned r_symndx:24, /* index into symbol table */ r_reserved:3, r_type:4, /* relocation type */ r_extern:1; /* if 1 symndx is an index into the external symbol table, else symndx is a section # */ # define RELSZ sizeof(struct reloc) #else long r_symndx; unsigned short r_type; #ifdef TARGET_IS_88000 unsigned short r_offset; /* ??? high 16 bits of expressions ??? */ # define RELSZ sizeof(struct reloc) #else # define RELSZ 10 /* probably sizeof(struct reloc) = 12 */ /* many hosts pad here */ #endif #endif }; /* Relocation types */ /* These are notionally system independent, but clipper R_DIR32 differs */ /* from I386. (Clipper follows ATT 3b2). Move to target.h? */ #ifdef TARGET_IS_MIPS /* * Mips machines * * 16-bit reference * 32-bit reference * 26-bit jump reference * reference to high 16-bits BUT what about carryout from LO??? * reference to low 16-bits * reference to global pointer relative data item * reference to global pointer relative literal pool item */ # define R_SN_TEXT 1 /* r_symndx values if r_extern == 0 */ # define R_SN_DATA 3 # define R_SN_BSS 6 # define R_REFHALF 1 /* r_type values. */ # define R_REFWORD 2 # define R_JMPADDR 3 # define R_REFHI 4 # define R_REFLO 5 # define R_GPREL 6 # define R_LITERAL 7 #else # ifndef TARGET_IS_88000 # ifdef TARGET_IS_I386 # define R_DIR32 6 # else # define R_DIR32 17 /* ATT 3b2, m68000, clipper */ # endif # ifdef TARGET_IS_ARM # define R_PCRLONG 20 # else # define R_PCRLONG 24 # endif # endif #endif /* symbol tables... */ #ifdef TARGET_IS_MIPS /* MIPS has a special symbol table(!) */ #define magicSym 0x7009 typedef struct { short magic; /* to verify validity of the table */ short vstamp; /* version stamp */ #ifdef TARGET_IS_STARDENT long filler1[15]; /* for Mips compatibility */ long issExtMax; /* strings_ct number of bytes of strings */ long cbSsExtOffset; /* strings_off offset of strings */ long comini_ct; /* initialized common data */ long comini_off; /* offset of initialized common data */ long address_ct; /* number of text-relocated addresses */ long address_off; /* offset of text-relocated addresses */ #else long ilineMax; /* number of line number entries */ long cbLine; /* number of bytes for line number entries */ long cbLineOffset; /* offset to start of line number entries*/ long idnMax; /* max index into dense number table */ long cbDnOffset; /* offset to start dense number table */ long ipdMax; /* number of procedures */ long cbPdOffset; /* offset to procedure descriptor table */ long isymMax; /* number of local symbols */ long cbSymOffset; /* offset to start of local symbols */ long ioptMax; /* max index into optimization symbol entries */ long cbOptOffset; /* offset to optimization symbol entries */ long iauxMax; /* number of auxillary (sic) symbol entries */ long cbAuxOffset; /* offset to start of auxillary symbol entries*/ long issMax; /* max index into local strings */ long cbSsOffset; /* offset to start of local strings */ long issExtMax; /* max index into external strings */ long cbSsExtOffset; /* offset to start of external strings */ long ifdMax; /* number of file descriptor entries */ long cbFdOffset; /* offset to file descriptor table */ long crfd; /* number of relative file descriptor entries */ long cbRfdOffset; /* offset to relative file descriptor table */ #endif long iextMax; /* max index into external symbols */ long cbExtOffset; /* offset to start of external symbol entries*/ /* If you add machine dependent fields, add them here */ } HDRR; typedef struct fdr { /* file descriptor entry (at least 1 needed) */ unsigned long adr; /* memory address of beginning of file */ long rss; /* file name (of source, if known) */ long issBase; /* file's string space */ long cbSs; /* number of bytes in the ss */ long isymBase; /* beginning of symbols */ long csym; /* count file's of symbols */ long ilineBase; /* file's line symbols */ long cline; /* count of file's line symbols */ long ioptBase; /* file's optimization entries */ long copt; /* count of file's optimization entries */ short ipdFirst; /* start of procedures for this file */ short cpd; /* count of procedures for this file */ long iauxBase; /* file's auxiliary entries */ long caux; /* count of file's auxiliary entries */ long rfdBase; /* index into the file indirect table */ long crfd; /* count file indirect entries */ unsigned lang: 5; /* language for this file */ unsigned fMerge : 1; /* whether this file can be merged */ unsigned fReadin : 1; /* true if it was read in (not just created) */ unsigned fBigendian : 1;/* if set, was compiled on big endian machine */ /* aux's will be in compile host's sex */ unsigned glevel : 2; /* level this file was compiled with */ unsigned reserved : 22; /* reserved for future use */ long cbLineOffset; /* byte offset from header for this file ln's */ long cbLine; /* size of lines for this file */ } FDR; #ifdef TARGET_IS_STARDENT typedef struct { unsigned auxval; /* offset for initialization */ unsigned iss; /* index into string table */ int value; /* size for common, value for others */ unsigned flags:8, /* what sort of value */ index:24; /* hash of common block fill */ } DL_XSYM; /* flags */ /* for Mips compatibility, they go up by 4's */ # define DL_NIL 0x00 # define DL_TEXT 0x04 # define DL_DATA 0x08 # define DL_BSS 0x0c # define DL_COMM 0x010 # define DL_ABS 0x014 /* DL_UNDEF is needed only to distinguish from DL_NIL (== ignored) */ # define DL_UNDEF 0x018 # define DL_COMINI 0x01c # define DL_THREAD 0x001 # define DL_ENTRY 0x002 /* for FORTRAN entry point */ # define DL_DEF 0x020 /* symbol is defined/initialized */ # define DL_LOCAL 0x40 /* local scope for symbol */ # define DL_FLAG 0x80 /* flag to mark old common regions */ #else typedef struct { /* (internal) symbol record */ long iss; /* index into String Space of name */ long value; /* value of symbol */ unsigned st : 6; /* symbol type */ unsigned sc : 5; /* storage class - text, data, etc */ unsigned reserved : 1; /* reserved */ unsigned index : 20; /* index into sym/aux table */ } SYMR; #define scNil 0 #define scText 1 /* text symbol */ #define scData 2 /* initialized data symbol */ #define scBss 3 /* un-initialized data symbol */ #define scUndefined 6 /* who knows? */ #define stGlobal 1 /* external symbol */ typedef struct { /* (external) symbol record */ #ifdef never unsigned jmptbl:1; /* symbol is a jump table entry for shlibs */ unsigned cobol_main:1; /* symbol is a cobol main procedure */ unsigned reserved:14; /* reserved for future use */ #else short reserved; #endif short ifd; /* where the iss and index fields point into */ SYMR asym; /* symbol for the external */ } EXTR; #endif #define indexNil 0xfffff #else /* TARGET_IS_MIPS */ #define SYMNMLEN 8 struct syment { union { char _n_name[SYMNMLEN]; struct { long _n_zeroes; long _n_offset; } _n_n; } _n; unsigned long n_value; short n_scnum; unsigned short n_type; char n_sclass; char n_numaux; #ifdef TARGET_IS_88000 char n_pad1, n_pad2; # define SYMESZ sizeof(struct syment) #else # define SYMESZ 18 /* probably sizeof(struct reloc) = 20 */ /* many hosts pad here */ #endif }; #define n_name _n._n_name #define n_zeroes _n._n_n._n_zeroes #define n_offset _n._n_n._n_offset #define N_UNDEF 0 #define T_NULL 0 #define C_EXT 2 #define C_STAT 3 #endif /* TARGET_IS_MIPS */ /* end of coff.h */
stardot/ncc
mip/jopprint.c
<filename>mip/jopprint.c /* * file jopprint.c - things maybe used while debugging compiler * Copyright (C) Codemist Ltd., April 1986. * Copyright (C) Acorn Computers Ltd., 1988. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 23 * Checkin $Date$ * Revising $Author$ */ #ifdef __STDC__ # include <string.h> # include <stdarg.h> # include <stdlib.h> #else # include <strings.h> # include <varargs.h> #endif #include "globals.h" #include "cgdefs.h" #include "store.h" #define DEFINE_JOPTABLE 1 #include "jopcode.h" #include "aeops.h" #include "aetree.h" /* for pr_stringsegs */ #include "flowgraf.h" /* for is_exit_label */ #if defined ENABLE_CG || defined ENABLE_REGS || defined ENABLE_CSE char *condition_name(uint32 w) /* only for print_opname(). Argument already masked with Q_MASK */ { char *op; switch(w) { case Q_EQ: op = "(if EQ)"; break; case Q_NE: op = "(if NE)"; break; case Q_HS: op = "(if HS)"; break; case Q_LO: op = "(if LO)"; break; case Q_MI: op = "(if MI)"; break; case Q_PL: op = "(if PL)"; break; case Q_VS: op = "(if VS)"; break; case Q_VC: op = "(if VC)"; break; case Q_HI: op = "(if HI)"; break; case Q_LS: op = "(if LS)"; break; case Q_GE: op = "(if GE)"; break; case Q_LT: op = "(if LT)"; break; case Q_GT: op = "(if GT)"; break; case Q_LE: op = "(if LE)"; break; case Q_AL + Q_UBIT: /* bits moved, rationalise */ case Q_AL: op = " "; break; case Q_UEQ: op = "(ifUEQ)"; break; case Q_UNE: op = "(ifUNE)"; break; case Q_UKN + Q_UBIT: case Q_UKN: op = "(ifUKN)"; break; default: { static char opbuf[12]; op = opbuf; sprintf(opbuf, "(Q_%.2x???)", (Uint)(w >> 24)); break; } } return op; } extern void jopprint_opname(J_OPCODE o) { char v[20]; strcpy(v, joptable[o & J_TABLE_BITS].name); if (o & J_SIGNED) strcat(v, "s"); if (o & J_UNSIGNED) strcat(v, "u"); if (o & J_ALIGNMENT) strcat(v, ((o & J_ALIGNMENT) >> J_ALIGNPOS)*3 + "a1\0a2\0a4\0a8"); if (o & J_BASEALIGN4) strcat(v, "w"); #if defined TARGET_HAS_SCALED_ADDRESSING || defined TARGET_HAS_SCALED_OPS || \ defined TARGET_HAS_SCALED_ADD if (o & J_NEGINDEX) strcat(v, "m"); if (o & J_SHIFTMASK) { int32 m = (o & J_SHIFTMASK) >> J_SHIFTPOS; if ((m & SHIFT_RIGHT) == 0) strcat(v, "<<"); else if (m & SHIFT_ARITH) strcat(v, ">>"); else strcat(v, ">>L"); sprintf(v+strlen(v), "%ld", (long)(m & SHIFT_MASK)); } #endif cc_msg("%-12s", v); } typedef struct BindListIndex BindListIndex; struct BindListIndex { /* int32 */ IPtr h0; /* same h0 field as a Binder (for puns) */ BindListIndex *next; Binder *binder; BindList *bindlist; }; static unsigned32 bindlist_n; static BindListIndex *bindlist_index; void pr_bindlist(BindList *p) { int ch = '{'; for (; p!=NULL; p = p->bindlistcdr) { Binder *b = p->bindlistcar; if (bindlist_n != 0) { if (h0_(b) == s_binder) { if (ch == '{') { BindListIndex *bi = (BindListIndex *)SynAlloc(sizeof(BindListIndex)); h0_(bi) = ++bindlist_n; bi->binder = b; bi->next = bindlist_index; bi->bindlist = p; bindlist_index = bi; p->bindlistcar = (Binder *)bi; cc_msg("%c#%ld= $b", ch, (long)bindlist_n ^ 0x80000000, b); } else cc_msg("%c$b", ch, b); ch = ','; } else { unsigned32 bindlist_nn = (unsigned32)h0_(b); cc_msg("%c#%ld#}", ch, (long)bindlist_nn ^ 0x80000000); return; } } else { cc_msg("%c$b", ch, b); ch = ','; } } cc_msg("%s", (ch=='{') ? "{}" : "}"); } static void pr_bindlist_head(BindList *p, int32 n) { int ch = '{'; for (; --n >= 0; p = p->bindlistcdr, ch = ',') cc_msg("%c$b", ch, p->bindlistcar); cc_msg("%c*}", ch); } static void pr_argdesc(int32 d) { #ifdef TARGET_FP_ARGS_IN_FP_REGS /* TARGET_FP_ARGS_CALLSTD1 */ cc_msg("%ld(%ld,%ld", k_argwords_(d), k_intregs_(d), k_fltregs_(d)); #else cc_msg("%ld(", k_argwords_(d)); #endif /*if (k_resultregs_(d) > 1) */cc_msg("=>%ld", k_resultregs_(d)); cc_msg(")"); if (d & K_SPECIAL_ARG) cc_msg("[+]");/* + implicit arg */ if (d & K_PURE) cc_msg("P"); if (d & K_COMMUTATIVE) cc_msg("C"); if (d & K_INLINE) cc_msg("I"); /* will be inlined */ if (d & K_VACALL) cc_msg("..."); /* call vararg fn */ } void jopprint_op3(J_OPCODE op, VRegInt r2, VRegInt r3) { if (uses_stack(op) || op == J_CALLK || op == J_TAILCALLK || op==J_ADCON || op == J_INIT || op == J_INITF || op == J_INITD) { Binder *bb = r3.b; if (bb == NULL || h0_(bb) == s_identifier) /* To allow print_jopcode to be called from local cgs */ cc_msg("$r", (Symstr *)bb); else { cc_msg("$b", bb); if (bindstg_(bb) & bitofstg_(s_auto)) { VRegnum r = bindxx_(bb); if (r != GAP) cc_msg(" [r%ld]", (long)r); } } } else if (uses_r3(op)) { if (r3.r == GAP) cc_msg("<**missing register**>"); else cc_msg("%ld", (long)r3.r); } else switch (op) { case J_MOVDK: case J_CMPDK: case J_ADDDK: case J_SUBDK: case J_MULDK: case J_DIVDK: case J_MOVFK: case J_CMPFK: case J_ADDFK: case J_SUBFK: case J_MULFK: case J_DIVFK: case J_ADCONF:case J_ADCOND: if (r3.f->floatstr[0] == '<') { DbleBin db, *dp; char b[128]; if (r3.f->floatlen == ts_float) { fltrep_widen(&r3.f->floatbin.fb, &db); dp = &db; } else dp = &r3.f->floatbin.db; fltrep_sprintf(b, "%g", dp); cc_msg("<expr = %s>", b); } else cc_msg("%s", r3.f->floatstr); break; case J_ADCONLL: pr_int64(&r3.i64->bin.i); break; case J_ENDPROC: cc_msg("-"); break; case J_B: case J_BXX: case J_LABEL: cc_msg("L%ld", (long)lab_xname_(r3.l)); break; case J_ENTER: case J_SAVE: pr_argdesc(r3.i); break; case J_STRING: pr_stringsegs(r3.s); break; case J_SETSPENV: if (bindlist_n == 0 && r3.bl != NULL && r2.bl != NULL) { int32 lm = length((List *)r3.bl); int32 lr2 = length((List *)r2.bl); if (lm > lr2) { pr_bindlist_head(r3.bl, lm - lr2); cc_msg(" from "); pr_bindlist(r2.bl); } else { pr_bindlist(r3.bl); cc_msg(" from "); pr_bindlist_head(r2.bl, lr2 - lm); } } else { pr_bindlist(r3.bl); cc_msg(" from "); pr_bindlist(r2.bl); } break; case J_SETSPGOTO: cc_msg("L%ld from ", (long)lab_xname_(r3.l)); pr_bindlist(r2.bl); break; default: cc_msg("%ld", (long)r3.i); if (r3.i > 1000 || r3.i < -1000) cc_msg(" [%#lx]", (long)r3.i); break; } } void print_jopcode_1(const Icode *const ic) { const J_OPCODE op = ic->op & J_TABLE_BITS; cc_msg("%8s", condition_name(ic->op & Q_MASK)); jopprint_opname(ic->op & ~J_DEADBITS); if (gap_r1(op)) cc_msg("-, "); else if (uses_r1(op) || pseudo_reads_r1(op)) { if (ic->r1.r == GAP) cc_msg("-, "); else cc_msg("%ld, ", (long)ic->r1.r); } else cc_msg("%ld, ", (long)ic->r1.i); if (gap_r2(op) || (pseudo_reads_r2(op) && ic->r2.r == GAP)) cc_msg("-, "); else if (op==J_INFOLINE || op==J_COUNT) cc_msg("'%s', ", ic->r2.str); else if (op==J_CALLK || op==J_CALLR || op==J_OPSYSK || op==J_TAILCALLK || op==J_TAILCALLR) { pr_argdesc(ic->r2.i); cc_msg(", "); } else cc_msg("%ld, ", (long)((uses_r2(op) || pseudo_reads_r2(op)) ? ic->r2.r : ic->r2.i)); jopprint_op3(op, ic->r2, ic->r3); if (uses_r4(op)) { if (ic->r4.r == GAP) cc_msg("<**missing register**>"); else cc_msg(", %ld", (long)ic->r4.r); } if (ic->flags != 0) cc_msg(" {%x}", ic->flags); } void print_jopcode(const Icode *const ic) { const J_OPCODE op = ic->op & ~J_DEADBITS; cc_msg(" "); print_jopcode_1(ic); cc_msg("\n"); if (op == J_CASEBRANCH || op == J_THUNKTABLE) { Icode ib; LabelNumber **v = ic->r2.lnn; int32 i, ncase = ic->r3.i; ib.op = J_BXX; ib.flags = 0; ib.r1.r = ib.r2.r = ib.r4.r = GAP; for (i=0; i<ncase; i++) { ib.r3.l = v[i]; print_jopcode(&ib); } } } void flowgraf_printblock(BlockHead *p, bool deadbits) { Icode *c = blkcode_(p), *limit; cc_msg("L%li: ", (long)lab_name_(blklab_(p))); if (c == (Icode *)DUFF_ADDR && blklength_(p) > 0) { cc_msg("block eliminated by crossjumping\n\n"); return; } if (blkflags_(p) & BLKSTACKI) cc_msg("stack %ld\n", blkstacki_(p)); else { pr_bindlist(blkstack_(p)); cc_msg("\n"); } for (limit = c + blklength_(p); c < limit; ++c) { if (deadbits) cc_msg("%c%c%c%c", (c->op & J_DEAD_R1 ? '1': '-'), (c->op & J_DEAD_R2 ? '2': '-'), (c->op & J_DEAD_R3 ? '3': '-'), (c->op & J_DEAD_R4 ? '4': '-')); print_jopcode(c); } if (!(blkflags_(p) & BLKSWITCH)) { Icode ib; ib.flags = 0; ib.r1.r = ib.r2.r = ib.r3.r = ib.r4.r = GAP; if (blkflags_(p) & BLK2EXIT) { if (deadbits) cc_msg(" "); ib.op = J_B + (blkflags_(p) & Q_MASK); ib.r3.l = blknext1_(p); print_jopcode(&ib); } if (!(blkflags_(p) & BLK0EXIT)) { if (deadbits) cc_msg(" "); ib.op = J_B; ib.r3.l = blknext_(p); print_jopcode(&ib); } } } static void flowgraf_print_start(void) { bindlist_n = 0x80000000; bindlist_index = NULL; } static void flowgraf_print_end(void) { BindListIndex *p = bindlist_index; for (; p != NULL; p = p->next) p->bindlist->bindlistcar = p->binder; bindlist_index = NULL; bindlist_n = 0; } void flowgraf_print(const char *mess, bool deadbits) { BlockHead *p; cc_msg("\n\n%s\n\n", mess); flowgraf_print_start(); for (p = top_block; p != NULL; p = blkdown_(p)) flowgraf_printblock(p, deadbits); flowgraf_print_end(); } /* Q_implies : returns whether cond1 implies cond2 */ bool Q_implies(int32 cond1, int32 cond2) { cond1 &= Q_MASK; cond2 &= Q_MASK; if (cond1 == Q_UNDEF || cond2 == Q_UNDEF || (cond1 & ~Q_UBIT) == Q_UKN || (cond2 & ~Q_UBIT) == Q_UKN) return NO; /* equal condition: a == b -> a == b */ if (cond1 == cond2) return YES; if ((cond1 == Q_UEQ || cond1 == Q_EQ) && (cond2 == Q_EQ || cond2 == Q_UEQ)) return YES; if ((cond1 == Q_UNE && cond1 == Q_NE) && (cond2 == Q_NE || cond2 == Q_UNE)) return YES; /* narrowing condition: a == b -> a >= b */ if ((cond1 == Q_EQ || cond1 == Q_UEQ) && (cond2 == Q_GE || cond2 == Q_LE || cond2 == Q_HS || cond2 == Q_LS)) return YES; /* narrowing condition: a > b -> a >= b */ if (cond1 == Q_GT && cond2 == Q_GE) return YES; if (cond1 == Q_LT && cond2 == Q_LE) return YES; if (cond1 == Q_HI && cond2 == Q_HS) return YES; if (cond1 == Q_LO && cond2 == Q_LS) return YES; /* narrowing condition: a > b -> a != b */ if ((cond2 == Q_NE || cond2 == Q_UNE) && (cond1 == Q_GT || cond1 == Q_HI || cond1 == Q_LT || cond1 == Q_LO)) return YES; return NO; } #else void print_jopcode_1(const Icode *const ic) { IGNORE(ic); } void print_jopcode(const Icode *const ic) { IGNORE(ic); } void flowgraf_print(const char *mess) { IGNORE(mess); } #endif #ifdef ENABLE_REGS void print_xjopcode(const Icode *const ic, char *fmt, ...) { va_list ap; char b[256]; va_start(ap, fmt); print_jopcode_1(ic); vsprintf(b, fmt, ap); cc_msg(" %s\n", b); va_end(ap); /* since this is only used by regalloc we do not need to print out */ /* branch tables of CASEBRANCH as it never calls it with such things */ } #else void print_xjopcode(const Icode *const ic, char *fmt, ...) { IGNORE(ic); IGNORE(fmt); } #endif /* end of jopprint.c */
stardot/ncc
tests/1192.c
/* * ARM C compiler regression test $RCSfile$ * Copyright (C) 1995 Advanced Risc Machines Ltd. All rights reserved. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <stdio.h> #include "testutil.h" #define BUFFER_SECS 2 #define SAMPLERATE 500 #define DATAMUX 12 #define BUFFER_SAMPLES ( BUFFER_SECS* SAMPLERATE* DATAMUX) #define FDS1 8 /* forward shift #1 (anticipate) @ 250 sps */ #define FDS2 16 /* forward shift #2 (anticipate) @ 250 sps */ #define BDS1 8 /* backward shift #1 (delay) @ 250 sps */ #define FWDEL1 (DATAMUX*FDS1*(SAMPLERATE/250)) #define FWDEL2 (DATAMUX*FDS2*(SAMPLERATE/250)) #define BKDEL1 (DATAMUX*BDS1*(SAMPLERATE/250)) short DataBuf[BUFFER_SAMPLES]; short FilterSum( short *pdata, short bndflt[]); short FilterSum( short *pdata, short bndflt[]) { unsigned short leads, ix; short fil_sig, fil_sig_part1, fil_sig_part2,sumdtr; leads = 0x72; /* set bits for the 4 channels to use */ ix = 0; sumdtr = 0; /* NOTE: adding any function call in this function will eliminate the * problem */ for (; leads != 0; leads = leads << 1) { if (leads & 0x80) { fil_sig_part1 = *pdata; fil_sig = fil_sig_part1 << 1; fil_sig = -fil_sig; fil_sig_part2 = *(pdata + FWDEL1); fil_sig += fil_sig_part2; fil_sig += *(pdata - BKDEL1); fil_sig += bndflt[ ix]; fil_sig_part2 *= 2; fil_sig_part1 -= fil_sig_part2; fil_sig_part1 += *(pdata + FWDEL2); fil_sig_part1 += bndflt[ ix+4]; bndflt[ ix+4] = fil_sig_part1; bndflt[ ix++] = fil_sig; fil_sig_part1 -= fil_sig; if (fil_sig_part1 < 0) fil_sig_part1 = -fil_sig_part1; fil_sig_part1 = fil_sig_part1 >> 2; sumdtr += fil_sig_part1; } pdata++; } sumdtr = sumdtr >> 1; return( sumdtr); } int main(int argc, char *argv[] ) { short sum,bndfltr[8]; int i; BeginTest(); /* fill data buffer with dummy data */ for ( i = 0; i < BUFFER_SAMPLES; i++ ) DataBuf[i] = (short)((i*17)&0xfff); for ( i = 0; i < 8; i++ ) bndfltr[i] = 0; sum = FilterSum( &DataBuf[BUFFER_SAMPLES/2], bndfltr); EQI(sum, 2048); EQI(bndfltr[0], -4096); EQI(bndfltr[1], -4096); EQI(bndfltr[2], -4096); EQI(bndfltr[3], -4096); EQI(bndfltr[4], 0); EQI(bndfltr[5], 0); EQI(bndfltr[6], 0); EQI(bndfltr[7], 0); EndTest(); return(0); }
stardot/ncc
mip/miperrs.h
<gh_stars>0 /* * C compiler error prototype file (miperrs.h) * Copyright (C) Codemist Ltd, 1988. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 151 * Checkin $Date$ * Revising $Author$ */ /* * This file is input to the genhdrs utility, which can compress error * strings (but leaving escape sequences alone so that format checking can * occur) and optionally mapping syserr messages onto numeric codes * (in case somebody wants to save the about 4Kbytes of memory involved). */ /* AM: (after discussion with LDS) It would seem that error texts below */ /* which (seriously) take 2 or more arguments should be of the form */ /* #define ermsg(a,b,c) "ho hum %s had a %s %s", a, b, c */ /* etc. to allow different sentence order in other (natural) languages. */ /* One nice thing would be to have a variant form of $r (etc) which did */ /* not quote its arg to avoid many uses of symname_() in the code. */ %Z /* Don't compress #include strings! */ #include "msg.h" #if defined(__CC_NORCROFT) && !defined(NLS) /* * The next procedure takes a string as a format... check args. */ #pragma -v3 #endif /* cc_msg has been left in globals.h since it takes an uncompressed string */ extern void cc_rerr(msg_t errcode, ...); extern void cc_ansi_rerr(msg_t errcode, ...); extern void cc_warn(msg_t errcode, ...); extern void cc_ansi_warn(msg_t errcode, ...); extern void cc_pccwarn(msg_t errcode, ...); extern void cc_err(msg_t errcode, ...); extern void cc_fatalerr(msg_t errcode, ...); extern void cc_rerr_cwarn(msg_t errorcode, ...); extern void cc_rerr_cppwarn(msg_t errorcode, ...); #if defined(__CC_NORCROFT) && !defined(NLS) /* * End of procedures that take error strings or codes. */ #pragma -v0 #endif extern void push_fnap_context(Binder* fn); /* NULL fn ok */ extern void set_fnap_arg(int); extern void pop_fnap_context(void); extern void push_nested_context(msg_t, IPtr arg1, IPtr arg2); extern void pop_nested_context(void); #ifdef NLS # include "tags.h" /* Under NLS, use tag versions */ #else %O /* Map strings to offsets in compressed string table */ #define warn_option_letter "unknown option -%c%c: ignored" #define warn_option_g "unknown debugging option -g%c: -g assumed" #define warn_option_zq "unknown option -zq%c: ignored" #define warn_preinclude "can't open pre-include file %s (ignored)" #define warn_option_E \ "Obsolete use of '%s' to suppress errors -- use '-zu' for PCC mode" #define warn_option_p "unknown profile option %s: -p assumed" #define warn_option "unknown option %s: ignored" #define warn_usage_rw \ "undefined behaviour: $b written and read without intervening sequence point" #define warn_usage_ww \ "undefined behaviour: $b written twice without intervening sequence point" /* Preprocessor messages. Here presumably because the preprocessor can be shared between different language front-ends. But then why is pp.[ch] in cfe? */ #define pp_warn_triglyph \ "ANSI '%c%c%c' trigraph for '%c' found - was this intended?" #define pp_warn_nested_comment "character sequence %s inside comment" #define pp_warn_many_arglines \ "(possible error): >= %lu lines of macro arguments" #define pp_warn_redefinition "repeated definition of #define macro %s" #define pp_warn_ifvaldef "#ifdef %s may indicate trouble..." /* MACH_EXTNS */ #define pp_warn_nonansi_header "Non-ANSI #include <%s>" #define pp_warn_bad_pragma "Unrecognised #pragma (no '-' or unknown word)" #define pp_warn_bad_pragma1 "Unrecognised #pragma -%c" #define pp_warn_unused_macro "#define macro '%s' defined but not used" #define pp_warn_unbalanced "Unbalanced #if/#ifdef/#ifndef/#endif in file" #define pp_warn_macro_arg_exp_in_string "argument %s of macro %s expanded in %c...%c" #define pp_warn_pragma_suppress "#pragma -b suppresses errors (hence non-ANSI)" #define pp_warn_not_guarded "Header file not guarded against multiple inclusion" #define pp_warn_guard_not_defined "File is guarded by '%s' but does not #define it" #define pp_warn_continued_comment "trailing '\\' continues comment" #define pp_warn_directive_in_args \ "preprocessor directive ignored in macro argument list\n" #define pp_warn_eol_string_skipped "Unmatched quote (%c) in skipped line" #define pp_rerr_redefinition "differing redefinition of #define macro %s" #define pp_rerr_nonunique_formal "duplicate macro formal parameter: '%s'" #define pp_rerr_define_hash_arg "operand of # not macro formal parameter" #define pp_rerr_define_hashhash "## first or last token in #define body" #define pp_rerr_newline_eof "missing newline before EOF - inserted" #define pp_rerr_nonprint_char "unprintable char %#.2x found - ignored" #define pp_rerr_illegal_option "illegal option -D%s%s" #define pp_rerr_spurious_else "spurious #else ignored" #define pp_rerr_spurious_elif "spurious #elif ignored" #define pp_rerr_spurious_endif "spurious #endif ignored" #define pp_rerr_hash_line "number missing in #line" #define pp_rerr_hash_error "#error encountered \"%s\"" #define pp_rerr_hash_ident "#ident is not in ANSI C" #define pp_rerr_junk_eol "junk at end of #%s line - ignored" #define pp_err_eof_comment "EOF in comment" #define pp_err_eof_string "EOF in string" #define pp_err_eol_string "quote (%c) inserted before newline" #define pp_err_eof_escape "EOF in string escape" #define pp_err_missing_quote "Missing '%c' in pre-processor command line" #define pp_err_if_defined "No identifier after #if defined" #define pp_err_if_defined1 "No ')' after #if defined(..." #define pp_err_rpar_eof "Missing ')' after %s(... on line %ld" #define pp_err_many_args "Too many arguments to macro %s(... on line %ld" #define pp_err_few_args "Too few arguments to macro %s(... on line %ld" #define pp_err_missing_identifier "Missing identifier after #define" #define pp_err_missing_parameter "Missing parameter name in #define %s(..." #define pp_err_missing_comma "Missing ',' or ')' after #define %s(..." #define pp_err_undef "Missing identifier after #undef" #define pp_err_ifdef "Missing identifier after #ifdef" #define pp_err_include_quote "Missing '<' or '\"' after #include" #define pp_err_include_junk "Junk after #include %c%s%c" #define pp_err_include_file "#include file %c%s%c wouldn't open" #define pp_err_unknown_directive "Unknown directive: #%s" #define pp_err_endif_eof "Missing #endif at EOF" #define pp_fatalerr_hash_error "#error encountered \"%s\"" #define pp_fatalerr_readfail "Host file system read error\n" #define bind_warn_extern_clash \ "extern clash $r, $r clash (ANSI 6 char monocase)" #define bind_warn_unused_static_decl "unused earlier static declaration of $r" #define bind_warn_not_in_hdr "extern $r not declared in header" #define bind_warn_main_not_int "extern 'main' needs to be 'int' function" #define bind_warn_label_not_used "label $r was defined but not used" /* * Note that when part of an error string MUST be stored as a regular * non-compressed string I have to inform the GenHdrs utility with %Z and %O * This arises when a string contains literal strings as extra sub-args. */ /* No longer applies to bind_warn_*_not_used, though */ #define bind_warn_typedef_not_used "typedef $b declared but not used" #define bind_warn_typename_not_used "typename $b declared but not used" #define bind_warn_function_not_used "function $b declared but not used" #define bind_warn_variable_not_used "variable $b declared but not used" #define bind_warn_static_not_used "static $b declared but not used" #define cg_warn_implicit_return "implicit return in non-void %s()" #define flowgraf_warn_implicit_return "implicit return in non-void function" #define regalloc_warn_use_before_set "$b may be used before being set" #define regalloc_warn_never_used "$b is set but never used" #define sem_warn_unsigned "ANSI surprise: 'long' $s 'unsigned' yields 'long'" #define sem_warn_format_type "actual type $t of argument %d mismatches format '%.*s'" #define sem_warn_bad_format "Illegal format conversion '%%%c'" #define sem_warn_incomplete_format "Incomplete format string" #define sem_warn_format_nargs_0 "Format requires 0 parameters, but %ld given" #define sem_warn_format_nargs_1 "Format requires 1 parameter, but %ld given" #define sem_warn_format_nargs_n "Format requires %ld parameters, but %ld given" #define sem_warn_addr_array "'&' unnecessary for function or array $e" #define sem_warn_bad_shift(_m,_n) "shift of $m by %ld undefined in ANSI C",_m,_n #define sem_warn_divrem_0 "division by zero: $s" #define sem_warn_fp_overflow(op) "floating point constant overflow: $s",op #define sem_warn_implicit_constructor "implicit constructor $t()" #define sem_warn_cast_sametype "explicit cast to same type" #define sem_warn_ctor_confused "user defined constructors confusing" #define sem_warn_structassign "structure assignment" #define sem_errwarn_udiad_overflow "unsigned constant overflow: $s" #define sem_errwarn_diad_overflow "signed constant overflow: $s" #define sem_errwarn_umonad_overflow "unsigned constant overflow: $s" #define sem_errwarn_monad_overflow "signed constant overflow: $s" #define sem_errwarn_bad_shift "overlarge shift distance" #define sem_errwarn_divrem_0 "division by zero: $s" #define sem_errwarn_ucomp_0 "odd unsigned comparison with 0: $s" #define sem_errwarn_ucomp_0_false "unsigned comparison with 0 is always false: $s" #define sem_errwarn_ucomp_0_true "unsigned comparison with 0 is always true: $s" #define sem_errwarn_fp_overflow "floating point constant overflow: $s" #define sem_rerr_udiad_overflow(op,_a,_b,_c) "unsigned constant overflow: $s",op #define sem_rerr_diad_overflow(op,_a,_b,_c) "signed constant overflow: $s",op #define sem_rerr_umonad_overflow(op,_a,_b) "unsigned constant overflow: $s",op #define sem_rerr_monad_overflow(op,_a,_b) "signed constant overflow: $s",op #define sem_rerr_implicit_cast_overflow(_t,_a,_b) \ "implicit cast (to $t) overflow",_t #define sem_rerr_implicit_cast5 \ "$s: implicit cast of pointer loses $m qualifier" #define sem_warn_depr_string \ "$s: deprecated conversion of string literal to pointer to non-const" #define sem_rerr_too_many_args_ovld "too many arguments for overload resolution" #define sem_rerr_postdecr_bool "operand of $s cannot be 'bool'" #define sem_rerr_opequal_bool \ "type of left operand of $s cannot be 'bool'" #define sem_warn_deprecated_bool "deprecated use: operand of $s is 'bool'" #define sem_warn_unusual_bool "$s: cast to 'bool' (other than integer 0 or 1)" #define sem_warn_fix_fail "floating to integral conversion overflow" #define sem_warn_index_ovfl "out-of-bound offset %ld in address" #define sem_warn_low_precision "lower precision in wider context: $s" #define sem_warn_odd_condition "use of $s in condition context" #define sem_warn_void_context "no side effect in void context: $s" #define sem_warn_olde_mismatch "argument and old-style parameter mismatch: $e" #define sem_warn_uncheckable_format \ "'format' arg. to printf/scanf etc. is variable, so cannot be checked" #define sem_warn_narrow_voidstar "implicit cast from (void *), C++ forbids" #define sem_warn_narrowing "implicit narrowing cast: $s" #define sem_warn_fn_cast \ "$s: cast between function pointer and non-function object" #define sem_warn_pointer_int "explicit cast of pointer to 'int'" #define bind_warn_unused_this_in_member "'this' unused in non-static member function" #define bind_warn_cpp_scope_differ "C++ scope may differ: $c" #define bind_warn_new_tag_in_formals "$c invented in parameter list" #define bind_err_cant_use_outer_member "attempt to use $p$r" #define bind_err_extern_clash "extern clash $r, $r (linker %ld char)" #define bind_err_extern_clash_monocase "extern clash $r, $r (linker %ld char monocase)" #define bind_err_duplicate_tag "duplicate definition of $s tag $b" #define bind_err_reuse_tag "re-using $s tag $b as $s tag" #define bind_err_incomplete_tentative \ "incomplete tentative declaration of $r" #define bind_err_type_disagreement "type disagreement for $r" #define bind_err_duplicate_definition "duplicate definition of $r" #define bind_err_duplicate_label "duplicate definition of label $r - ignored" #define bind_err_unset_label "label $r has not been set" #define bind_err_undefined_static \ "static function $b not defined - treated as extern" #define bind_err_conflicting_globalreg \ "conflicting global register declarations for $b" #define xbind_err_template_specialize_after "attempt to specialize after use" #define xbind_err_template_undef "attempt to instantiate undefined template $b" #define xbind_err_template_none "no template found to specialize or instantiate" #define xbind_err_template_ambiguous "ambiguous templates to specialize or instantiate" #define bind_err_template_tpara_redeclared "re-declaration of template type paramenter $r" #define fp_err_very_big "Overlarge floating point value found" #define fp_err_big_single \ "Overlarge (single precision) floating point value found" #define sem_err_typeclash "Illegal types for operands: $s" #define sem_err_sizeof_struct "size of $c needed but not yet defined" #define sem_rerr_sizeof_opaque "size of opaque $c needed" #define sem_err_lvalue "Illegal in lvalue: function or array $e" #define sem_err_bitfield_address "bit fields do not have addresses" #define sem_err_lvalue1 "Illegal in l-value: 'enum' constant $b" #define sem_err_lvalue2 "Illegal in the context of an l-value: $s" #define sem_err_nonconst "illegal in %s: <unknown>" #define sem_err_nonconst1 "illegal in %s: non constant $b" #define sem_err_nonconst2 "illegal in %s: $s" #define bind_msg_const_nonconst "illegal in constant expression: <unknown>" #define bind_msg_const_nonconst1 \ "illegal in constant expression: non constant $b" #define bind_msg_const_nonconst2 "illegal in constant expression: $s" #define moan_floating_type_nonconst \ "illegal in floating type initialiser: <unknown>" #define moan_floating_type_nonconst1 \ "illegal in floating type initialiser: non constant $b" #define moan_floating_type_nonconst2 \ "illegal in floating type initialiser: $s" #define moan_static_int_type_nonconst \ "illegal in static integral type initialiser: <unknown>" #define moan_static_int_type_nonconst1 \ "illegal in static integral type initialiser: non constant $b" #define moan_static_int_type_nonconst2 \ "illegal in static integral type initialiser: $s" #define sem_err_nonfunction "attempt to apply a non-function" #define sem_err_void_argument "'void' values may not be arguments" #define sem_err_bad_cast "$s: illegal cast of $t to pointer" #define sem_err_bad_cast1 "$s: illegal cast to $t" #define sem_err_bad_cast2 "$s: cast to non-equal $t illegal" #define sem_err_undef_struct \ "$c not yet defined - cannot be selected from" #define sem_err_unknown_field "$c has no $r field" #define sem_err_no_this_pntr "no 'this' pointer to access member" #define sem_err_no_this_pntr2 "no 'this' pointer for member function $e" #define sem_err_dupl_default_value \ "duplicate declaration of default value for argument #%d: $r" #define sem_err_missing_default_value "missing default value for argment #%d: $r" #define sem_err_noncallsite_function "non-call site '.*' or '->*' yielding function" #define sem_err_illegal_loperand "illegal left operand to $s" #define sem_err_addr_globalvar "$b is a global register variable - can't take its address" #define sem_err_ctor_confused "construction of value of type $t is recursively confused" #define sem_err_no_ctor_at_type "no constructor for $c at this type signature" #define sem_err_template_nontype_storage "template non-type $b has no storage" #define syn_err_template_member "template member expected" #define syn_rerr_temp_para_redefinition "template parameter $b re-defined" #define simplify_err_outsizearray "array $b too large" #define simplify_err_illegal_use_of_mem_fn "illegal use of member function - '&$#b' intended?" /* This has been removed - MJW * #define errs_membobj(_m)\ * %Z (_m ? "member":"object") * %O */ #define bind_rerr_undefined_tag "$s tag $b not defined" #define bind_rerr_mem_opaque "can't access data member $b of opaque type" #define bind_rerr_linkage_disagreement \ "linkage disagreement for $r - treated as $g" #define bind_rerr_linkage_disagreement_2 \ "$b has no linkage, but $b requires it to have" #define bind_rerr_linkage_disagreement_3 \ "linkage disagreement between $b and $b" #define bind_rerr_linkage_previously_c \ "$b was previously declared without \"C\" linkage" #define bind_rerr_duplicate_typedef "duplicate typedef $r" #define bind_rerr_local_extern "extern $r mismatches top-level declaration" #define xbind_warn_implicit_virtual "$p$r inherits implicit virtual" #define xbind_rerr_inherited_type_differs "inherited virtual function type differs: $b" #define xbind_rerr_ovld_non_fn "attempt to overload non-function $b" #define xbind_rerr_is_ambiguous_name "$r is an ambiguous name in $c" #define xbind_rerr_dl_cant_be_overloaded "'operator delete' can't be overloaded" #define xbind_rerr_bad_dl_type \ "'operator delete' must be of type 'void (void*)' or 'void (void*, size_t)'" #define xbind_rerr_bad_global_dl_type \ "'::operator delete' must be of type 'void (void*)'" #define xbind_rerr_bad_nw_type \ "'operator new' must have a return type of 'void*' and have a first argument of type 'size_t'" #define xbind_rerr_more_than_one_C_linkage "more than one $r has \"C\" linkage" #define xbind_rerr_both_virtual_and_nonvirtual \ "$r inherits both virtual and non-virtual attributes from bases of $c" #define cg_rerr_iffy_arithmetics "iffy arithmetic shift" #define fp_rerr_very_small "small floating point value converted to 0.0" #define fp_rerr_small_single \ "small (single precision) floating value converted to 0.0" #define sem_rerr_sizeof_bitfield \ "sizeof <bit field> illegal - sizeof(int) assumed" #define sem_rerr_sizeof_void "size of 'void' required - treated as 1" #define sem_rerr_sizeof_array "size of a [] array required, treated as [1]" #define sem_rerr_sizeof_function \ "size of function required - treated as size of pointer" #define sem_rerr_pointer_arith \ "<int> $s <pointer> treated as <int> $s (int)<pointer>" #define sem_rerr_pointer_arith1 \ "<pointer> $s <int> treated as (int)<pointer> $s <int>" #define sem_rerr_assign_const "assignment to 'const' object $e" #define sem_rerr_addr_regvar \ "'register' attribute for $b ignored when address taken" #define sem_rerr_lcast "objects that have been cast are not l-values" #define sem_rerr_pointer_compare \ "comparison $s of pointer and int:\n\ literal 0 (for == and !=) is only legal case" #define sem_rerr_different_pointers "differing pointer types: $s" #define sem_rerr_wrong_no_args "wrong number of parameters to $e" #define sem_rerr_casttoenum "$s: cast of $m to differing enum" /* warn in C */ #define sem_rerr_valcasttoref "$s: non-lvalue cast to non-const reference" #define sem_rerr_implicit_cast1 \ "$s: implicit cast of pointer to non-equal pointer" #define sem_rerr_implicit_cast2 "$s: implicit cast of non-0 int to pointer" #define sem_rerr_implicit_cast3 "$s: implicit cast of pointer to 'int'" #define sem_rerr_implicit_cast4 "$s: implicit cast of $t to 'int'" #define sem_rerr_nonpublic "$p$r is a non-public member" #define sem_rerr_cant_balance "differing pointer types: $s" #define sem_rerr_void_indirection "illegal indirection on (void *): '*'" #define sem_rerr_noncallsite_ovld "non-call site overload (using $b for $e)" #define sem_rerr_cast_dtype_from_vbase "cast to derived type from virtual base" #define sem_rerr_abclass_need_vtable "confusion: abstract? $c needs vtable" #define sem_rerr_too_many_args "too many arguments: $t constructor" #define obj_fatalerr_io_object "I/O error on object stream" #define compiler_rerr_no_extern_decl\ "no external declaration in translation unit" #define compiler_fatalerr_io_error "I/O error writing '%s'" #define compiler_fatalerr_load_version \ "load file created with a different version of the compiler" #define driver_fatalerr_io_object "I/O error on object stream" #define driver_fatalerr_io_asm "I/O error on assembler output stream" #define driver_fatalerr_io_listing "I/O error on listing stream" #ifdef TARGET_HAS_AOUT #define aout_fatalerr_toomany "Too many symbols for 'a.out' output" #define aout_fatalerr_toobig "Module too big for a.out formatter" #endif #ifdef TARGET_HAS_COFF #define coff_fatalerr_toomany "Too many relocations for COFF format in .o file" #define coff_fatalerr_toobig "Module too big for COFF formatter" #endif #define misc_fatalerr_space1 "out of store (for error buffer)" #define misc_fatalerr_toomanyerrs "Too many errors" #define misc_fatalerr_space2 "out of store (in cc_alloc)\n\ (Compilation of the debugging tables requested with the -g option\n\ requires a great deal of memory. Recompiling without -g, with\n\ the more restricted -gf option, or with the program broken into\n\ smaller pieces, may help.)" #define misc_fatalerr_space3 "out of store (in cc_alloc)" /* Beware: none of the following driver_message #defined are used! */ #define driver_message_nolisting \ "Unable to open %s for listing: -l option ignored\n" #ifdef NO_ASSEMBLER_OUTPUT #define driver_message_noasm \ "This version of the compiler does not support -s\n" #endif #define driver_message_writefail "Couldn't write file '%s'\n" #define driver_message_oddoption "Unrecognized option '%c': ignored\n" #define driver_message_readfail "Couldn't read file '%s'\n" /* NB the next error can not arise with the current ARM driver */ #define driver_message_toomanyfiles "Too many file args" #define driver_message_asmstdout "Assembly code will go to stdout\n" #define driver_message_no_listing \ "-m option useless without source listing. Ignored\n" #define driver_message_nomap "-m file not available or corrupt - ignored\n" #define driver_message_notest \ "This version of the compiler does not support the -test option\n" #define driver_message_needfile "At least one file argument wanted\n" #ifndef COMPILING_ON_ARM_OS #define driver_message_spool "output to clog1.log & clog2.log\n" #endif #define driver_message_testfile "No files allowed with -test\n" %Z #define driver_abort_msg "Compilation aborted: %s\n" #define driver_couldnt_write "couldn't write file '%s'\n" #define driver_couldnt_read "couldn't read file '%s'\n" #define driver_too_many_file_args "too many file arguments" #define driver_couldnt_read_counts "couldn't read \"counts\" file" #define driver_malformed_counts "malformed \"counts\" file" #define driver_toolenv_writefail "Couldn't write installation configuration\n" #define driver_incompat_cfrontcpp_ansi "-ansi incompatible with -cfront or -cpp" #define driver_incompat_cfrontcpp_pcc "-pcc incompatible with -cfront or -cpp" #define driver_incompat_pccansi_cfront "-cfront incompatible with -pcc or -ansi" #define driver_incompat_pccansi_cpp "-cpp incompatible with -pcc or -ansi" #define driver_ignored_arthur_unix "Warning: -arthur/-super ignored under unix\n" #ifdef WANT_WHINGY_MSGS_EVEN_WHEN_WRONG #define driver_ignored_linkerflags \ "Warning: linker flag(s) ignored with -c -E -M or -S\n" #endif #define driver_conflict_EM "Warning: options -E and -M conflict: -E assumed\n" #ifdef FORTRAN #define driver_conflict_strict_onetrip \ "Warning: -onetrip and -strict conflict: -strict assumed\n" #define driver_conflict_strict_f66 \ "Warning: -f66 and -strict conflict: -strict assumed\n" #define driver_conflict_strict_extend \ "Warning: -extend and -strict conflict: -strict assumed\n" #define driver_implies_f66_onetrip "Warning: -f66 implies -onetrip\n" #endif #define driver_ignored_filename_overlong "Overlong filename ignored: %s\n" #define driver_unknown_filetype "Error: type of '%s' unknown (file ignored)\n" #define driver_option_bad "Error: bad option '%s': ignored\n" #ifdef FORTRAN #define driver_option_nimp "Error: unimplemented option '%s': ignored\n" #endif #define driver_via_not_opened "Can't open -via file %s\n" /* Printed as "Error: bad option '<opt> <opt> <opt> ...': ignored\n" */ #define driver_option_bad1 "Error: bad option " #define driver_option_bad2 ": ignored\n" #define driver_option_missing_filearg "Missing file argument for %s\n" #define driver_option_missing_lastarg "No argument to last compiler option" #define driver_option_missing_arg "No argument to compiler option %s\n" #define driver_cant_open_output "Can't open %s for output\n" #define driver_cpp_toomanyfileargs "More than 2 file arguments to cpp ignored\n" #define driver_cpp_cantopenoutput "Can't open output file %s\n" #define driver_stdin_otherfiles "stdin ('-') combined with other files -- ignored\n" #define driver_noeffect "Warning: %s command with no effect\n" /* Needs fixing for NLS */ #define driver_banner "%s\n", CC_BANNER #define driver_prerelease "%s\n", DRIVER_PRE_RELEASE_MSG /* messages that form part of the varied help texts produced by cc -help */ #define driver_expire "\ This time-limited software remains the property of %s.\n\ It will expire at (GMT) %s\n" #define help_blank "\n" #define help_bsd_f77 "\n\nBSD compatible ANSI F77 compiler.\n" #define help_usage "\n\ Usage: %s [options] file1 file2 ... filen\n" #define help_main_options "Main options:\n" #define help_list "\ -list Generate a compilation listing\n" #define help_iso "\ -iso Compile strictly according to ISO (BS 6192 : 1982)\n" #define help_ansi "\ -ansi Compile ANSI-style C source code\n" #define help_strict "\ -strict Accept only programs strictly conforming to ANSI standard\n" #define help_pcc "\ -pcc Compile UNIX PCC style C source code\n" #define help_pcc_bsd "\ -pcc Compile BSD UNIX PCC-style C source code\n" #define help_f66 "\ -f66 Follow F66 practices or rules when conflicting with F77\n" #define help_arthur "\ -arthur Add 'arthur' to the list of libraries to be linked with\n\ (Arthur only)\n" #define help_brazil "\ -super Add 'supervisor' to the list of libraries to be linked with\n\ (Brazil only)\n" #define help_dont_link "\ -c Do not link the files being compiled\n" #define help_dont_link_invoke "\ -c Do not invoke the linker to link the files being compiled\n" #define help_leave_comments "\ -C Prevent the preprocessor from removing comments (Use with -E)\n" #define help_predefine "\ -D<symbol> Define <symbol> on entry to the compiler\n" #define help_predefine_pp "\ -D<symbol> Define preprocessor <symbol> on entry to the compiler\n" #define help_preprocess_pascal "\ -E Preprocess the Pascal source code only\n" #define help_preprocess_c "\ -E Preprocess the C source code only\n" #define help_preprocess_fortran "\ -E Preprocess the F77 source code only\n" #define help_compiler_features "\ -F<options> Enable a selection of compiler defined features\n" #define help_runtime_checks "\ -R<options> Disable selected run time error checks\n" #define help_debug "\ -g<options> Generate code that may be used with the debugger\n" #define help_debug_noopt "\ -g Generate code that may be used with the debugger\n" #define help_include_I "\ -I<directory> Include <directory> on the #include search path\n" #define help_16bit_ints "\ -i2 Make the default integer size 16 bits\n" #define help_include_J "\ -J<directory> Replace the default #include path with <directory>\n" #define help_libraries "\ -L<libs> Specify a comma-joined list of libraries to be linked with\n\ instead of the standard library\n" #define help_makefile "\ -M<options> Generate a 'makefile' style list of dependencies\n" #define help_output "\ -o<file> Instruct the linker to call the object code produced <file>\n" #define help_output_space "\ -o <file> Instruct the linker to name the object code produced <file>\n" #define help_optimised "\ -O Invoke the object code improver\n" #define help_onetrip "\ -onetrip Compile DO loops that are performed at least once if reached\n" #define help_profile "\ -P<options> Generate code to generate 'profile' information\n" #define help_profile_lc "\ -p<options> Generate code to generate 'profile' information\n" #define help_readonly_strings "\ -R Place all compile time strings in a 'Read only' segment\n" #define help_readonly_strings_lc "\ -r Place all compile time strings in a 'Read only' segment\n" #define help_output_assembler "\ -S Output assembly code instead of object code\n" #define help_generate_assembler "\ -S Generate assembly code instead of object code\n" #define help_dont_downcase "\ -U Do not convert upper case letters to lower case\n" #define help_preundefine "\ -U<symbol> Undefine <symbol> on entry to the compiler\n" #define help_preundefine_pp "\ -U<symbol> Undefine preprocessor <symbol> on entry to the compiler\n" #define help_disable_warnings "\ -W<options> Disable all or selected warning and error messages\n" #define help_disable_warnings_lc "\ -w<options> Disable all or selected warning and error messages\n" #define help_helios_libraries "\ -Z<option> Special Helios options for shared library building etc\n" %O /* messages generated by misc.c */ #ifndef TARGET_IS_UNIX # ifndef COMPILING_ON_MPW #define misc_message_lineno(_f,_l,_s) "\"%s\", line %ld: %s",_f,_l,_s # else #define misc_message_lineno_mpw(_f,_l,_s) \ "File \"%s\"; Line %ld # %s",_f,_l,_s # endif #else #define misc_message_lineno_unix(_f,_l,_s) "%s: %ld: %s",_f,_l,_s #endif #ifndef TARGET_IS_UNIX # ifndef COMPILING_ON_MPW #define misc_message_nolineno(_f,_s) "\"%s\": %s",_f,_s # else #define misc_message_nolineno_mpw(_f,_s) \ "File \"%s\" # %s",_f,_s # endif #else #define misc_message_nolineno_unix(_f,_s) "%s: %s",_f,_s #endif #define misc_message_nofile(_s) "%s",_s #ifndef COMPILING_ON_MPW #define misc_message_sum1_zero "%s: 0 warnings" #define misc_message_sum1_sing "%s: 1 warning" #define misc_message_sum1(_f,nx) "%s: %ld warnings", _f, nx #else #define misc_message_sum1_zero_mpw "### \"%s\": 0 warnings" #define misc_message_sum1_sing_mpw "### \"%s\": 1 warning" #define misc_message_sum1_mpw(_f,nx) "### \"%s\": %ld warnings", _f, nx #endif #define misc_message_sum2 " (+ %ld suppressed)" #define misc_message_sum3_zero ", 0 errors" #define misc_message_sum3_sing ", 1 error" #define misc_message_sum3 ", %ld errors" #define misc_message_sum5_zero ", 0 serious errors\n" #define misc_message_sum5_sing ", 1 serious error\n" #define misc_message_sum5 ", %ld serious errors\n" #define misc_message_internal "Failure of internal consistency check" #define misc_msg_fnarg_this_fnap "<implicit 'this' argument to function call>" #define misc_msg_fnarg_this_fnname "<implicit 'this' argument to $b>" #define misc_msg_fnarg_fnap "<argument %d to function call>" #define misc_msg_fnarg_fnname "<argument %d to $b>" /* Cannot be issued if NARGREGS==0 */ #define warn_untrustable "untrustable code generated for $r" #endif /* ndef NLS */ /* Under NLS the following are still not tags */ %S /* The next batch of things just get mapped onto syserr codes */ #define syserr_removepostincs "unexpected op in RemovePostIncs" #define syserr_mkqualifiedtype "mkqualifiedtype(..., %ld)" #define syserr_unbitfield "unbitfield_type $t" #define syserr_bf_promote "bf_promoted_type $t" #define syserr_typeof "typeof(%ld)" #define syserr_alignoftype "alignoftype(%ld,%#lx)" #define syserr_sizeoftype "sizeoftype(%ld,%#lx)" #define syserr_codeoftype "codeoftype" #define syserr_equivtype "equivtype(%ld)" #define syserr_compositetype "compositetype(%ld)" #define syserr_trydiadicreduce "trydiadreduce(unsigned op %ld)" #define syserr_trydiadicreduce1 "trydiadreduce(signed op %ld)" #define syserr_trydiadicreduce2 "trydiadreduce(float op %ld)" #define syserr_fp_op "FP op %ld unknown" #define syserr_trymonadicreduce "trymonadreduce(int op %ld)" #define syserr_trymonadicreduce1 "trymonadreduce(float op %ld)" #define syserr_bf_container "bf_container" #define syserr_coerceunary1 "coerceunary(%ld,%#lx)" #define syserr_bitfieldassign "bitfieldassign" #define syserr_mkindex "sem(mkindex)" #define syserr_ptrdiff "sem(mkbinary/ptrdiff)" #define syserr_va_arg_fn "sem(odd va_arg fn)" #define syserr_mkcast "mkcast(%ld,%#lx)" #define syserr_mkcast1 "mkcast(%ld)" #define syserr_te_plain "te_plain(%ld)" #define syserr_clone_node "clone_node(%ld)" #define syserr_optimise "optimise &(%ld)" #define syserr_optimise1 "optimise(%ld)" #define syserr_mcrepofexpr "mcrepofexpr(%ld,%#lx)" #define syserr_mcreparray "mcrep(array %ld)" #define syserr_newdbuf "pp_newdbuf(%ld,%ld)" #define syserr_pp_recursion "pp recursive sleep: '%s'" #define syserr_pp_special "pp_special(%ld)" #define syserr_overlarge_store1 "Overlarge storage request (binder %ld)" #define syserr_overlarge_store2 "Overlarge storage request (local %ld)" #define syserr_discard2 "discard2 %p" #define syserr_discard3 "discard3 %p" #define syserr_alloc_unmark "alloc_unmark - called too often" #define syserr_alloc_unmark1 "alloc_unmark(no drop_local_store())" #define syserr_alloc_reinit "alloc_reinit(no drop_local_store())" #define syserr_addclash "add_clash (0x%lx, 0x%lx)" #define syserr_forget_slave "forget_slave(%ld, %ld) %ld" #define syserr_GAP "GAP in reference_register" #define syserr_corrupt_register "corrupt_register %ld %p" #define syserr_regalloc "regalloc(corrupt/alloc)" #define syserr_regalloc_typefnaux "regalloc(typefnaux)" #define syserr_regalloc_POP "regalloc(POP)" #define syserr_call2 "CALL2 %ld" #define syserr_regno "reg %lx" #define syserr_vregsort "vregsort(%lx)" #define syserr_liveness "liveness odd" #define syserr_dataflow "dataflow &-var" #define syserr_choose_real_reg "choose_real_reg %lx" #define syserr_fail_to_spill "Failed to spill register for %ld" #define syserr_regalloc_reinit2 "regalloc_reinit2" #define syserr_regheap "Register heap overflow" #define syserr_bad_fmt_dir "bad fmt directive" #define syserr_syserr "syserr simulated" #define syserr_r1r "r1r %ld" #define syserr_r2r "r2r %ld" #define syserr_r3r "r3r %ld" #define syserr_r4r "r4r %ld" #define syserr_expand_jop "expand_jop(2address)" #define syserr_nonauto_active "Non auto 'active_binders' element" #define syserr_size_of_binder "size_of_binder" #define syserr_insertblockbetween "insertblockbetween(%ld, %ld)" #define syserr_reopen_block "reopen_block called" #define syserr_scaled_address "emit5(scaled address)" #define syserr_expand_pushr "expand_jop_macro(PUSHR)" #define syserr_remove_noop_failed "remove_noop failed" #define syserr_remove_noop_failed2 "remove_noop failed2" #define syserr_bad_bindaddr "Bad bindaddr_() with LDRVx1" #define syserr_ldrfk "duff LD/STRF/DK 0x%lx" #define syserr_ldrk "duff LD/STRK 0x%lx" #define syserr_ldrbk "duff LD/STRBK 0x%lx" #define syserr_ldrwk "duff LD/STRWK 0x%lx" #define syserr_branch_backptr "Bad back-pointer code in branch_chain" #define syserr_no_main_exit "use_cond_field(no main exit)" #define syserr_two_returns "Two return exits from a block" #define syserr_unrefblock "unrefblock" #define syserr_zip_blocks "zip_blocks(SETSP confused %ld!=%ld)" #define syserr_live_empty_block "ALIVE empty block L%ld" #define syserr_loctype "loctype" #define syserr_adconbase "cse_adconbase" #define syserr_find_exprn "CSE: find_exprn %ld" #define syserr_removecomparison "CSE: removecomparison %lx" #define syserr_evalconst "CSE: evalconst %lx" #define syserr_scanblock "cse_scanblock %08lx" #define syserr_prune "csescan(prune)" #define syserr_globalize "globalize_declaree1(%p,%ld)" #define syserr_globalize1 "globalize_typeexpr(%p,%ld)" #define syserr_copy_typeexpr "copy_typeexpr(%p,%ld)" #define syserr_tentative "is_tentative(tmpdataq == NULL)" #define syserr_tentative1 "is_tentative(ADCON)" #define syserr_tentative2 "tentative definition confusion" #define syserr_instate_decl "instate_decl %ld" #define syserr_totarget "totargetsex(%d)" #define syserr_vg_wpos "vg_wpos(%ld)" #define syserr_vg_wflush "vg_wflush(type=0x%x)" #define syserr_gendcI "gendcI(%ld,%ld)" #define syserr_vg_wtype "vg_wtype=0x%x" #define syserr_codevec "code vector overflow" #define syserr_nonstring_lit "non-string literal: %.8lx" #define syserr_addr_lit "Address-literals should not arise in HELIOS mode" #define syserr_dumplits "dumplits(codep&3)" #define syserr_dumplits1 "codebuf(dumplits1)" #define syserr_dumplits2 "codebuf(dumplits2)" #define syserr_outlitword "outlitword confused" #define syserr_dumplits3 "codebuf(dumplits3)" #define syserr_addlocalcse "addlocalcse %ld" #define syserr_cse_lost_def "cse: def missing" #define syserr_cse_lost_use "cse: use missing" #define syserr_cse_safetolift "cse: safetolift" #define syserr_storecse "storecse %ld %ld\n" #define syserr_baseop "cse: baseop %lx" #define syserr_cse_wordn "CSE_WORDn" #define syserr_addcsedefs "addcsedefs" #define syserr_cse_preheader "cse: loop preheader %d != %ld" #define syserr_cse_modifycode "cse: modifycode %ld %ld!=%ld" #define syserr_cse_modifycode_2 "cse: compare ref L%ld not reachable from def L%ld" #define syserr_cse_makesubdef "cse: MakeSubDef" #define syserr_referencecsedefs "ReferenceCSEDefs" #define cse_rewritenext "cse: RewriteNext %ld: %ld" #define syserr_regtype "ensure_regtype(%lx)" #define syserr_struct_val "Value of structure requested improperly" #define syserr_missing_expr "missing expr" #define syserr_checknot "s_checknot" #define syserr_structassign_val "value of structure assignment needed" #define syserr_floating "Float %%" #define syserr_cg_expr "cg_expr(%ld = $s)" #define syserr_bad_reg "bad reg %lx in use" #define syserr_bad_fp_reg "fp reg in use" #define syserr_cg_fnarg "cg_fnarg(odd rep %lx)" #define syserr_fnarg_struct "cg(struct arg confused)" #define syserr_fnret_struct "struct returning s_fnap" #define syserr_cg_fnarg1 "cg_fnargs confused" #define syserr_cg_argcount "arg count confused" #define syserr_cg_fnarg2 "cg_fnargs tidy" #define syserr_padbinder "odd padbinder $b in cg_fnargs()" #define syserr_null_nb "nb==NULL in cg.c (A)" #define syserr_cg_fnap "cg_fnap" #define syserr_cg_fnap_1 "cg_fnap_1(typefnaux-mismatch)" #define syserr_cg_return_struct "cg_return(struct)" #define syserr_cg_cmd "cg_cmd(%ld = $s)" #define syserr_cg_endcase "cg_cmd(endcase)" #define syserr_cg_break "cg_cmd(break)" #define syserr_cg_cont "cg_cmd(cont)" #define syserr_cg_switch "switch expression must have integer type" #define syserr_cg_caselist "cg_caselist" #define syserr_cg_case "cg_cmd(case)" #define syserr_unset_case "Unset case_lab" #define syserr_cg_default "cg_cmd(default)" #define syserr_cg_badrep "rep bad in comparison %.8lx" #define syserr_cg_plain "(plain) qualifies non-<narrow-int-binder>" #define syserr_cg_cast "Illegal cast involving a structure or union" #define syserr_cg_fpsize "fp sizes are wrong %ld %ld" #define syserr_cg_cast1 "bad mode %ld in cast expression" #define syserr_cg_cast2 "cast %ld %ld %ld %ld" #define syserr_cg_indexword "Indexed address mode with word-store" #define syserr_cg_bad_width "bad width %ld in cg_stind" #define syserr_cg_bad_mode "bad mcmode %ld in cg_stind" #define syserr_chroma "chroma_check(target.h setup wrong or multi-temp op confused)" #define syserr_Q_swap "Q_swap(%lx)" #define syserr_cg_stgclass "Funny storage class %#lx" #define syserr_cg_storein "cg_storein(%ld)" #define syserr_cg_addr "p nasty in '&(p=q)'" #define syserr_cg_addr1 "cg_addr(%ld)" #define syserr_cg_shift0 "n=0 in shift_op1" #define syserr_not_shift "not a shift in shift_operand()" #define syserr_not_shift1 "not a shift in shift_amount()" #define syserr_integer_expected "integer expression expected" #define syserr_nonauto_arg "Non-auto arg!" #define syserr_struct_result "Unexpected struct result" #define syserr_cg_topdecl "cg_topdecl(not fn type)" #define syserr_cg_unknown "unknown top level %ld" #define syserr_cg_narrowformal "unwidened formal" #define syserr_emitfloat1 "Bad FP op with emitfloat1" #define syserr_regalloc_clash "Register allocation clash (R%d)" #ifdef TARGET_HAS_AOUT #define syserr_aout_reloc "relocate_code_to_data(PCreloc)" #define syserr_aout_checksym "obj_checksym(%s)" #define syserr_aout_reloc1 "obj_coderelocation %.8lx" #define syserr_aout_gendata "obj_gendata(%ld)" #define syserr_aout_datalen "obj_data len=%ld" #define syserr_aout_data "obj_data %ldEL%ld'%s'" #define syserr_aout_debug "writedebug: aoutobj linked with xxxdbg not dbx" # ifdef TARGET_HAS_DEBUGGER /* dbx support */ #define syserr_too_many_types "too many types in dbx" #define syserr_addcodep "bad pointer in dbg_addcodep" #define syserr_tagbindsort "bad tagbindsort 0x%08lx" #define syserr_sprinttype "sprinttype(%p,0x%lx)" #define syserr_dbx_locvar "debugger table confusion(local variable $r %lx %lx)" #define syserr_dbx_scope "dbg_scope" #define syserr_dbx_proc "dbg_proc" #define syserr_dbx_proc1 "dbg_proc confused" #define syserr_dbx_write "dbg_write(%lx)" # endif #endif #ifdef TARGET_HAS_COFF #define syserr_coff_reloc "relocate_code_to_data(PCreloc)" #define syserr_coff_pcrel "coff(unexpected X_PCreloc)" #define syserr_coff_m88000 "coffobj(X_DataAddr needs extending)" #define syserr_coff_toobig "coffobj(Module over 64K -- fix)" #define syserr_coff_checksym "obj_checksym($r)" #define syserr_coff_reloc1 "obj_coderelocation(%.8lx)" #define syserr_coff_gendata "obj_gendata(%ld)" #define syserr_coff_datalen "obj_data len=%ld" #define syserr_coff_data "obj_data %ldEL%ld'%s'" # ifdef TARGET_HAS_DEBUGGER /* dbx support */ #define syserr_too_many_types "too many types in dbx" #define syserr_addcodep "bad pointer in dbg_addcodep" #define syserr_tagbindsort "bad tagbindsort 0x%08lx" #define syserr_sprinttype "sprinttype(%p,0x%lx)" #define syserr_dbx_locvar "debugger table confusion(local variable $r %lx %lx)" #define syserr_dbx_scope "dbg_scope" #define syserr_dbx_proc "dbg_proc" #define syserr_dbx_proc1 "dbg_proc confused" #define syserr_dbx_write "dbg_write(%lx)" # endif #endif #ifndef NLS /* These become tags */ %Z /* The following remain as ordinary (uncompressed) strings */ /* * @@@ Wording here is subject to change... */ #define misc_message_warning "Warning: " #define misc_message_error "Error: " #define misc_message_serious "Serious error: " #define misc_message_fatal "Fatal error: " #define misc_message_abandoned "\nCompilation abandoned.\n" /* * The following are used in init_sym_name_table() and/or ctxtofdeclflag() * and eventually find their ways into various error messages. */ /* _aftercommand has been added where needed in feerrs.h * #define errname_aftercommand " after command" */ #define errname_unset "<?>" #define errname_pointertypes "<after * in declarator>" #define errname_toplevel "<top level>" #define errname_structelement "<structure component>" #define errname_formalarg "<formal parameter>" #define errname_formaltype "<formal parameter type declaration>" #define errname_blockhead "<head of block>" #define errname_typename "<type-name>" #define errname_unknown "<unknown context>" #define errname_error "<previous error>" #define errname_invisible "<invisible>" #define errname_let "<let>" #define errname_character "<character constant>" #define errname_wcharacter "<wide character constant>" #define errname_integer "<integer constant>" #define errname_int64con "<int64 constant>" #define errname_boolean "<boolean constant>" #define errname_floatcon "<floating constant>" #define errname_string "<string constant>" #define errname_wstring "<wide string constant>" #define errname_identifier "<identifier>" #define errname_binder "<variable>" #define errname_tagbind "<struct/union tag>" #define errname_simpletype "<simple type>" #define errname_conversiontype "<conversion type>" #define errname_new_type_name "<new-type-name>" #define errname_catch_name "<catch name>" #define errname_cond "_?_:_" #define errname_displace "++ or --" #define errname_postinc "++" #define errname_postdec "--" #define errname_arrow "->" #define errname_dotstar ".*" #define errname_arrowstar "->*" #define errname_constructor "<constructor>" #define errname_destructor "<destructor>" #define errname_addrof "unary &" #define errname_content "unary *" #define errname_monplus "unary +" #define errname_neg "unary -" #define errname_fnap "<function argument>" #define errname_fnarg "<function argument %d>" #define errname_subscript "<subscript>" #define errname_cast "<cast>" #define errname_sizeoftype "sizeof" #define errname_sizeofexpr "sizeof" #define errname_ptrdiff "-" /* for (a-b)=c msg */ #define errname_endcase "break" #define errname_block "<block>" #define errname_decl "decl" #define errname_fndef "fndef" #define errname_typespec "typespec" #define errname_typedefname "typedefname" #define errname_valof "valof" #define errname_ellipsis "..." #define errname_init "=" #define errname_eol "\\n" #define errname_eof "<eof>" #define errname_longdouble "long double" /* there is no s_longdouble */ #define errname_membertemplate "<member template>" #define errname_classtemplate "<class template>" #ifdef RANGECHECK_SUPPORTED # define errname_rangecheck "<rangecheck>" # define errname_checknot "<checknot>" #endif #endif /* ndef NLS */ /* end of miperrs.h */
stardot/ncc
armthumb/arminst.h
/* * armthumb/arminst.h * Copyright (C) Codemist Ltd., 1987-1993 * Copyright (C) Advanced RISC Machines Limited., 1990-1997 * SPDX-Licence-Identifier: Apache-2.0 * * Functions to generate sequences of ARM instructions required by * both ARM and Thumb backends */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include "cgdefs.h" int32 Arm_EightBits(int32 n); int32 Arm_SplitForAdd(RealRegister r, int32 n, int32 *opp); #define V_Exact 0x001 #define V_Negated 0x002 #define V_Inverted 0x004 #define V_Orred 0x008 #define V_KAdded 0x010 #define V_RegPair 0x020 #define V_ASR 0x040 #define V_LSR 0x080 #define V_LSL 0x100 #define V_ROR 0x200 #define V_AnyShift (V_ASR|V_LSR|V_LSL|V_ROR) typedef union { int32 shift; /* The decription of a constant shift, suitable */ /* for orring into an ARM instruction */ struct { int32 op; /* J_ADDK or J_SUBK */ int32 k; /* a representation of the constant, suitable for */ /* orring into an ARM instruction */ } add; struct { int32 op; int32 rm; } rpair; } ValueDescOp3; typedef struct { RealRegister r; ValueDescOp3 op3; } ValueDesc; typedef int RegisterContaining(uint32 n, int flags, ValueDesc *vp); int32 *arm_add_integer( RealRegister r1, RealRegister r2, int32 n, int32 scc, RegisterContaining *cachelookup, int32 *v); /* Generates instructions into the buffer v to add the constant n */ /* to the contents of r2, placing the result in r1. The condition */ /* field of the generated instructions is 0; scc is orred into the */ /* last instruction generated (expected to be the S bit or 0). The */ /* return value is a pointer to the next free word in v. */ /* If cachelookup is non-null, it is used to determine whether the */ /* addition can be performed via a RR-instruction with a register */ /* whose value is known */ /* end of armthumb/arminst.h */
stardot/ncc
cppfe/xsyn.c
<gh_stars>0 /* * xsyn.c: syntax analysis phase of C++ compiler. * Copyright (C) Codemist Ltd., 1988-1993 * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Advanced RISC Machines Limited, 1992, 1994 * SPDX-Licence-Identifier: Apache-2.0 * All rights reserved. */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <string.h> /* for memset */ #include "globals.h" #include "syn.h" #include "pp.h" /* for pp_inhashif */ #include "lex.h" #include "simplify.h" #include "bind.h" #include "sem.h" #include "aetree.h" #include "builtin.h" #include "vargen.h" #include "mcdep.h" /* for dbg_xxx */ #include "store.h" #include "errors.h" #include "aeops.h" #include "codebuf.h" #include "compiler.h" /* UpdateProgress */ #include "cg.h" /* for cg_topdecl - @@@ BREAKS the dependency structure */ #ifdef CALLABLE_COMPILER #include "dbg_hdr.h" #include "dbg_hl.h" /* for dbg_mk_formatpack() */ #endif #define _SYN_H /* It seems better to forbid "int a{2};" etc in C++. c */ #define archaic_init(s) 0 static Expr *cpp_mkunaryorop(AEop, Expr *); static Expr *cpp_mkfnaporop(Expr *, ExprList *); static void gen_reftemps(void); static Cmd *cmd_rescope(SynScope *to, SynScope *from, Cmd *c); static void syn_setlab(LabBind *, SynScope *); static Cmd *syn_reflab(LabBind *lab, SynScope *s, Cmd *c); /* <NAME> - Make it compile by losing the static */ #ifdef CALLABLE_COMPILER SynBindList *reverse_SynBindList(SynBindList *x); #else static SynBindList *reverse_SynBindList(SynBindList *x); #endif static void rd_cpp_name(TagBinder *leftScope); static void rd_template_postfix(ScopeSaver tformals, bool name_only); static void rd_exception_spec(void); static void rd_dtor(TagBinder *scope); static Expr *rd_cpp_prefixextra(AEop op); static void memfn_typefix(DeclRhsList *, TagBinder *); static DeclRhsList *DeclRhs_of_FormType(FormTypeList *x); static DeclRhsList *reinvent_fn_DeclRhsList(Symstr *name, Symstr *realname, TypeExpr *t,SET_BITMAP s); static void cpp_end_strdecl(TagBinder *cl); static void syn_pop_linkage(void); static ExprList *rd_template_actuals(bool check); static ScopeSaver rd_template_formals(void); static Cmd *rd_meminit(TagBinder *ctorcl, Binder *ctor, SynBindList *args, Cmd **pre, Cmd **post); static Expr *syn_memdtor(TagBinder *dtorclass, Binder *dtor, SynBindList *formals, Cmd **pre); static bool ispurefnconst(Expr *e); static void instate_anonu_members(int declflag, Binder *b); static void use_classname_typedef(TypeExpr *t); static Binder *ovld_match_def(Binder *b, TypeExpr *t, BindList *l, bool prefer_tmpt, SET_BITMAP declflag); static TypeExpr *fixup_special_member(Symstr *, TypeExpr *, TypeExpr *, TagBinder *, SET_BITMAP stg); static Binder *instate_classname_typedef(TagBinder *tb, int declflag); static Handler *rd_handler(void); static Cmd *rd_compound_statement(AEop op); static Expr *rd_declrhs_exec_cpp(DeclRhsList *d, int* initflag); static Cmd *syn_embed_if(CmdList *cl); static Expr *rd_cppcast(void); static void rd_classdecl(TagBinder *tb); static void rd_access_adjuster(TagBinder *b, AEop access); static Cmd *conditionalised_delete(Binder *thisb, Binder *isdelb, TagBinder *parent); static int is_declaration(int n); static int is_type_id(void); static void xsyn_init(void); static void add_memfn_template(TagBinder *p, Symstr *name, Symstr *realname, TypeExpr *t, SET_BITMAP stg, TagBinder *scope, ScopeSaver formaltags, int tokhandle, ScopeSaver templateformals); static ScopeSaver applicable_template_formals(void); static ScopeSaver cur_tformals(void); static void syn_implicit_instantiate(TagBinder *primary, TagBinder *instance); static Binder *find_typename(Symstr *sv, TagBinder *scope); TagBindList *rootOfPath; /* <NAME> - Make it compile */ #ifdef CALLABLE_COMPILER #define CheckSWIValue(n) n #endif /* This next function should be handled by some form of attribute flag. */ /* Oh woe, even (d->declname == ctorsym) etc fails (name-munging). */ static bool cpp_special_member(DeclRhsList *d) { const char *s = symname_(d->declname); return LanguageIsCPlusPlus && /* these names aren't special in C mode */ (strncmp(s, "__ct", 4) == 0 || strncmp(s, "__dt", 4) == 0 || strncmp(s, "__op", 4) == 0); } static TagBinder DNAME = {s_tagbind}; static TagBinder TAS = {s_tagbind}; /* Template Actual Scope */ static SynScope *temps = 0; static int32 temps_scopeid = 0; #include "syn.c" #include "doe.c" int recursing; static void save_pendingfns(PendingFnList **saved_pendingfns) { *saved_pendingfns = syn_pendingfns; syn_pendingfns = NULL; } static void restore_pendingfns(PendingFnList *saved_pendingfns) { syn_pendingfns = saved_pendingfns; } static void save_curfn_misc(FuncMisc *tmp) { tmp->switchcmd = cur_switchcmd; tmp->loopscope = cur_loopscope; tmp->switchscope = cur_switchscope; tmp->kaerb = cur_break; tmp->resttype = cur_restype; tmp->switchtype = cur_switchtype; tmp->is_ctor = cur_fn_is_ctor; tmp->is_dtor = cur_fn_is_dtor; tmp->structresult = cur_structresult; tmp->curfndetails = currentfunction; tmp->recurse = recursing, recursing = 0; save_labels(&tmp->labels, tmp->labsyms); } static void restore_curfn_misc(FuncMisc *tmp) { cur_switchcmd = tmp->switchcmd; cur_loopscope = tmp->loopscope; cur_switchscope = tmp->switchscope; cur_break = tmp->kaerb; cur_restype = tmp->resttype; cur_switchtype = tmp->switchtype; cur_structresult = tmp->structresult; cur_fn_is_ctor = tmp->is_ctor; cur_fn_is_dtor = tmp->is_dtor; currentfunction = tmp->curfndetails; recursing = tmp->recurse; restore_labels(tmp->labels, tmp->labsyms); } /* AM, Sept 91: memo: too much effort is spent mapping between */ /* DeclRhsList and FormTypeLists, and Binders. @@@ Think. */ /* FormTypeList is now an initial sub-struct of DeclRhsList. */ static DeclRhsList *DeclRhs_of_FormType(FormTypeList *x) { DeclRhsList *p = 0, *q = 0, *t; /* This routine loses any s_register on args of member fn definitions */ /* which are specified in a class definition. Tough. */ for (; x; x = x->ftcdr) { TypeExpr *tt = x->fttype; t = mkDeclRhsList(x->ftname, tt, bitofstg_(s_auto)); declinit_(t) = x->ftdefault; if (p == 0) p = q = t; else q->declcdr = t, q = t; } return p; } static DeclRhsList *reinvent_fn_DeclRhsList(Symstr *name, Symstr *realname, TypeExpr *t, SET_BITMAP s) { DeclRhsList *p; TypeExpr *newt; if (h0_(t) != t_fnap) syserr("not a function type"); /* make a global shallow copy of 't' since we're going to reuse the */ /* typefnargs of it */ newt = g_mkTypeExprfn(t_fnap, typearg_(t), (SET_BITMAP)typespecbind_(t), (FormTypeList*)DeclRhs_of_FormType(typefnargs_(t)), &typefnaux_(t)); typedbginfo_(newt) = typedbginfo_(t); p = mkDeclRhsList(name, newt, s); p->declrealname = realname; fault_incomplete_formals(typefnargs1_(p->decltype), 1); return p; } static void rd_operator_name(void) { AEop op = curlex.sym; /*/* need to parse 'operator new[]' and 'operator delete[]' here */ if (op == s_lbracket || op == s_lpar) { AEop ket; if (op == s_lbracket) op = s_subscript, ket = s_rbracket; else op = s_fnap, ket = s_rpar; nextsym(); checkfor_ket(ket); ungetsym(); } curlex.a1.sv = operator_name(op); curlex.sym = s_pseudoid; } static void rd_operator_or_conversion_name(void) { if (curlex.sym == s_identifier) rd_cpp_name(0); if (isdeclstarter2_(curlex)) /* rd_declspec(stgclass) moans */ { TypeExpr *t = rd_typename(CONVERSIONTYPE); ungetsym(); curlex_optype = t; curlex.a1.sv = conversion_name(t); curlex.sym = s_pseudoid; } else rd_operator_name(); } /* Temporary routine to read and ignore C++ exception specifications. An * error should be raised if an exception specification is used in a typedef * (DWP 15.4.1) and there are restrictions on the allowed types. None of this * is yet checked for. */ static void rd_exception_spec(void) { if (curlex.sym != s_throw) return; nextsym(); checkfor_ket(s_lpar); if (curlex.sym != s_rpar) for(;;) { (void)rd_typename(TYPENAME); if (curlex.sym != s_comma) break; nextsym(); } checkfor_ket(s_rpar); } /* rd_dtor is now called only from rd_declarator() to read the decl of */ /* a dtor. The syntactic form is, therefore, very simple. More complex */ /* forms of ctors and dtors are now all handled by rd_cpp_name. */ static void rd_dtor(TagBinder *scope) { if (scope) { nextsym(); if (curlex.sym == s_identifier) rd_template_postfix(NULL, YES); if (curlex.sym != s_identifier || (curlex.a1.sv != bindsym_(scope) && (tagprimary_(scope) == NULL || bindsym_(tagprimary_(scope)) != curlex.a1.sv))) { cc_err(syn_err_illdtor); if (curlex.sym != s_identifier) ungetsym(); } else curlex.sym = s_pseudoid; curlex_optype = 0; curlex.a1.sv = dtorsym; return; } syserr("rd_dtor(0)"); /* should never happen now */ } void diagnose_access(Symstr *sv, TagBinder *scope) { accessOK |= 4; /* prevent multiple diagnoses of the same token */ if (suppress & D_ACCESS) cc_warn(sem_rerr_nonpublic, scope, sv); else cc_rerr(sem_rerr_nonpublic, scope, sv); } static ClassMember *last_type_seen; static void check_last_type_seen(void) { if (last_type_seen) { check_access_1(last_type_seen, curlex_scope); last_type_seen = 0; } } static void check_last_access(TagBinder *leftScope) { TagBinder *scope; if (accessOK) /* allowable or more serious error */ return; if (no_access_context()) { last_type_seen = (curlex_typename && bindparent_(curlex_typename) && !(attributes_(curlex_typename) & bitofaccess_(s_public))) ? (ClassMember *)curlex_typename : 0; return; } scope = (curlex.sym & s_qualified) ? curlex_scope : (leftScope != 0) ? leftScope : (curlex_member != 0) ? bindparent_(curlex_member) : 0; if (scope == 0) return; diagnose_access(curlex.a1.sv, scope); } static TagBinder *findscope(Symstr *sv, TagBinder *scope, int flags, bool is_dname) { /* I'd like to use 'findtagbinder' but it won't do FB_INHERIT */ Binder *b = findbinding(sv, scope, flags|FB_CLASSNAME); if (b != NULL) { if (scope != 0 && accessOK == 0 && !is_dname) diagnose_access(curlex.a1.sv, scope); /* Check to see if it is a typedef to a tagbinder */ if (bindstg_(b) & bitofstg_(s_typedef)) { TypeExpr *tbt = princtype(bindtype_(b)); if (isclasstype_(tbt)) return typespectagbind_(tbt); } } return (b != NULL && h0_(b) == s_tagbind) ? (TagBinder *)b : NULL; } static TagBinder *globalize_tagbinder(TagBinder *tb) { TagBinder *res = NULL; if (attributes_(tb) & A_GLOBALSTORE) return tb; if (tb != NULL) { res = global_mk_tagbinder(NULL, bindsym_(tb), tagbindsort(tb)); tagbindparent_(res) = globalize_tagbinder(tagbindparent_(tb)); } return res; } /* Reading a name in C++. */ /* When we have a s_identifier in C++, we sometimes (but e.g. not after */ /* symbols like 'goto') read a qualified name. Other tokens - :: ~ and */ /* operator - also introduce entities handled as names. Here, all are */ /* read by a single mechanism. A serious wart on the implementation is */ /* caused by the recursion rd_cpp_name -> rd_operator_or_type_name() -> */ /* rd_typename() -> rd_cpp_name(). We handle this explicitly in rd_cpp_ */ /* name() rather than add yet another argument to every invocation of a */ /* function from this cycle. */ /* NOTE: we don't transform A to __ct_1A in class A MEMBER declaration */ /* context to avoid look-ahead (e.g. A(*B)() vs A(B) problems). We only */ /* do the transformation if it is completely certain, eg A::A, A::~A. */ /* NOTE: we should be careful about the (non-)effect of ungetsym() on */ /* the following statics as they aren't part of curlex. All is OK but */ /* rd_cpp_name()'s post-conditions must be maintained carefully. */ /* Lexical pre-conditions: */ /* curlex.sym is in {s_coloncolon,s_identifier,s_bitnot,s_operator} */ /* otherwise rd_cpp_name() is a no-op. */ /* Example constructs parsed: */ /* ::new, ::delete, ::name, S::*, S::operator op, S::identifier, S::~S */ /* S::operator X::T (which causes recursion), S::new, S::delete. */ /* Ambiguity detection following X. and X->: */ /* After X. and X-> (leftScope != 0), if there is an initial-type-name, */ /* it must be sought twice: once in leftScope and once in the scope */ /* enclosing X. In, for example, X.A::B::m, A::B must denote the same */ /* type in both contexts. NOTE: it is quite possible for this to hold */ /* even though A:: denotes <different> types in each context. See the */ /* DRAFT standard 5.2.4 <Class member access>. */ #define MSG_SILENT 0 #define MSG_DIAGNOSE 1 #define MSG_NOMORE 2 static void rd_cpp_name(TagBinder *leftScope) { int scopeFlags = ALLSCOPES, msg; static bool reading_conversion_typename = NO; bool is_dname = NO, expect_dtor = NO, expect_typename = NO, is_template_instance = NO, allowable_template_name = NO; Binder *tvb = NULL; switch (curlex.sym) { case s_bitnot: /* except after . -> and ::, ~ means bitnot, by A.R.M. fiat. */ if (leftScope == 0) return; case s_identifier: /* curlex.a2.flag on s_identifier protects against infinite */ /* recursion via rd_operator_or_type_name() if input is broken. */ if (curlex.a2.flag != 0) return; case s_typename: case s_operator: case s_coloncolon: /* These cases will consume tokens and/or alter curlex state. */ break; default: /* let the caller handle things we don't understand... */ return; } if (!reading_conversion_typename) { /* first entry - initialise return values */ curlex_scope = 0; curlex_binder = curlex_typename = 0; curlex_path = 0; curlex_member = 0; curlex_optype = 0; } if (leftScope == &DNAME) /* reading a name in declaration context - syntactically a dname... */ { leftScope = 0; is_dname = YES; msg = MSG_SILENT; } else if (leftScope == &TAS) { leftScope = 0; allowable_template_name = YES; msg = MSG_DIAGNOSE; } else msg = MSG_DIAGNOSE; switch (curlex.sym) { case s_typename: nextsym(); expect_typename = YES; break; case s_bitnot: nextsym(); if (curlex.sym != s_identifier) { ungetsym(); /* let the caller handle the diagnosis... */ return; } expect_dtor = YES; break; case s_operator: if (reading_conversion_typename) /* parsing botch - let the caller diagnose it */ return; nextsym(); curlex_scope = leftScope; /* in case a.operator B::T */ reading_conversion_typename = YES; rd_operator_or_conversion_name(); reading_conversion_typename = NO; if ((bind_scope & TOPLEVEL) && (curlex_scope == 0) && curlex.a1.sv == operator_name(s_assign)) cc_warn(syn_warn_special_ops); /* curlex.sym == s_pseudoid or error */ /* Are there operator templates? */ break; case s_coloncolon: /* leftScope != 0 is a parsing botch - let the caller handle. */ if (pp_inhashif || leftScope != 0) return; nextsym(); switch (curlex.sym) { default: cc_err(syn_err_cannot_follow_unary_dcolon); return; case s_new: case s_delete: curlex.sym |= s_qualified; return; case s_operator: nextsym(); rd_operator_name(); break; case s_identifier: break; } /* curlex.sym in {s_identifier,s_pseudoid} otherwise error. */ scopeFlags = FB_GLOBAL; break; case s_identifier: break; } /* Assert: curlex.sym in {s_pseudoid, s_identifier} otherwise error. */ if (curlex.sym == s_identifier) { Symstr *sv = curlex.a1.sv; TagBinder *lscope = leftScope; /* May have the start of a nested-name-specifier: check for :: */ for (;;) { TagBinder *primary = NULL, *instance = NULL; if (peepsym() == s_less && (primary = findtagbinding(sv, curlex_scope, ALLSCOPES)) != NULL) { if (peepsym() == s_less) is_template_instance = YES; rd_template_postfix(applicable_template_formals(), is_dname); if (curlex.a1.sv != sv && (instance = tag_global_(curlex.a1.sv)) != NULL && peepsym() != s_times) { syn_implicit_instantiate(primary, instance); sv = bindsym_(instance); } } nextsym(); if (curlex.sym != s_coloncolon) {ungetsym(); break;} if (primary == NULL && (tvb = findbinding(sv, NULL, ALLSCOPES)) != NULL && istypevar(bindtype_(tvb))) { typespecmap_(princtype(bindtype_(tvb))) |= bitoftype_(s_struct)|bitoftype_(s_class); binduses_(tvb) |= u_referenced; /* /* globalized just in case its parameter type */ curlex_scope = global_mk_tagbinder(NULL, sv, s_struct); tagbindparent_(curlex_scope) = NULL; tagbindtype_(curlex_scope) = globalize_typeexpr(mk_typeexpr1(s_typespec, (TypeExpr *)bitoftype_(s_typedefname), (Expr *)tvb)); } else { if (lscope != 0) lscope = findscope(sv, lscope, INDERIVATION, is_dname); if (curlex_scope != NULL && istypevar(tagbindtype_(curlex_scope))) { TagBinder *curScope = global_mk_tagbinder(NULL, sv, s_struct); tagbindparent_(curScope) = curlex_scope; curlex_scope = curScope; tagbindtype_(curlex_scope) = mk_typevar(); } else curlex_scope = findscope(sv, curlex_scope, scopeFlags, is_dname); if (curlex_scope == 0 && lscope == 0 && msg != MSG_NOMORE) msg = MSG_NOMORE, cc_err(syn_err_classname_not_found, sv); } /* once we have a curlex_scope, lookup is constrained to it */ scopeFlags = INDERIVATION; nextsym(); /* class-name coloncolon tilde ... is a destructor or error */ if (curlex.sym != s_identifier) break; sv = curlex.a1.sv; } /* Assert curlex.sym != s_identifier OR nxtsym != s_coloncolcon */ if (scopeFlags == INDERIVATION && lscope != 0) { if (curlex_scope != 0) { if (curlex_scope != lscope) { /* message re ambiguity... DRAFT standard 5.2.4 <Class member access>. */ cc_rerr(syn_rerr_ambiguous_qualification, curlex.a1.sv); msg = MSG_NOMORE; } } else curlex_scope = lscope; } switch (curlex.sym) { default: cc_err(syn_err_cannot_follow_binary_dcolon); return; case s_times: if (curlex_scope != 0) curlex.sym |= s_qualified; return; case s_bitnot: nextsym(); if (curlex.sym != s_identifier) { cc_err(syn_err_expected_dtor_name); ungetsym(); /* hope this is a good way to recover */ return; } expect_dtor = YES; break; case s_operator: if (reading_conversion_typename) return; /* parsing botch - let the caller diagnose it */ nextsym(); { TagBinder *curScope = curlex_scope; int scopelevel = push_multi_scope(curScope); curlex_scope = 0; reading_conversion_typename = YES; rd_operator_or_conversion_name(); reading_conversion_typename = NO; pop_scope(scopelevel); curlex_scope = curScope; } /* curlex.sym == s_pseudoid or error */ /* Are there operator templates? */ break; case s_template: nextsym(); break; case s_identifier: break; } } if (msg == MSG_NOMORE || curlex.sym != s_identifier && curlex.sym != s_pseudoid) return; if (scopeFlags != ALLSCOPES) curlex.sym |= s_qualified; /* rootOfPath is exported to xbind to support access control checks */ rootOfPath = (leftScope || curlex_scope) ? binder_cons2(binder_cons2(NULL, leftScope), curlex_scope) : NULL; /* Assert: scopeFlags is one of ALLSCOPES, INDERIVATION, FB_GLOBAL. */ if (leftScope != 0) curlex_path = findpath(curlex.a1.sv,leftScope,scopeFlags,curlex_scope); else curlex_path = findpath(curlex.a1.sv, curlex_scope, (is_dname ? ((scopeFlags&~FB_INHERIT)|FB_THISSCOPE) : scopeFlags), 0); curlex.a2.flag = 1; /* prevent reentry without an intervening call to nextsym() */ if (is_dname) rootOfPath = NULL; if (curlex_path == 0 && (feature & FEATURE_CFRONT) && /* This is illegal by the standard... last desperate effort */ /* to make sense of X::[~]X() where typedef T X... */ (curlex_scope != 0 || leftScope != 0)) { TagBinder *tb = findscope(curlex.a1.sv, 0, ALLSCOPES, is_dname); if (tb != 0 && (tb == curlex_scope || tb == leftScope)) curlex.a1.sv = tagbindsym_(tb); } try_again_for_ctor_or_dtor: if (curlex_path == 0) { Symstr *sv = curlex.a1.sv; if (scopeFlags == FB_GLOBAL) { /* unbound :: entity */ cc_err(syn_err_missing_tlevel_decl, sv); curlex_path = errornode; return; } rd_template_postfix(NULL, is_dname); if (curlex_scope != 0 && (tagbindsym_(curlex_scope) == sv || (tagprimary_(curlex_scope) != NULL && tagbindsym_(tagprimary_(curlex_scope)) == sv)) || leftScope != 0 && tagbindsym_(leftScope) == sv) { sv = expect_dtor ? dtorsym : ctorsym; if (curlex_scope == 0) curlex_scope = leftScope; curlex.a1.sv = sv; curlex.sym = (scopeFlags == ALLSCOPES) ? s_pseudoid : s_pseudoid|s_qualified; curlex_path = findpath(sv, curlex_scope, INCLASSONLY,0); } else if (leftScope == 0 && curlex_scope == 0 || curlex_scope != NULL && istypevar(tagbindtype_(curlex_scope)) || /* a la Microsoft Visual C++ - can declare class S {int S::x;}. */ curlex_scope == syn_class_scope) { /* allowably not found */ TagBinder *cl = current_member_scope(); if (is_dname) check_last_type_seen(); else if ((curlex_scope && istypevar(tagbindtype_(curlex_scope))) || (cl && (tagbindbits_(cl) & TB_TEMPLATE))) { if (expect_typename) { curlex_binder = find_typename(sv, curlex_scope); if (curlex_binder == NULL) { curlex_binder = global_mk_binder(NULL, sv, bitofstg_(s_typedef), mk_typevar()); bindparent_(curlex_binder) = curlex_scope; } curlex_typename = curlex_binder; } else curlex_binder = global_mk_binder(NULL, sv, bitofstg_(s_auto), mk_typevar()); } return; } if (curlex_path == 0) { #ifdef SURE_ABOUT_STATIC_MEM_SEMANTICS Expr *e; if (tagprimary_(curlex_scope) && (e = findpath(sv, tagprimary_(curlex_scope), scopeFlags, 0)) != NULL && h0_(e) == s_binder) { Binder *b = e; DeclRhsList decl; TypeExpr *t = clone_typeexpr(bindtype_(b)); fixup_template_arg_type(t, tagactuals_(curlex_scope)); decl.declname = ovld_add_memclass(sv, curlex_scope, NO); decl.declstg = bindstg_(b)|b_undef; decl.decltype = globalize_typeexpr(t); if (bindconst_(b) != NULL) declinit_(&decl) = mkcast(s_init, bindconst_(b), t); curlex_binder = instate_declaration(&decl, TOPLEVEL); return; } #endif cc_err(syn_err_not_found_named_member, sv, (leftScope != NULL) ? leftScope : curlex_scope); curlex_path = errornode; return; } } if (h0_(curlex_path) == s_binder) { TagBinder *thisscope = (curlex_scope) ? curlex_scope : current_member_scope(); curlex_binder = exb_(curlex_path); curlex_path = 0; /* first use, implicit instantiation from primary, any explicit specialization afterwards is a fault: specialization after use. 14.7.3 cl 5. */ if (!is_dname && bindstg_(curlex_binder) & b_undef && curlex_member != NULL && bindstg_(curlex_member) & b_pseudonym && !isfntype(bindtype_(curlex_binder)) && thisscope != NULL && tagprimary_(thisscope) != NULL) { Binder *b1 = findbinding(curlex.a1.sv, tagprimary_(thisscope), FB_LOCALS|FB_THISSCOPE); if (!b1 || !realbinder_(b1)) syserr("Lost static member $l in $c", thisscope); if (bindconst_(realbinder_(b1)) != NULL) { DeclRhsList *d; Expr *einit = bindconst_(realbinder_(b1)); push_exprtemp_scope(); einit = mkcast(s_init, einit, bindtype_(curlex_binder)); if (h0_(einit) != s_error) { einit = cpp_mkbinaryorop(s_init, (Expr *)curlex_binder, einit); bindstg_(curlex_binder) &= ~b_undef; d = mkDeclRhsList(bindsym_(curlex_binder), bindtype_(curlex_binder), bindstg_(curlex_binder)); d->declbind = curlex_binder; (void) genstaticparts(d, YES, typehasctor(bindtype_(curlex_binder)), einit); } if (killexprtemp() != NULL) syserr("extra temps leaked");; } } } else if (h0_(curlex_path) == s_dot) { TypeExpr *t = type_(curlex_path); if (h0_(t) == t_ovld || h0_(t) == t_fnap) { /* exprdotmemfn case... */ if (h0_(arg2_(curlex_path)) != s_binder) syserr("rd_cpp_name(bad exprdomemfn)"); curlex_binder = exb_(arg2_(curlex_path)); if (curlex_binder != NULL && peepsym() == s_less && h0_(princtype(bindtype_(curlex_binder))) == t_ovld) (void) rd_template_postfix(cur_tformals(), is_dname); if (curlex.sym & s_qualified) /* s_qualdot demands direct call/inhibits the virtual call mechanism. */ /* NB: modifying h0_() in place is OK: nothing points to the node yet. */ h0_(curlex_path) = s_qualdot; if (msg == MSG_DIAGNOSE) check_last_access(leftScope); if (is_dname) check_last_type_seen(); return; } } /* don't recognise typedefs in #if even if extension "keywords in #if"! */ if (pp_inhashif || (curlex.sym & ~s_qualified) == s_pseudoid) return; if (curlex_binder != 0 && (bindstg_(curlex_binder) & bitofstg_(s_typedef))) { TagBinder *thisscope = current_member_scope(); if (attributes_(curlex_binder) & A_PRIMARY && (thisscope == NULL || bindsym_(curlex_binder) != bindsym_(thisscope))) { if (thisscope != NULL && tagprimary_(thisscope) == typespectagbind_(bindtype_(curlex_binder))) { Binder *b; curlex.a1.sv = bindsym_(thisscope); curlex_binder = ((b = bind_global_(bindsym_(thisscope))) != NULL) ? b : findbinding(bindsym_(thisscope), NULL, FB_THISSCOPE|FB_CLASSNAME); } else if (!is_template_instance && !allowable_template_name) { cc_err(syn_err_unspecialized_template, curlex_binder); return; } } curlex_typename = curlex_binder; { TypeExpr *t = princtype(bindtype_(curlex_typename)); TagBinder *scope = leftScope != 0 ? leftScope : curlex_scope; int ctor_or_dtor = isclasstype_(t) && typespectagbind_(t) == scope; if (ctor_or_dtor || expect_dtor) { if (!ctor_or_dtor) cc_rerr(syn_rerr_expect_dtor, scope, curlex.a1.sv); curlex.a1.sv = tagbindsym_(scope); curlex_typename = 0; scopeFlags = INDERIVATION; goto try_again_for_ctor_or_dtor; } } } if (curlex_binder != NULL && h0_(princtype(bindtype_(curlex_binder))) == t_ovld) (void)rd_template_postfix(cur_tformals(), is_dname); if (msg == MSG_DIAGNOSE) check_last_access(leftScope); if (is_dname) check_last_type_seen(); } ScopeSaver copy_env(ScopeSaver env, int n) { Binder *p = NULL, *q = NULL; for (; env && n; env = bindcdr_(env), n--) { Binder *tmp = mk_binder(bindsym_(env), bindstg_(env), bindtype_(env)); if (!p) p = q = tmp; else { bindcdr_(q) = tmp; q = tmp; } } return p; } static void rd_template_postfix(ScopeSaver tformals, bool name_only) { /* assert: curlex.sym == s_identifer */ Symstr *sv = curlex.a1.sv, *sv2 = sv; TagBinder *tb; bool done = NO; int qualified = (curlex.sym & s_qualified); /* Question: if global S is a template class but local S is an int, */ /* then "S<..." is extremely dubious. Maybe 'findtagbinding' is wrong */ /* in the next line for this reason. */ if (peepsym() != s_less) return; if ((tb = findtagbinding(sv, NULL, ALLSCOPES)) != NULL && tagbindbits_(tb) & TB_TEMPLATE) { ExprList *actuals; int scope_level; bool newtag; /* @@@ need to move the unaliged-check code in rd_declspec */ TagBinder *tb2; ScopeSaver env = tagformals_(tb); int size = env_size(env); nextsym(); /* skip the identifier. */ nextsym(); /* skip the '<' seen by peepsym(). */ if ((tformals != NULL) && (size == env_size(tformals)) && name_only) /* Make sure names don't matter for ovld_template_app() purpose. */ env = copy_env(tformals, size); /* Push tformals the typenames introduced in a partial specialisation */ scope_level = push_var_scope(tformals, Scope_TemplateArgs); actuals = rd_template_actuals(YES); /* sv not necessarily the same as tagbindsym_() because of defaults */ sv = tagbindsym_(tb); sv2 = ovld_template_app(sv, env, actuals); if (sv2 != sv) { AEop s = tagbindsort(tb); tb2 = instate_tagbinding(sv2, s, TD_Decl, TOPLEVEL|TEMPLATE, &newtag); if (newtag) { Binder *b; tagprimary_(tb2) = tb; tagparent_(tb2) = NULL; /* always at top-level until namespace */ tagscope_(tb2) = /*dup_template_scope()*/ tagscope_(tb); add_instance((Binder *)tb2, &taginstances_(tb), YES); tagactuals_(tb2) = globalize_template_arg_binders(tagformals_(tb), actuals); b = instate_classname_typedef(tb2, TOPLEVEL); if (is_dependent_type(tagbindtype_(tb2))) tagformals_(tb2) = tformals /*tagformals_(tb)*/; else attributes_(b) |= A_TEMPLATE; } } (void)pop_scope(scope_level); done = YES; } /* Try function template */ else if (curlex_binder != NULL && bindftlist_(curlex_binder) != NULL) { Binder *b = curlex_binder; nextsym(); nextsym(); sv2 = bindsym_(b); /* A temp store for the actuals before specialization takes place. */ bindactuals_(b) = rd_template_actuals(YES); done = YES; } if (done) { /* @@@ the next 3 lines are unspeakably nasty (rationalise!). */ ungetsym(); curlex.sym = s_identifier|qualified; curlex.a1.sv = lex_replaceable_template_sym(sv2); } } static Binder *genstatictemp(TypeExpr *t) { Binder *b = mk_binder(gensymval(0), bitofstg_(s_static), t); SetDataArea(DS_ReadWrite); syn_initdepth = -1; syn_initpeek = 0; /* institutionalise! */ initstaticvar(b, 0); return b; } static void gen_reftemps() { for (; syn_reftemps; syn_reftemps = syn_reftemps->bindlistcdr) { SetDataArea(DS_ReadWrite); syn_initdepth = -1; syn_initpeek = 0; /* institutionalise! */ initstaticvar(syn_reftemps->bindlistcar, 0); } } static Cmd *syn_embed_if(CmdList *cl) { /* assert(cl != NULL); */ FileLine fl; fl = cmdcar_(cl)->fileline; /* fl for *first* dyn-static */ { Binder *b = genstatictemp(te_int); Expr *btest = optimise0(mkbinary(s_equalequal, (Expr *)b, lit_zero)); Expr *bset = optimise0(mkbinary(s_assign, (Expr *)b, lit_one)); CmdList *act = mkCmdList(cl, mk_cmd_e(s_semicolon, fl, bset)); return mk_cmd_if(fl, btest, mk_cmd_block(fl, 0, act), 0); } } static Cmd *rd_compound_statement(AEop op) { Cmd *c; if (curlex.sym == s_lbrace) c = rd_block(blk_INNER, YES); else { cc_rerr(syn_rerr_insert_braces, op); c = rd_command(1); } if (curlex.sym == s_nothing) nextsym(); return c; } static void syn_pop_linkage(void) { Linkage *p = syn_linkage; if (p == 0) syserr("pop_linkage(0)"); syn_linkage = p->linkcdr; p->linkcdr = syn_linkage_free; syn_linkage_free = p; } static int cmpANSIstring(String *s, char *t) { /* @@@ beware: treats concatenation as mismatch currently! */ StringSegList *z = s->strseg; return (h0_(s) == s_string && z->strsegcdr == 0 && z->strseglen == (IPtr)strlen(t)) ? memcmp(t, z->strsegbase, (size_t)z->strseglen) : 99; } static enum LinkSort linkage_of_string(String *s) { static struct { char lang[4]; enum LinkSort code; } valid[] = { "C++", LINK_CPP, "C", LINK_C }; unsigned i = 0; for (; i < sizeof valid/sizeof valid[0]; i++) if (cmpANSIstring((String *)s, valid[i].lang) == 0) return valid[i].code; cc_rerr(syn_rerr_unknown_linkage, s); return LINK_CPP; } static Binder *ovld_match_def(Binder *b, TypeExpr *t, BindList *l, bool prefer_tmpt, SET_BITMAP declflag) { /* declflag is examined for SPECIALIZE or INSTANTIATE purpose. */ if (!prefer_tmpt) for (; l != 0; l=l->bindlistcdr) { Binder *bb = l->bindlistcar; if (bindenv_(bb)) continue; /* ignore specialized */ if (equivtype(bindtype_(bb), t)) return bb; } /* try again for template memfn */ for (l = bindftlist_(b); l; l = l->bindlistcdr) { Binder *bb = l->bindlistcar; if (equivtype(bindtype_(bb), t)) return bb; } if (bindftlist_(b) != NULL && bindparent_(bindftlist_(b)->bindlistcar) !=NULL) { BindList *tmpts; ExprList *l = NULL; FormTypeList *ft = typefnargs_(t); for (; ft; ft = ft->ftcdr) l = mkExprList(l, (Expr *)gentempbinder(ft->fttype)); l = (ExprList *)dreverse((List *)l); if ((tmpts = temp_reduce(NULL, l, NULL, b)) != NULL) { Binder *ftemp = tmpts->bindlistcar, *fbind = NULL; ScopeSaver env = bindformals_(ftemp); bool has_failed = NO; TypeExpr *t = type_deduction(bindtype_(ftemp), l, bindactuals_(b), &env, YES, &has_failed); Binder *btop; DeclRhsList decl; SET_BITMAP stg; if (has_failed) syserr("type deduction failed: shouldn't happen"); t = globalize_typeexpr(t); env = globalize_env(env); fixup_template_arg_type(t, env); fbind = global_mk_binder(NULL, ovld_instance_name(ovld_tmptfn_instance_name(bindsym_(ftemp), env), t), bindstg_(ftemp), t); attributes_(fbind) |= attributes_(ftemp); bindstg_(fbind) |= b_undef; bindparent_(fbind) = bindparent_(ftemp); bindenv_(fbind) = env; /*typeovldlist_(bindtype_(b)) = (BindList *) global_cons2(SU_Type, typeovldlist_(bindtype_(b)), fbind);*/ add_instance(fbind, &typeovldlist_(bindtype_(b)), NO); add_instance(fbind, &bindinstances_(ftemp), YES); decl.declname = ovld_add_memclass(bindsym_(fbind), bindparent_(fbind), (bindstg_(fbind) & b_memfns) != 0); stg = killstgacc_(bindstg_(fbind)); if (stg & bitofstg_(s_static)) stg = (stg & ~bitofstg_(s_static))|bitofstg_(s_extern); decl.declstg = stg; decl.decltype = (stg & b_memfna) ? memfn_realtype(t, bindparent_(fbind)) : t; btop = instate_declaration(&decl, TOPLEVEL); bindenv_(btop) = bindenv_(fbind); realbinder_(fbind) = btop; bindactuals_(b) = NULL; if (declflag & INSTANTIATE && !(bindstg_(ftemp) & b_undef)) { ScopeSaver temp, q; temp = q = tagactuals_(bindparent_(fbind)); for (; q != NULL && bindcdr_(q) != NULL; q = bindcdr_(q)); if (q != NULL) bindcdr_(q) = env; else temp = env; add_pendingfn(bindsym_(btop), ovld_tmptfn_instance_name(bindsym_(ftemp), bindenv_(btop)), t, bindstg_(btop), bindparent_(fbind), temp, bindtext_(ftemp), bindenv_(btop), YES); if (q != NULL) bindcdr_(q) = NULL; bindstg_(fbind) &= ~b_undef; } return fbind; } } cc_err(syn_err_no_decl_at_type, b); return 0; } static void use_classname_typedef(TypeExpr *t) { /* Assert: isclasstype_(t)... */ TagBinder *tb = typespectagbind_(t); /* If tb->tagparent != 0, the associated type name will be found in */ /* scope tb->tagparent, unless tb is anonymous (gensym'd name). */ /* If tagparent is 0 and tb is not anonymous, then seek the nearest */ /* binding, which <should> be found in the scope containing tb... */ /* Note that we <must> find a typename if there is one... */ Binder *b = isgensym(tagbindsym_(tb)) ? 0 : findbinding(tagbindsym_(tb), tb->tagparent, ALLSCOPES|FB_CLASSNAME); if (b) binduses_(b) |= u_referenced; if (!LanguageIsCPlusPlus) syserr("use_classname_typedef()"); } static bool ispurefnconst(Expr *e) { /* Share the next tests with isnullptrconst()/move to sem.c? */ /* The present code allows "int f() = 0" but not "int f() = 0L" nor */ /* "int f() = 1-1" as [ES] suggest. */ TypeExpr *t; return (h0_(e) == s_integer && intval_(e) == 0 && intorig_(e) == 0 && h0_(t = princtype(type_(e))) == s_typespec && typespecmap_(t) == bitoftype_(s_int)); } /* <NAME> - Make it compile by losing the static */ #ifdef CALLABLE_COMPILER SynBindList *reverse_SynBindList(SynBindList *x) #else static SynBindList *reverse_SynBindList(SynBindList *x) #endif { SynBindList *p = 0; for (; x; x = x->bindlistcdr) p = mkSynBindList(p, x->bindlistcar); return p; } /* syn_copyscope() is expensive, but only called for labels/gotos. */ /* We *are* removing it by removing some of the dreverses and nconcs. */ static SynBindList *copy_SynBindList(SynBindList *x) { SynBindList *p = 0, *q = 0; if (debugging(DEBUG_SYN)) cc_msg("("); for (; x; x = x->bindlistcdr) { SynBindList *t = mkSynBindList(0, x->bindlistcar); if (p == 0) p = q = t; else q->bindlistcdr = t, q = t; if (debugging(DEBUG_SYN)) cc_msg("$b", x->bindlistcar); } if (debugging(DEBUG_SYN)) cc_msg(")"); return p; } static SynScope *syn_copyscope(SynScope *x) { SynScope *p = 0, *q = 0; if (debugging(DEBUG_SYN)) cc_msg("copy_scope["); for (; x; x = x->cdr) { SynBindList *bl = copy_SynBindList(x->car); SynScope *t = mkSynScope(0, bl, x->scopeid); if (p == 0) p = q = t; else cdr_(q) = t, q = t; } if (debugging(DEBUG_SYN)) cc_msg("]\n"); return p; } static Expr *unbind_dtor(SynScope *to, SynScope *from) { Expr *edtor = 0, *ector = 0; SynScope *s, *fromx = from, *tox = to; /* Find a common, but possibly copied, substring of from and to: */ /* Relies on scopeid(children) > scopeid(parent). */ if (!LanguageIsCPlusPlus) return edtor; for (;;) { if (fromx == 0) { tox = 0; break; } if (tox == 0) { fromx = 0; break; } if (fromx->scopeid == tox->scopeid) break; if (fromx->scopeid > tox->scopeid) fromx = fromx->cdr; else tox = tox->cdr; } for (s = to; s != tox; s = s->cdr) { SynBindList *l; for (l = s->car; l; l = l->bindlistcdr) { Binder *b = l->bindlistcar; if (attributes_(b) & A_DYNINIT /* && ector == 0 */ ) { /* one day do ctors for such, hence ector. */ /* @@@ in particular setting b to undefined would improve liveness */ /* calculations for branches into blocks! */ ector = (Expr *)b; /* next line is error to agree with Cfront 3.1 */ if ((feature & FEATURE_CFRONT) && !typehasctor(bindtype_(b)) && h0_(princtype(bindtype_(b))) != t_ref) cc_warn(syn_rerr_jump_past_init, b); else cc_rerr(syn_rerr_jump_past_init, b); } } } for (s = from; s != fromx; s = s->cdr) { Expr *e = mkdtor_v_list(s->car); /* @@@ backwards? */ /* next line is 'commacons'. */ edtor = edtor==0 ? e : e==0 ? edtor : mkbinary(s_comma, edtor, e); } return edtor; } static Cmd *cmd_rescope(SynScope *to, SynScope *from, Cmd *c) { Expr *edtor = unbind_dtor(to, from); if (edtor && h0_(edtor = optimise0(edtor)) != s_error) { if (h0_(c) == s_return && cmd1e_(c) != 0) { if (cur_structresult != 0) cmd1e_(c) = mkbinary(s_comma, cmd1e_(c), mkcast(s_return, edtor, te_void)); else { Expr *e = cmd1e_(c); Expr *ee = (h0_(e) == s_return) ? arg1_(e) : e; TypeExpr *t = typeofexpr(ee); Binder *gen = gentempbinder(t); ee = mkbinary(s_init, (Expr *)gen, ee); ee = mkbinary(s_comma, ee, edtor); ee = mkbinary(s_comma, ee, (Expr *)gen); ee = mk_exprlet(s_let, t, mkSynBindList(0, gen), ee); /* may change type (in a harmless way) */ ee = optimise0(ee); if (h0_(e) == s_return) arg1_(e) = ee; else cmd1e_(c) = ee; } } else { FileLine fl; fl = c ? c->fileline : syn_invented_fl; c = mk_cmd_block(fl, 0, mkCmdList(mkCmdList(0, c), mk_cmd_e(s_semicolon, fl, edtor))); } } return c; } static void syn_setlab(LabBind *lab, SynScope *defscope) { /* Modifies code in forward-reference gotos to include dtors. */ SynGoto *ref = lab->labu.ref; lab->labu.def = syn_copyscope(defscope); for (; ref; ref = ref->cdr) { Expr *edtor = unbind_dtor(defscope, ref->gotoscope); if (edtor) { Cmd *c = ref->gotocmd; CmdList *cl = cmdblk_cl_(c); cmdcar_(cl) = mk_cmd_e(s_semicolon, c->fileline, optimise0(edtor)); } } } static Cmd *syn_reflab(LabBind *lab, SynScope *s, Cmd *c) { if (lab->labuses & l_defined) c = cmd_rescope(lab->labu.def, s, c); else { /* for goto-destructors -- updated by syn_setlab(). */ c = mk_cmd_block(c->fileline, 0, mkCmdList(mkCmdList(0, c), 0)); /* The top-level copy of synscope is essential (avoids dtors of yet-to- */ /* -be-bound reftemps). The rest is needed because of dreverses (q.v.) */ lab->labu.ref = mkSynGoto(lab->labu.ref, c, syn_copyscope(s)); } return c; } void push_exprtemp_scope(void) { if (temps == 0) temps = mkSynScope(0, 0, ++temps_scopeid); else temps = mkSynScope(temps, 0, ++temps_scopeid); } void pop_exprtemp_scope(void) { SynScope *prev = temps->cdr; if (temps == NULL) syserr("pop_exprtemp_scope: no exprtemp scope"); discardSynScope(temps); temps = prev; --temps_scopeid; } Binder *genexprtemp(TypeExpr *t) { Binder *b = (bind_scope & TOPLEVEL) ? genglobinder(globalize_typeexpr(t)) : gentempbinder(t); #ifdef CALLABLE_COMPILER dbgdata_(b, VoidStar) = (VoidStar)dbg_mk_formatpack(NULL, NULL); #endif if (temps == NULL) { /*/* surely this should be a syserr */ #if 0 syserr("genexprtemp: no temp scope"); #else if (var_cc_private_flags & 65536) cc_msg("genexprtemp: called without a temp scope\n"); #endif } else temps->car = mkSynBindList(temps->car, b); return b; } static SynScope *saved_temps; void push_saved_temps(int32 scopeid) { if (LanguageIsCPlusPlus) saved_temps = mkSynScope(saved_temps, 0, scopeid); } /* prepends the binders of the saved temps to bl */ SynBindList *pop_saved_temps(SynBindList *bl) { if (LanguageIsCPlusPlus) { SynBindList *st = saved_temps->car; SynScope *prev = saved_temps->cdr; while (st) { Binder *b = st->bindlistcar; bl = mkSynBindList(bl, b); st = st->bindlistcdr; } discardSynScope(saved_temps); saved_temps = prev; return bl; } else if (saved_temps != NULL) syserr("unexpected saved temps"); return bl; } void add_expr_dtors(Expr *edtor) { if (edtor != NULL) expr_dtors = commacons(expr_dtors, edtor); } void add_to_saved_temps(SynBindList *tmps) { if (!saved_temps) syserr("no saved temps scope"); for(; tmps != NULL; tmps = tmps->bindlistcdr) saved_temps->car = mkSynBindList(saved_temps->car, tmps->bindlistcar); } Expr *killexprtemp() { Expr *edtor = 0; SynBindList *t; if (temps == 0) { /*/* surely this should be a syserr */ #if 0 syserr("genexprtemp: no temp scope"); #else if (var_cc_private_flags & 65536) cc_msg("killexprtemp: no temps scope\n"); #endif } else { t = temps->car; while (t != 0 && saved_temps) { Binder *b = t->bindlistcar; edtor = commacons(edtor, mkdtor_v((Expr *)b)); saved_temps->car = mkSynBindList(saved_temps->car, b); t = t->bindlistcdr; } pop_exprtemp_scope(); } return (edtor == 0) ? 0 : optimise0(edtor); } /* Note that these following routine is declared in bind.h (!!). */ Binder *genreftemp(TypeExpr *t) { /* the test below may be made more generous so we can deal more */ /* effectively with f() { extern foo(); ... } etc. */ Binder *b = (bind_scope & TOPLEVEL) ? genglobinder(globalize_typeexpr(t)) : gentempbinder(t); #ifdef CALLABLE_COMPILER dbgdata_(b, VoidStar) = (VoidStar) dbg_mk_formatpack(NULL, NULL); #endif /* in flux: */ if (synscope) synscope->car = mkSynBindList(synscope->car, b); else syn_reftemps = mkSynBindList(syn_reftemps, b); return b; } int killnexprtemp(Binder *b) { if (temps) { SynBindList *bl, **blp = &temps->car; for (bl = *blp; bl != 0; bl = *(blp = &bl->bindlistcdr)) if (bl->bindlistcar == b) { *blp = bl->bindlistcdr; return 1; } } return 0; } int killreftemp(Binder *b) { SynBindList *bl, **blp = synscope ? &synscope->car : &syn_reftemps; for (bl = *blp; bl != 0; bl = *(blp = &bl->bindlistcdr)) if (bl->bindlistcar == b) { *blp = bl->bindlistcdr; return 1; } return 0; } static Expr *rd_cppcast(void) { /* C++ casts of the form type(e1,...,en) */ /* return 0 to indicate absence of '( after the type. */ TypeSpec *t; AE_op s = (AE_op)(curlex.sym & ~s_qualified); /*/* @@@ Need to add wchar_t to this list... */ if ((s == s_char || s == s_short || s == s_signed || s == s_int || s == s_long || s == s_float || s == s_double || s == s_unsigned || s == s_bool || s == s_float || s == s_identifier) && peepsym() == s_lpar) { ExprList *l; t = rd_typename(SIMPLETYPE); nextsym(); l = rd_exprlist_opt(); /* There is an ambiguity in the semantics of the 'type(e1,...,en)' */ /* construct which means that this code does not share with mkcast(). */ /* Consider: class A { A(B&); }; class B { operator A(); }; */ /* ...; A a; B b; ...; a = b; */ /* This is ambiguous as to whether a = A::A(b) or a = b.operator A() */ /* is meant. This is presumably also true for a = (A)b; */ /* However, it seems plausible that a = A(b) can ONLY have the former */ /* meaning (conversion by constructor). */ /* Hence we take all such calls to mean conversion by constructor. */ /* (the alternative would be to pass all 1-argument calls to mkcast */ /* by swapping the following two tests. */ if (typehasctor(t)) return mkctor_t(t, l); if (l && !cdr_(l)) return mkcast(s_cast, exprcar_(l), t); if (l == 0) { TypeExpr *pt = princtype(t); if (h0_(pt) == t_ref || h0_(pt) == t_content) return mkintconst(t, 0, 0); if (issimpletype_(pt)) return mkcast(s_init, lit_zero, t); t = pt; } if (!istypevar(t)) cc_err(syn_err_lacks_arg_ctor, t, (long)length(l)); return errornode; } return 0; } /* The following mirrors rd_declrhslist()... */ /* But should it be in bind.c? */ /* Yes, but only if we get rid of the FileLine's. */ static Binder *instate_classname_typedef(TagBinder *tb, int declflag) { DeclRhsList *d = mkDeclRhsList(bindsym_(tb), tagbindtype_(tb), bitofstg_(s_typedef)|u_implicitdef); Binder *b; FileLine fl; fl = curlex.fl; fl.p = dbg_notefileline(fl); d->fileline = fl; if ((declflag & MEMBER) && (tb->tagparent != 0)) { d->declstg |= stgaccof_(access); b = instate_member(d, bind_scope); } else { b = instate_classname(d, tb); if (b != NULL && usrdbg(DBG_PROC)) dbg_type(bindsym_(b), bindtype_(b), d->fileline); } /* propagate linkage attributes from type to typename... */ /* @@@ Danger of collision with attribofstgacc_() */ if (b != NULL) attributes_(b) |= attributes_(tb) & (A_NOLINKAGE+A_INTERN+A_EXTERN); return b; } static void instate_anonu_members(int declflag, Binder *b) { ClassMember *l = tagbindmems_(typespectagbind_(bindtype_(b))); for (; l != NULL; l = memcdr_(l)) { Symstr *sv = memsv_(l); if (h0_(l) == s_tagbind) continue; if (h0_(l) != s_member || sv == 0) cc_rerr(syn_rerr_illegal_anon_union_mem, sv); else { TypeExpr *t = memtype_(l); DeclRhsList *d = mkDeclRhsList(sv, t, 0); Binder *db; if ((attributes_(l) & ACCESSBITS) != bitofaccess_(s_public)) cc_rerr(syn_rerr_illegal_nonpub_anon_union_mem, sv); if (declflag & MEMBER) { d->declstg = (attributes_(b) & ACCESSBITS) << 28-shiftoftype_(s_union+1); /* @@@ stgaccof_(...) */ db = instate_member(d, bind_scope); membits_(db) = membits_(l); } else db = instate_declaration(d, declflag); attributes_(db) |= CB_ANON; realbinder_(db) = b; } } } /* rationalise next code with caller. */ /* there are also similarities with mkopap(). */ static Binder *syn_binderofname(Symstr *sv, TagBinder *optclass) { Binder *b; if (sv == 0) syserr("syn_binderofname"); /* @@@ if s_qualified then curlex_binder should already hold! */ /* Hmm, the above comment taken from rd_idexpr(). It applies to */ /* the call from cfe/syn.c but not from new/delete below. */ b = optclass == NULL ? NULL : findbinding(sv, optclass, INDERIVATION); if (b == NULL && (b = findbinding(sv, NULL, FB_GLOBAL)) == NULL) syserr("syn_binderofname '%s'", symname_(sv)); else if (h0_(b) != s_binder) syserr("non fn operator member '%s'", symname_(sv)); else if (bindstg_(b) & bitofstg_(s_typedef)) syserr("operator typedef '%s'", symname_(sv)); return b; } static Cmd *conditionalised_delete(Binder* thisb, Binder* isdelb, TagBinder *parent) { Binder *delgeneric = syn_binderofname(cppsim.xdel, parent); Expr *magic_test = optimise0(mkbinary(s_notequal, #ifdef CFRONT_COMPATIBLE_DESTRUCTORS /* testing '(is_delete & 1) != 0' instead of 'is_delete != 0' */ /* creates destructors that Cfront-built code can call (if */ /* there is no muliple inheiritance). The code is the same */ /* size on the ARM. */ mkbinary(s_and, (Expr *)isdelb, lit_one), #else (Expr *)isdelb, #endif lit_zero)); ExprList *delargs = 0; Expr *e; binduses_(isdelb) |= u_referenced; if (is_two_arg_delete(delgeneric)) delargs = mkExprList1(mkintconst(te_size_t, sizeoftype(typearg_(typeofexpr((Expr *)thisb))), 0)); delargs = mkExprList(delargs, (Expr*)thisb); e = mkfnap((Expr *)delgeneric, delargs); return mk_cmd_if(curlex.fl, magic_test, mk_cmd_e(s_semicolon, curlex.fl, optimise0(e)), 0); } /* Move to aeops.h (can be done via bit twiddle)... */ #define ispostop_(op) ((op) == s_postinc || (op) == s_postdec) /* We treat operator->() as a monadic op -- see [ES, p337]. */ static Expr *cpp_mkunaryorop(AEop op, Expr *x) { TypeExpr *tx = typeofexpr(x); TagBinder *bx; if (is_dependent_type(tx)) return errornode; bx = isclassenumorref_type(tx); if (bx) { /* [ES, p338] say that postfix ++/-- gets an 2nd param of 0. */ Expr *r = mkopap(op, bx, x, ispostop_(op) ? mkExprList1(lit_zero) : NULL); if (r) { if(h0_(r) != s_operator) { if (op != s_arrow) return r; if (bx == isclassenumorref_type(typeofexpr(r))) { cc_err(syn_err_recursive_app_operator_arrow, bx); return errornode; } else return cpp_mkunaryorop(op,r); } x = user_conversion(x, bx, (TypeExpr *)((List3 *)r)->car); discard3(r); } } return op == s_arrow ? x : mkunary(op, x); } Expr *cpp_mkbinaryorop(AEop op, Expr *x, Expr *y) { TypeExpr *tx = typeofexpr(x); TypeExpr *ty = typeofexpr(y); TagBinder *bx, *by; if (is_dependent_type(tx) || is_dependent_type(ty)) return errornode; bx = isclassenumorref_type(tx); by = isclassenumorref_type(ty); if (op != s_dotstar && (bx || by)) { Expr *r = mkopap(op, bx, x, mkExprList1(y)); if (r) { if (h0_(r) != s_operator) return r; x = user_conversion(x, bx, (TypeExpr *)((List3 *)r)->car); y = user_conversion(y, by, (TypeExpr *)((List3 *)r)->csr); discard3(r); } else if (op == s_assign && bx && (tagbindbits_(bx) & TB_HASCMEM)) /* should really complained about const member, new error msg? */ cc_rerr(syn_err_not_found_named_member, assignsym, bx); } return mkbinary(op, x, y); } static Expr *cpp_mkfnaporop(Expr *e, ExprList *l) { TypeExpr *te = typeofexpr(e); TagBinder *be; if (is_dependent_type(te)) return errornode; be = isclassenumorref_type(te); if (te) { /* [ES, p355] require operator() to be a member fn. We don't. */ Expr *r = mkopap(s_fnap, be, e, l); if (r) { if (h0_(r) != s_operator) return r; } } return mkfnap(e, l); } /* Calculate from inside so that any variable will be at the top. */ static TypeExpr *new_basetype(TypeExpr *t, Expr **nelts) { t = princtype(t); if (h0_(t) == t_subscript) { Expr *size = typesubsize_(t); t = new_basetype(typearg_(t), nelts); /* The next error message is borrowed from sem.c(sizeoftype). */ if (size == 0) cc_rerr(sem_rerr_sizeof_array); else if (*nelts == 0) *nelts = size; else *nelts = mkbinary(s_times, *nelts, size); return t; } if (!isclasstype_(t)) { *nelts = mkintconst(te_size_t, sizeoftype(t), 0); return 0; } else { *nelts = 0; return t; } } static Expr *rd_new(AEop op) { TypeExpr *t, *newt; Binder *newgeneric; ExprList *placement = 0, *init = 0; Expr *nelts; bool forceglobal = NO; nextsym(); retry: if (curlex.sym == s_lpar) { nextsym(); rd_cpp_name(0); /* don't know if type or expr yet */ if (placement != 0 || (isdeclstarter2_(curlex) && (peepsym() != s_lpar || is_type_id()))) { t = rd_typename(FLEX_TYPENAME); checkfor_ket(s_rpar); } else { placement = rd_exprlist_opt(); /* fault '()' above as Type, so opt() doesn't happen. */ goto retry; } } else t = rd_typename(NEW_TYPENAME); newt = prunetype(t); t = new_basetype(t, &nelts); if (curlex.sym == s_lpar) { nextsym(); /* @@@ we need to allow '{}' form inits in the following soon. */ init = rd_exprlist_opt(); if (init && h0_(newt) == t_subscript) cc_err(syn_err_ignored_new_array_ctor), init = 0; } if (t == 0) newgeneric = syn_binderofname(cppsim.xnew, 0); else { newgeneric = syn_binderofname(cppsim.xnew, typespectagbind_(t)); /* /* should we really check 'op new' access for '::new T' and '::new T[n]'? */ forceglobal = (op & s_qualified) && bindparent_(newgeneric) != 0; if ((op & s_qualified) || nelts) newgeneric = syn_binderofname(cppsim.xnew, 0); } return mknew(newt, t, newgeneric, nelts, placement, init, forceglobal); } static Expr *rd_delete(AEop op) { Expr *e; TypeExpr *t; bool isarray = NO; nextsym(); /* call __dl(p) for delete p/delete [] p; where p is not ptr-to-class. */ /* call __dl_v(p,eltsize,dtor) for delete[]p; where p is ptr-to-class. */ if (curlex.sym == s_lbracket) { isarray = YES; nextsym(); if (curlex.sym != s_rbracket) { if (feature & FEATURE_CFRONT) cc_warn(syn_rerr_delete_expr_anachronism); else cc_rerr(syn_rerr_delete_expr_anachronism); (void)rd_expr(PASTCOMMA); } checkfor_ket(s_rbracket); } e = rd_prefixexp(NOLABEL); /* disallow int a[5]; delete a; */ if (h0_(princtype(typeofexpr(e))) == t_subscript) { cc_err(syn_err_requires_pntr_arg, s_delete); return errornode; } if (h0_(e = coerceunary(e)) == s_error) return e; t = princtype(typeofexpr(e)); if (h0_(t) != t_content) { cc_err(syn_err_requires_pntr_arg, s_delete); return errornode; } t = princtype(typearg_(t)); if (isclasstype_(t) && !(tagbindbits_(typespectagbind_(t)) & TB_DEFD)) cc_warn(xsyn_warn_delete_undef, typespectagbind_(t)); { Expr *temp; bool forceglobal = NO; Binder *delgeneric; t = isprimtype_(t, s_void) ? te_void : new_basetype(t, &temp); if (t == 0) delgeneric = syn_binderofname(cppsim.xdel, 0); else { delgeneric = syn_binderofname(cppsim.xdel, typespectagbind_(t)); /* /* should we really check 'op delete' access for '::delete T' and '::delete T[n]'? */ forceglobal = (op & s_qualified) && bindparent_(delgeneric) != 0; if ((op & s_qualified) || isarray) delgeneric = syn_binderofname(cppsim.xdel, 0); } return mkdelete(e, t, isarray, delgeneric, forceglobal); } } static Expr *rd_cpp_prefixextra(AEop op) { switch (op) { case s_new: case s_qualified+s_new: /* maybe s_qualified (by top-level only). */ return rd_new(op); case s_delete: case s_qualified+s_delete: /* maybe s_qualified (by top-level only). */ return rd_delete(op); case s_throw: { Expr *a; nextsym(); /* use same binding as sizeof xxx for throw xxx. */ a = isexprstarter(curlex.sym) ? rd_prefixexp(NOLABEL) : 0; return a; /*will be something like mkthrow(syn_invented_fl, a);*/ } default: syserr("rd_cpp_prefixextra()"); } return errornode; } #if 0 /* C++ for's (i.e. of the form "for (decl; exp; exp) cmd") are nasty */ /* and presumably subject to change -- Ellis and Stroustrup require */ /* the scope of decl to be the rest of the block: simulate this. */ /* Draft std of 28-April-1995 said scope of decl extends to end of the */ /* for-statement. */ static Cmd *rd_cplusplus_for(FileLine fl) { synscope = mkSynScope(synscope, 0, ++synscopeid); { DeclRhsList *d = rd_decl2(BLOCKHEAD, 0), *dp; /* is BLOCKHEAD right? */ SynBindList *dd; Expr *e1 = 0, *edtor; CmdList *cp, *cq; /* The following code to perform initialisation is turned into a */ /* s_comma Expr (this allows exploitation of for-init code in cg.c */ /* for constant propagation) but similar code in rd_block() uses Cmd!! */ for (dp = d; dp != 0; dp = dp->declcdr) /* add dynamic inits */ { Expr *einit = declinit_(dp); /* see genstaticparts() */ if (einit) { if (debugging(DEBUG_SYN)) cc_msg("[Init]"); e1 = e1 ? mkbinary(s_comma, e1, einit) : einit; } } e1 = e1 ? optimise0(mkcast(s_for, e1, te_void)) : 0; if (curlex.sym == s_nothing) nextsym(); /* tidy after rd_decl2. */ cp = cq = mkCmdList(0, rd_for_2(e1,fl)); #if NEVER synscope->car = mkSynBindList_from_Decl(d, synscope->car); #endif if (curlex.sym == s_nothing) nextsym(); while (curlex.sym != s_rbrace && /* not end of scope */ curlex.sym != s_eof) /* not botched eof */ { CmdList *ct = mkCmdList(0, rd_command(1)); if (curlex.sym == s_nothing) nextsym(); cdr_(cq) = ct, cq = ct; } dd = synscope->car; synscope = synscope->cdr; pop_scope(scope_level); edtor = mkdtor_v_list(dd); if (edtor) { /* just what is the right FileLine for a dtor? */ CmdList *ct = mkCmdList(0, mk_cmd_e(s_semicolon, fl, optimise0(edtor))); if (cp == 0) cp = cq = ct; else cdr_(cq) = ct, cq = ct; } return mk_cmd_block(fl, reverse_SynBindList(dd), cp); } } #endif static Expr *rd_declrhs_exec_cpp(DeclRhsList *d, int* initflag) { TypeExpr *dtype = d->decltype, *elmtype; Expr* init = 0; if (typehasctor(dtype)) { if (curlex.sym == s_assign) { nextsym(); if (curlex.sym == s_lbrace) { cc_err(syn_err_constructor_init, d->declname); syn_initdepth = 0, syn_initpeek = 0, (void)syn_rdinit(0,0,4); } else { Expr *einit = rd_expr(UPTOCOMMA); /* this cast keeps 12p3p1b.c from breaking */ einit = mkcast(s_init, einit, d->decltype); if (h0_(einit) != s_error) init = cpp_mkbinaryorop(s_init, (Expr *)d->declbind, einit); } *initflag = 3; } else { init = mkctor_v((Expr *)d->declbind, 0); *initflag = 3; } } else /* initialising an array of class */ if (isarraytype(dtype, &elmtype) && typehasctor(elmtype)) { if (curlex.sym == s_assign) { int32 i, upb, note; TypeExpr *t = ptrtotype_(elmtype); nextsym(); /* @@@ botch to error recovery? */ syn_initdepth = 0; note = syn_begin_agg(); #define OPEN_ARRAY_SIZE 0xffffff upb = (typesubsize_(dtype) && h0_(typesubsize_(dtype)) != s_binder) ? evaluate(typesubsize_(dtype)) : OPEN_ARRAY_SIZE; for (i = 0; i < upb; ++i) { Expr *thisp, *init = NULL; if (syn_canrdinit()) init = rd_expr(UPTOCOMMA); else { if (upb == OPEN_ARRAY_SIZE) { if (i) typesubsize_(bindtype_(d->declbind)) = globalize_int(i); break; } } thisp = mk_expr2(s_plus, t, mk_expr1(s_addrof, t, (Expr *)datasegment), mkintconst(te_int, get_datadesc_size(), 0)); /* initializing value may not have the right type */ if (init != NULL) init = mkcast(s_init, init, elmtype); if (init == NULL || h0_(init) != s_error) { TagBinder *cla = typespectagbind_(elmtype); Expr *einit = init == NULL ? mkfnap(mkfieldselector(s_arrow, thisp, findbinding(ctorsym, cla, INCLASSONLY)), 0) : cpp_mkbinaryorop(s_init, mkunary(s_content, thisp), init); init = init == 0 ? einit : mkbinary(s_comma, init, einit); } gendc0(sizeoftype(elmtype)); if (curlex.sym == s_comma) nextsym(); } *initflag = 3; syn_end_agg(note); } else { init = mkctor_v((Expr *)d->declbind, 0); if (init) binduses_(d->declbind) |= u_referenced; *initflag = 3; } } else if (!(d->declstg & bitofstg_(s_auto)) && curlex.sym == s_assign && (issimpletype_(princtype(dtype)) || istypevar(dtype))) { nextsym(); init = syn_rdinit(dtype, d->declbind, 0); *initflag = 1; } return init; } static TypeExpr *fixup_special_member(Symstr *name, TypeExpr *giventype, TypeExpr *fnrtype, TagBinder *scope, SET_BITMAP stg) { /* cc_msg("fixup_special_member $r\n", name); */ /* Note that special members (ctors/dtors &c) cannot have result types */ /* and hence we don't have to check for s_typedef with prunetype(). */ /* But we do it to catch 'typedef void F(); struct T { F T; };' */ TypeExpr *pt = princtype(giventype); if (h0_(pt) == t_fnap && !(stg & bitofstg_(s_typedef))) { bool msg = 0; TypeExpr *pta; FormTypeList *f = 0; SET_BITMAP quals = typeptrmap_(pt); if (name == ctorsym) { f = typefnargs_(pt); if (f && minargs_(pt) <= 1 && 1 <= maxargs_(pt)) { TypeExpr *t = princtype(f->fttype); if (isclasstype_(t) && typespectagbind_(t) == scope) { cc_rerr(syn_rerr_self_copying_ctor, scope); msg = 1; f = mkFormTypeList(f->ftcdr, f->ftname, mk_typeexpr1(t_ref, f->fttype, 0), f->ftdefault); } } } else if (typefnargs_(pt) != NULL) cc_rerr(xsyn_rerr_zero_params, scope, name); else if (name != dtorsym) { /* conversion operator */ if (scope == 0 || (stg & bitofstg_(s_static))) cc_rerr(xsyn_rerr_non_memfn_operator, scope, name); else if (equivtype(fnrtype, te_void)) cc_rerr(xsyn_rerr_bad_conv, scope, name); } if (!msg && !((typefnaux_(pt).flags & f_norettype) && h0_(pta = typearg_(pt)) == s_typespec && typespecmap_(pta) == bitoftype_(s_int))) cc_rerr(xsyn_rerr_no_return_type_allowed, scope, name); /* Make ctor's return their 'this' arg. */ /* @@@ This syserr happens for broken input like 'struct X { int f(); }; X::X() { }' needs fixing */ if (name == ctorsym) { if (scope == 0) syserr("fix up ctor: scope == 0"); fnrtype = ptrtotype_(tagbindtype_(scope)); } return mkTypeExprfn(t_fnap, fnrtype, quals, f, &typefnaux_(pt)); } else cc_rerr(xsyn_rerr_must_be_function, scope, name); return giventype; } static void memfn_typefix(DeclRhsList *d, TagBinder *scope) { TypeExpr *fntype = prunetype(d->decltype); if (h0_(fntype) != t_fnap || scope == 0) syserr("memfn_typefix"); if (strncmp(symname_(d->declname), "__dt", 4) == 0) fntype = add_delete_arg(fntype, NO); d->decltype = memfn_realtype(fntype, scope); } static ClassMember *nconc_member(ClassMember *list, ClassMember *member) { ClassMember *q = list; if (q == NULL) return member; for (;;) { if (equivtype(memtype_(q), memtype_(member))) { TypeExpr *t = memtype_(q); TagBinder *b; if (h0_(t) == t_content) t = typearg_(t); b = typespectagbind_(t); if (tagbindbits_(b) & TB_CORE) b = b->tagparent; cc_rerr(syn_rerr_duplicated_base, b); return list; } if (memcdr_(q) == NULL) break; q = memcdr_(q); } memcdr_(q) = member; return list; } static ClassMember *clone_member(ClassMember *p, SET_BITMAP attributes) { ClassMember *q = (ClassMember *) memcpy(GlobAlloc(SU_Other,(int32)SIZEOF_CLASSMEMBER), p, (size_t)SIZEOF_CLASSMEMBER); memcdr_(q) = NULL; attributes_(q) = attributes & ~A_LOCALSTORE | A_GLOBALSTORE; return q; } #define DONT_COPY ((SET_BITMAP)-1) static ClassMember *append_no_dups(ClassMember *mem, SET_BITMAP attributes, ClassMember *list) { ClassMember *q, *prev = NULL; for (q = list; q != NULL; prev = q, q = memcdr_(q)) if (equivtype(memtype_(q), memtype_(mem)) == 2) return list; if (attributes == DONT_COPY) q = mem; else q = clone_member(mem, attributes); if (list == NULL) list = q; else memcdr_(prev) = q; return list; } static ClassMember *append_vbases_of(TagBinder *base_tag, SET_BITMAP attributes, ClassMember *list) { ClassMember *p = tagbindmems_(base_tag); if (p != NULL && (attributes_(p) & CB_CORE)) for (p = memcdr_(p); p && (attributes_(p) & CB_VBASE); p = memcdr_(p)) list = append_no_dups(p, attributes, list); return list; } #ifdef DEBUG_CLASS static void print_classdecl(ClassMember *list, int indent) { ClassMember *p; for (p = list; p != NULL; p = memcdr_(p)) { printf(" %*s%s\n", indent, "", memsv_(p)->symname); if (isclasstype_(memtype_(p))) { printf(" %*s{%s}\n", indent, "", typespectagbind_(bindsym_(memtype_(p)))->symname); print_classdecl( typespectagbind_(memtype_(p))->tagbindmems, indent+4); } } } #endif /* DEBUG_CLASS */ #define is_purevirtual(l) (bindstg_(l) & b_purevirtual) static bool chk_abstractness(TagBinder *cl, List *derivation) { ClassMember *l; TagBinder *tb; for (l = tagbindmems_(cl); l != NULL; l = memcdr_(l)) { SET_BITMAP bm = attributes_(l); if (h0_(l) == s_tagbind) continue; tb = typespectagbind_(memtype_(l)); if (bm & CB_CORE) { if (chk_abstractness(tb, (List *)syn_cons2(derivation, tb))) return YES; } else if (bm & CB_BASE) { if (tagbindbits_(tb) & TB_ABSTRACT) if (chk_abstractness(tb, (List *)syn_cons2(derivation, tb))) return YES; } else { if (is_purevirtual(l)) { List *d; for (d = derivation; d != 0; d = d->cdr) { Binder *b = findbinding(bindsym_(l), (TagBinder *)d->car, INCLASSONLY); if ((b != 0) && (b != l)) break; } if (d == 0) return YES; } } } return NO; } static void rd_classdecl(TagBinder *b) { ClassMember *vbase_members = NULL, *base_members = NULL; SET_BITMAP bitsinherit = 0; if (curlex.sym == s_colon) { nextsym(); if (typespecmap_(tagbindtype_(b)) & bitoftype_(s_union)) cc_rerr(syn_rerr_union_w_base); for (;;) { SET_BITMAP access = 0; bool is_virtual = 0; TypeExpr *pt = NULL; TagBinder *base_tag = 0; for (;;) { if (curlex.sym == s_virtual && !is_virtual) { is_virtual = 1; bitsinherit |= TB_HASVBASE; } else if (isaccessspec_(curlex.sym) && access == 0) /* [ES] has 'protected' allowed syntactically, but offers no meaning! */ access = bitofaccess_(curlex.sym); else break; nextsym(); } rd_cpp_name(0); if (curlex.sym != s_identifier) { cc_err(syn_err_missing_basetag); while (curlex.sym != s_lbrace && curlex.sym != s_comma) nextsym(); } else if (curlex_typename == 0 || (typespecmap_(pt=princtype(bindtype_(curlex_typename))) & (bitoftype_(s_struct)|bitoftype_(s_class))) == 0 || !(tagbindbits_(base_tag = typespectagbind_(pt)) & TB_DEFD)) { if (pt != NULL && h0_(pt) == t_unknown) { typespecmap_(pt) |= bitoftype_(s_class)|bitoftype_(s_struct); if (curlex_typename == NULL) syserr("base type $t", pt); binduses_(curlex_typename) |= u_referenced; } else if (base_tag && tagprimary_(base_tag) && (tagbindbits_(tagprimary_(base_tag)) & TB_DEFD) && !(tagbindbits_(base_tag) & TB_DEFD)) { syn_implicit_instantiate(tagprimary_(base_tag), base_tag); goto base_tag_member; } else { if (!base_tag) base_tag = mk_tagbinder(curlex.a1.sv, s_struct); cc_err(syn_err_undef_basetag, base_tag); } nextsym(); } else if (!(tagbindbits_(base_tag) & (TB_DEFD|TB_UNDEFMSG))) { cc_err(syn_err_undef_basetag, base_tag); tagbindbits_(base_tag) |= TB_UNDEFMSG; nextsym(); } else base_tag_member: { TypeExpr *t = core_type(base_tag); ClassMember *m; if (access == 0) { if (tagbindbits_(b) & bitoftype_(s_class)) { cc_warn(xsyn_warn_implicit_private_base, base_tag); access = bitofaccess_(s_private); } else access = bitofaccess_(s_public); } m = mk_member(base_tag, t, access | (is_virtual ? CB_VBASE : CB_BASE), b); vbase_members = append_vbases_of(base_tag, access|CB_VBASE, vbase_members); if (is_virtual) { vbase_members = append_no_dups(m, DONT_COPY, vbase_members); m = mk_member(base_tag, ptrtotype_(t), access|CB_VBPTR, b); } bitsinherit |= tagbindbits_(base_tag); base_members = nconc_member(base_members, m); nextsym(); } if (curlex.sym != s_comma) break; nextsym(); } } /* We presume an abstractly-based class is abstract until this is */ /* disproved. Is this right/moral? */ /* !!!! Not any more !!!! (29.6.94) FW */ /* Logic: inherit abstractness in class C:A { ... } but don't fault */ /* member/friend fns in '...' with C as arg/result until reach '}'. */ /* Also flag need vtable if vfn members (later) or any base needs one. */ tagbindbits_(b) |= bitsinherit & TB_HASVTABLE; checkfor_ket(s_lbrace); /* The organisation of a class is: */ /* base-member base-member... base-member member member ... member */ /* or core-member virtual-base virtual-base ... virtual-base */ /* where core-member contains: */ /* base-member base-member... base-member member member ... member. */ /* Note that the 2nd arg below has direct bases. It also has direct and */ /* INDIRECT virtual bases. Beware use for 'access-spec' in rd_strdecl. */ rd_strdecl(b, mk_core_part(b, base_members, vbase_members)); if (!(tagbindbits_(b) & TB_ABSTRACT) && chk_abstractness(b, (List *)syn_cons2(0, b))) tagbindbits_(b) |= TB_ABSTRACT; /* @@@ probably we wish to add a static vfntable here, but sadly the */ /* scope has been closed by rd_strdecl(). Think. */ /* @@@@@@@@@@@ not any more! */ #ifdef DEBUG_CLASS print_classdecl(base_members, 0); #endif } static void rd_access_adjuster(TagBinder *b, AEop access) { /* Assert: (curlex.sym == s_qualified+s_identifier || */ /* curlex.sym == s_qualified+s_pseudoid) */ /* && (curlex_typename != 0 || curlex_path != 0) */ /* && (peepsym() in {s_semicolon, s_comma, s_rbrace}) */ ClassMember *basemem; /* Access declarations must refer to a base class... */ /* @@@ but is it a direct or indirect base? */ if (curlex_scope == NULL || (basemem = derived_from(curlex_scope, b)) == NULL) cc_rerr(syn_rerr_not_base(curlex_scope, b)); /* Access declarations may only occur in a public or protected part... */ else if (access == s_private) cc_rerr(syn_rerr_badly_placed_access); /* Finally, an access declaration may not vary base access rights... */ else if (accessOK == 1) { if (attributes_(basemem) & bitofaccess_(s_public)) { /* publicly derived */ /* Warn of vacuously useless declarations and fault all others... */ if (attributes_(curlex_member) & bitofaccess_(access)) cc_warn(syn_warn_modify_access); else cc_rerr(syn_rerr_modify_access); } else { /* privately derived... */ /* Fault attempts to grant access greater or less than base access... */ if ((attributes_(curlex_member) & bitofaccess_(access)) == 0 && (access == s_protected || ((attributes_(curlex_member) & bitofaccess_(s_public)) == 0))) cc_rerr(syn_rerr_modify_access); else { Symstr *sv = memsv_(curlex_member); Binder *bm = findbinding(sv, b, INCLASSONLY); if (bm != NULL) cc_rerr(syn_rerr_duplicate_member(bm)); else { Binder *bm = findbinding(sv, b, INDERIVATION); TypeExpr *bmt = bindtype_(bm); BindList *l; DeclRhsList *d; if ((l = typeovldlist_(bmt)) != NULL) { bool done_once = NO; for (; l != NULL; l = l->bindlistcdr) { Binder *tmp = l->bindlistcar; if (attributes_(tmp) & bitofaccess_(s_public) || attributes_(tmp) & bitofaccess_(s_protected)) { if (!done_once) { d = mkDeclRhsList(sv, ACCESSADJ, stgaccof_(access)|bindstg_(tmp)); (void) instate_member(d, bind_scope); done_once = YES; } } else cc_rerr(syn_rerr_private_bmember_ignored); } } else { d = mkDeclRhsList(sv, curlex_typename ? memtype_(curlex_typename) : type_(curlex_path), stgaccof_(access)); (void) instate_member(d, bind_scope); } } } } } nextsym(); checkfor_ket(s_semicolon); } static TagBinder *firstbaseclass(TagBinder *cl) { ClassMember *p; ClassMemo memo; /* Beware: the following code doesn't always give the FIRST base class */ /* in that it prefers non-virtual bases. Since it only exists to patch */ /* up an anachronism (where only ONE base was allowed) I don't care. */ forClassMember(p, tagbindmems_(cl), &memo) if (attributes_(p) & (CB_BASE|CB_VBASE)) { TypeExpr *t = memtype_(p); if (isclasstype_(t)) return typespectagbind_(t); syserr("firstbaseclass $t", t); } return 0; } #define NOARGS ((SET_BITMAP)1) static Expr *nonconst_thislv(Expr *thislv, TypeExpr *lvt); /* find a default cctor, dtor, copy constructor or operator=() */ static Binder *default_structor(Symstr *sv, TagBinder *cl, SET_BITMAP flags) { Binder *bgeneric = findbinding(sv, cl, INCLASSONLY); Binder *bimpl = 0; if (bgeneric) { TypeExpr *tt = bindtype_(bgeneric); /* t_ovld */ Binder *b; Expr *thisptr; ExprList *l, *ll; /* if cl is a core class TagBinder then use the real class... */ if (tagbindbits_(cl) & TB_CORE) cl = cl->tagparent; b = gentempbinder(tagbindtype_(cl)); thisptr = mk_expr1(s_addrof, ptrtotype_(tagbindtype_(cl)), (Expr *)b); if (flags == NOARGS) { l = NULL; ll = mkExprList(l, thisptr); } else { Expr *nextarg = nonconst_thislv((Expr *)b, tagbindtype_(cl)); l = mkExprList1(nextarg); ll = mkExprList(l, thisptr); } if ((bimpl = ovld_resolve(bgeneric, typeovldlist_(tt), l, ll, YES)) != NULL) { Binder *bspecific = bimpl; bimpl = (h0_(bimpl) == s_error) ? NULL : realbinder_(bimpl); if ((bimpl != NULL) && (bindstg_(bimpl) & b_undef) && !contains_typevars(bindtype_(bimpl))) syn_attempt_template_memfn(bgeneric, bspecific); } } return bimpl; } typedef struct MemInitList { struct MemInitList *micdr; ClassMember *mimem; ExprList *miargs; } MemInitList; #define mkMemInit(x,y,z) ((MemInitList *)syn_list3(x,y,z)) /* MemInitLists are built in declaration order, for convenient use later */ static MemInitList *addmeminit(MemInitList *mi, Symstr *sv, ExprList *init, TagBinder *cl) { TagBinder *core; ClassMember *p; MemInitList *mip = mi, *miq = 0; /* What should we do with "class B:A { int A; };"? Fault earlier by */ /* making A's clash? Currently first look for virtual base A, then */ /* member A, then base A. */ p = tagbindmems_(cl); if (p != 0 && (attributes_(p) & CB_CORE)) { core = typespectagbind_(memtype_(p)); for (p = memcdr_(p); p != 0; p = memcdr_(p)) { TypeExpr *t = memtype_(p); if (!isclasstype_(t)) syserr("addmeminit"); if (sv == bindsym_(typespectagbind_(t))) goto found; if (mip && p == mip->mimem) mip = (miq = mip)->micdr; } } else core = cl; for (p = tagbindmems_(core); p != 0; p = memcdr_(p)) { if (h0_(p) != s_member) continue; if (sv == memsv_(p)) goto found; if (attributes_(p) & CB_BASE) { TypeExpr *t = memtype_(p); TagBinder *cla; if (!isclasstype_(t)) syserr("addmeminit"); cla = typespectagbind_(t); if (sv == bindsym_(cla) || (tagbindbits_(cla) & TB_CORE) && sv == bindsym_(cla->tagparent)) goto found; } if (mip && p == mip->mimem) mip = (miq = mip)->micdr; } cc_err(syn_err_no_named_member, cl, sv); return mi; found: if (debugging(DEBUG_SYN)) cc_msg("addmeminit($r)\n", sv); if (mip && p == mip->mimem) cc_err(syn_err_duplicated_mem_init, memsv_(p)); else { /* Insert the new initialiser in declaration order. */ /* @@@ Beware the thisify syserr()s for static members &c &c */ mip = mkMemInit(mip, p, init); if (miq == 0) mi = mip; else miq->micdr = mip; } return mi; } static Expr *nonconst_thislv(Expr *thislv, TypeExpr *lvt) { return mkunary(s_content, mkcast(s_cast, mkunary(s_addrof, thislv), ptrtotype_(lvt))); } static Expr *mkspecialfnap(Binder *b, Expr *thislv, ExprList *args, bool corefn) { if (b == 0) return 0; else if (corefn && realbinder_(b) != 0) { /* call core_function(args)... */ Expr *thisp = (h0_(thislv) == s_dot) ? arg1_(thislv) : mkunary(s_addrof, thislv); return mkfnap((Expr *)realbinder_(b), mkExprList(args, thisp)); } else /* exprdotmemfn(args)... */ return mkfnap( mk_exprwdot(s_qualdot, bindtype_(b), thislv, (IPtr)b), args); } static const char* structor_string(const Symstr *structorsv) { return structorsv == ctorsym ? msg_lookup(xsyn_constructor_string) : structorsv == dtorsym ? msg_lookup(xsyn_destructor_string) : structorsv == assignsym ? msg_lookup(xsyn_copy_assign_string) : symname_(structorsv); } /* called for (default?) ctors and dtors ('structors) only... */ static Expr *structor_expr(Symstr *structorsv, Binder *thisb, ClassMember *p) { TypeExpr *t = memtype_(p); TypeExpr *pt = princtype(t); Expr *e = 0; int32 nelts = 0; ExprList *args = 0; if (h0_(pt) == t_subscript) nelts = arraysize(pt, &pt); if (isclasstype_(pt)) { TagBinder *cla = typespectagbind_(pt); bool is_dtor = structorsv == dtorsym; if (structorsv == ctorsym && (tagbindbits_(cla) & TB_NEEDSCTOR) || is_dtor && (tagbindbits_(cla) & TB_HASDTOR)) { /* call the default ctor/dtor if the member is of a class */ /* type which isn't Plain Ol' Data. Call the core function */ /* if the member is a base or a vbase. */ Expr *thislv = mkfieldselector(s_arrow, (Expr *)thisb, p); binduses_(thisb) |= u_referenced; if (nelts == 0) { if (is_dtor) args = mkExprList1(lit_zero); e = mkspecialfnap(default_structor(structorsv, cla, NOARGS), nonconst_thislv(thislv, tagbindtype_(cla)), args, (attributes_(p) & (CB_BASE|CB_VBASE)) != 0); } else { int32 size = sizeoftype(pt); thislv = nonconst_thislv(thislv, tagbindtype_(cla)); thislv = mkcast(s_cast, mkunary(s_addrof, thislv), te_voidptr); e = array_of_class_map( thislv, nelts, size, structorsv != dtorsym, mkunary(s_addrof, (Expr *)default_structor(structorsv, cla, NOARGS)), structorsv == dtorsym); } if (e == 0) cc_warn(syn_warn_no_default_structor, p, cla, structor_string(structorsv)); } } else if (structorsv == ctorsym) { if (h0_(pt) == t_ref) cc_rerr(syn_rerr_ref_not_initialised, p); else if (qualifiersoftype(t) & bitoftype_(s_const)) cc_rerr(syn_rerr_const_not_initialised, p); } return e; } static Expr *meminit_expr(TagBinder *ctorcl, Binder *thisb, MemInitList **mip) { Expr *e = 0; ClassMember *p; MemInitList *mi = (mip == 0) ? 0 : *mip; /* Pass in 'thisb' rather than thisify() in deference to compiler- */ /* generated fns which don't set up a local scope containing 'this' */ /* Other ctors <always> have a ___this, so it's safe and convenient.*/ /* 'srcb' is used only by copy ctors... */ for (p = tagbindmems_(ctorcl); p != 0; p = memcdr_(p)) { if (h0_(p) != s_member || (attributes_(p) & CB_CORE)) continue; /* i.e. not for memfns, static members or typedefs. */ /* NB. mi is built in declaration order so use is simple... */ if (mi != 0 && mi->mimem == p) { Expr *thislv = mkfieldselector(s_arrow, (Expr *)thisb, p); TypeExpr *pt = princtype(type_(thislv)); TagBinder *cla = isclasstype_(pt) ? typespectagbind_(pt) : 0; Expr *ee = 0; binduses_(thisb) |= u_referenced; if (cla != 0) ee = mkopap(s_init, cla, thislv, mi->miargs); if (ee == 0) { if (mi->miargs != 0) ee = mkbinary(s_init, thislv, exprcar_(mi->miargs)); if (mi->miargs == 0 || mi->miargs->cdr != 0) cc_rerr(syn_rerr_meminit_wrong_args, p); } *mip = (mi = mi->micdr); e = commacons(e, ee); } else e = commacons(e, structor_expr(ctorsym, thisb, p)); } return e; } static Cmd *alloc_cmd(TagBinder *cl, Binder *thisb) { Binder *newb = syn_binderofname(cppsim.xnew, cl); TypeExpr *bt; if (newb == 0) { syserr("alloc_cmd 1, $b", newb); return 0; } if (h0_(bt = bindtype_(newb)) != t_ovld) syserr("alloc_cmd 1, $b", newb); if (bindparent_(newb) != 0) { BindList *bl; Binder *newspecific = 0; /* find T::operator new(size_t) if there is one */ for (bl = typeovldlist_(bt); bl != 0; bl = bl->bindlistcdr) { FormTypeList *f; bt = princtype(bindtype_(bl->bindlistcar)); if (h0_(bt) != t_fnap) syserr("alloc_cmd 2 $b?", bl->bindlistcar); f = typefnargs_(bt); if (f != NULL && f->ftcdr == NULL && equivtype(f->fttype, te_size_t)) { newspecific = bl->bindlistcar; break; } } if (newspecific == 0) return 0; else newb = newspecific; } /* 'if (this == 0) { this = operator new(sizeof(T)); if (this == 0) return this; }' */ /* Note that 'new' prefers class to global scope whereas, mkopap() */ /* may choose from either. */ /* We use s_init to allow initting this which is a const T* */ /* /* intzero (and intone) are used enough to move them to builtin */ { Expr *testthis = optimise0(mkbinary(s_equalequal, (Expr*)thisb, lit_zero)); TypeExpr *t = tagbindtype_(cl); Expr *e = mkcast(s_cast, mkfnap((Expr*)newb, mkExprList1(mkintconst(te_size_t, sizeoftype(t), 0))), ptrtotype_(t)); Cmd *init = mk_cmd_e(s_semicolon, syn_invented_fl, optimise0(mkbinary(s_init, (Expr*)thisb, e))); return mk_cmd_block(syn_invented_fl, 0, mkCmdList(0, mk_cmd_if(syn_invented_fl, testthis, mk_cmd_block(syn_invented_fl, 0, mkCmdList( mkCmdList(0, mk_cmd_if(syn_invented_fl, testthis, mk_cmd_e(s_return, syn_invented_fl, (Expr*)thisb), 0)), init)), 0))); } } #define CTOR_DEFAULT 1 #define DTOR_DEFAULT 2 #define CTOR_COPY 4 #define OP_ASSIGN 8 #define HAS_CORE 16 #define IN_CORE 32 static void generate_fn_body(TagBinder *cl, int sort, Binder *fnbinder, SynBindList *argbinders, MemInitList **mip); static Cmd *meminit_cmd(TagBinder *ctorclass, Binder *ctor, SynBindList *argbinders, MemInitList *mi, Cmd **alloc) { Binder *thisb = argbinders->bindlistcar; TagBinder *coreclass = core_class(ctorclass); Expr *e = 0; if (coreclass != ctorclass) /* Split the function into a top-level part and a core part. We need to */ /* clone the argbinders, re-writing their types appropriately. */ { SynBindList *a; SynBindList *blp = 0, *blq = 0; for (a = argbinders; a != 0; a = a->bindlistcdr) { Binder *b = a->bindlistcar; TypeExpr *t = bindtype_(b); SynBindList *bla; if (isclasstype_(princtype(t))) { Binder *ob = b; bindtype_(ob) = mk_typeexpr1(t_ref, t, 0); b = mk_binder(bindsym_(b), bitofstg_(s_auto), t); } bla = (SynBindList *) syn_list3(0, b, 0); if (blp == 0) blq = (blp = bla); else blq = (blq->bindlistcdr = bla); } /* binders in argbinders have been re-typed - class T -> T&. */ generate_fn_body(ctorclass, CTOR_DEFAULT|HAS_CORE, ctor, blp, &mi); } else *alloc = alloc_cmd(ctorclass, thisb); e = commacons(e, meminit_expr(coreclass, thisb, &mi)); if (mi != 0) syserr("meminit_cmd"); if (coreclass == ctorclass && tagbindbits_(ctorclass) & TB_HASVTABLE) { Expr *thislv = mk_expr1(s_content, typearg_(bindtype_(thisb)), (Expr *)thisb); e = commacons(e, vtab_init(ctorclass, thislv)); } { FileLine fl; SynBindList *bl; fl = curlex.fl; fl.p = dbg_notefileline(fl); add_expr_dtors(killexprtemp()); bl = pop_saved_temps(NULL); if (expr_dtors != NULL) { e = commacons(e, expr_dtors); e = mk_exprlet(s_let, te_void, bl, e); expr_dtors = NULL; extra_flags = NULL; } return e == 0 ? 0 : mk_cmd_e(s_semicolon, fl, optimise0(mkcast(s_semicolon, e, te_void))); } } static Cmd *rd_meminit(TagBinder *ctorclass, Binder *ctor, SynBindList *argbinders, Cmd **pre, Cmd **post) { MemInitList *mi = 0; *pre = *post = 0; if (strncmp(symname_(bindsym_(ctor)), "__ct", 4) != 0) ctorclass = 0; if (ctorclass == 0) { if (curlex.sym == s_colon) cc_err(syn_err_init_not_in_ctor); else return 0; } push_saved_temps(synscopeid); /* popped in meminit_cmd */ push_exprtemp_scope(); /* Here we read the meminit list even if not a ctor, for error recovery */ if (curlex.sym == s_colon) { for (;;) { Symstr *sv = 0; ExprList *init; nextsym(); rd_cpp_name(0); switch (curlex.sym) { case s_lpar: if (ctorclass) { TagBinder *b = firstbaseclass(ctorclass); if (b != 0) sv = bindsym_(b), cc_warn(syn_warn_insert_sym_anachronism, sv); else cc_err(syn_err_lacks_bclass_anachronism, ctorclass); } break; case s_identifier: /* s_qualified? */ sv = 0; if (ctorclass != 0) { TypeExpr *pt; if (curlex_typename != 0 && (typespecmap_(pt=princtype(bindtype_(curlex_typename))) & (bitoftype_(s_struct)|bitoftype_(s_class))) != 0) /* basename case... */ { if (istypevar(pt)) { pop_exprtemp_scope(); (void)pop_saved_temps(NULL); return 0; } sv = tagbindsym_(typespectagbind_(pt)); } else /* data-member-name case ... */ sv = curlex.a1.sv; } nextsym(); break; default: cc_err(syn_err_expected_id_in_mem_init); while (!(curlex.sym == s_lbrace || curlex.sym == s_eof)) nextsym(); pop_exprtemp_scope(); (void)pop_saved_temps(NULL); return 0; } checkfor_ket(s_lpar); init = rd_exprlist_opt(); if (sv) mi = addmeminit(mi, sv, init, ctorclass); if (curlex.sym == s_nothing) nextsym(); if (curlex.sym != s_comma) break; } } if (ctorclass == 0) /* not a constructor meminit list */ { pop_exprtemp_scope(); (void)pop_saved_temps(NULL); return 0; } *post = mk_cmd_e(s_return, syn_invented_fl, (Expr*) argbinders->bindlistcar /* thisb */); return meminit_cmd(ctorclass, ctor, argbinders, mi, pre); } static Expr *memdtor_expr(TagBinder *dtorclass, Binder *thisb) { Expr *e = 0; ClassMember *p; for (p = tagbindmems_(dtorclass); p != 0; p = memcdr_(p)) if (h0_(p) == s_member && !(attributes_(p) & CB_CORE)) /* NB: cons in REVERSE order - last constructed is first destroyed... */ e = commacons(structor_expr(dtorsym, thisb, p), e); return e; } static Expr *syn_memdtor(TagBinder *dtorclass, Binder *dtor, SynBindList *formals, Cmd **pre) { Binder *thisb = formals->bindlistcar; TagBinder *coreclass = core_class(dtorclass); if (tagbindbits_(dtorclass) & TB_HASVTABLE) { Expr *thislv = mk_expr1(s_content, typearg_(bindtype_(thisb)), (Expr *)thisb); /* this is only really needed if the body has any function calls in it */ *pre = mk_cmd_e(s_semicolon, syn_invented_fl, optimise0(vtab_init(dtorclass, thislv))); } else *pre = 0; /* NB: cons in REVERSE order - last constructed is first destroyed... */ if (coreclass != dtorclass) generate_fn_body(dtorclass, DTOR_DEFAULT|HAS_CORE, dtor, (SynBindList *) syn_list3( syn_list3(0, formals->bindlistcdr->bindlistcar, 0), thisb, 0), 0); return memdtor_expr(coreclass, thisb); } /* Given the type of a vbase, this fn locates a pointer to it. NB there */ /* is exactly one vbase of a given type in a derivation, so any pointer */ /* to it suffices. */ static Expr *vbaserv_1(TagBinder *core, Binder *srcb, TagBinder *vbase) { ClassMember *p; Expr *e; for (p = tagbindmems_(core); p != 0; p = memcdr_(p)) { if (h0_(p) != s_member) continue; if ((attributes_(p) & CB_VBPTR) && typespectagbind_(typearg_(memtype_(p))) == vbase) return mkunary(s_content, mkfieldselector(s_dot, (Expr *)srcb, p)); else if ((attributes_(p) & CB_BASE) && (e=vbaserv_1(typespectagbind_(memtype_(p)), srcb, vbase)) !=0) return e; } return 0; } static Expr *vbaserv(TagBinder *core, Binder *srcb, TagBinder *vbase) { Expr *e = vbaserv_1(core, srcb,vbase); if (e) return e; syserr("copy_expr/vbaserv"); return errornode; } static Expr *pod_copy(Expr *to, Expr *fm, int32 len, TypeExpr *t) { if (len == 0) return 0; to = mk_expr1(s_addrof, ptrtotype_(t), to); fm = mk_expr1(s_addrof, ptrtotype_(t), fm); if (t == te_int && len == sizeof_int) return mkbinary(s_assign, mkunary(s_content, to), mkunary(s_content, fm)); return mk_expr2(s_fnap, t, sim.realmemcpyfn, (Expr *)mkExprList( mkExprList(mkExprList1(mkintconst(te_int, len, 0)), fm), to)); } /* sv == assignsym (for operator=()) or sv == ctorsym (for copy ctors) */ static Expr *copy_expr(TagBinder *cl, Symstr *sv, Binder *thisb, Binder *srcb) { Expr *e = 0; ClassMember *p; TagBinder *core = core_class(cl); Expr *fromlv = 0, *fromrv = 0; int32 pod_len = 0; TypeExpr *pod_type = 0; bool is_assign = sv == assignsym; SET_BITMAP needstest = is_assign ? TB_NEEDSOPEQ : TB_NEEDSCCTOR; for (p = tagbindmems_(cl); p != 0; p = memcdr_(p)) { if (h0_(p) == s_member && !(attributes_(p) & (CB_CORE|CB_VBPTR|CB_VTAB))) { Expr *thislv = mkfieldselector(s_arrow, (Expr *)thisb, p); TypeExpr *pt = princtype(memtype_(p)); TagBinder *cla = typespectagbind_(pt); Expr *thisrv, *ee; if (attributes_(p) & CB_VBASE) /* If copying to a vbase, the source expression must indirect via an */ /* appropriate vbptr, as the source object need not be 'most derived'. */ { e = commacons(e, pod_copy(fromlv, fromrv, pod_len, pod_type)); pod_len = 0; thisrv = vbaserv(core, srcb, cla); } else thisrv = mkfieldselector(s_dot, (Expr *)srcb, p); if (pod_len == 0) { fromlv = thislv; fromrv = thisrv; if ((arg2i_(fromlv) % alignof_int) == 0) pod_type = te_int; else pod_type = te_char; } if (is_assign && (qualifiersoftype(memtype_(p)) & bitoftype_(s_const))) cc_rerr(sem_rerr_assign_const, p); if (isclasstype_(pt) && tagbindbits_(cla) & needstest) { ee = mkspecialfnap( default_structor(sv, cla, qualifiersoftype(memtype_(p)) & bitoftype_(s_const)), nonconst_thislv(thislv, tagbindtype_(cla)), mkExprList1(thisrv), (attributes_(p) & (CB_BASE|CB_VBASE)) != 0); if (ee == 0) cc_warn(syn_warn_no_default_structor, p, cla, structor_string(sv)); /* 'recover' by treating as POD... for now... */ else { e = commacons(e, pod_copy(fromlv, fromrv, pod_len, pod_type)); pod_len = 0; e = commacons(e, ee); continue; } } else if (h0_(pt) == t_subscript) { /* array of foo... */ TypeExpr *et = pt; int32 nelts = arraysize(pt, &et); if (isclasstype_(et) && (cla = typespectagbind_(et), tagbindbits_(cla) & needstest)) { SET_BITMAP constness = qualifiersoftype(memtype_(p)) & bitoftype_(s_const); Expr* limit = /* '(char*)(&thisrv) + nelts * sizeoftype(et)' */ mkbinary(s_plus, mkcast(s_cast, mkunary(s_addrof, thisrv), te_charptr), mkintconst(te_size_t, nelts * sizeoftype(et), 0)); ee = array_of_class_copy(thislv, thisrv, limit, sizeoftype(et), default_structor(sv, cla, constness)); if (ee == 0) cc_warn(syn_warn_no_default_structor, p, cla, structor_string(sv)); /* 'recover' by treating as POD... for now. */ else { e = commacons(e, pod_copy(fromlv, fromrv, pod_len, pod_type)); pod_len = 0; e = commacons(e, ee); } continue; } } pod_len = arg2i_(thislv) - arg2i_(fromlv); if (isbitfield_type(pt)) pt = unbitfield_type(pt); if (!(attributes_(p) & CB_BASE && isclasstype_(pt) && tagbindmems_(typespectagbind_(pt)) == 0)) /* NOT empty base class... */ pod_len += sizeoftype(pt); } } e = commacons(e, pod_copy(fromlv, fromrv, pod_len, pod_type)); return e; } /* cpp_end_strdecl() is called at the end of adding members to (the */ /* core of) a class (bind.c::insertionpoint() knows to add members to */ /* the core of a class if it has a CB_CORE member). cpp_end_strdecl() */ /* accumulates information about the class, initialises its vtable if */ /* it has one and adds decls of a default ctor, dtor, copy ctor and */ /* operator= if any of these are needed. The info accumulated is: */ /* - TB_NOTPOD - an attribute_() of the class TagBinder (meaning not */ /* Plain Ol' Data) set if: */ /* - any base or member is NOTPOD; */ /* - there is any ctor or dtor declared; */ /* - there are any virtual bases or virtual function tables. */ /* Jan-1995 TB_NOTPOD is no longer an attribute bit, see defs.h */ /* - CB_CGEN - an attribute_() of realbinders for ctors, dtors and */ /* operator= memers - which indicates that part of the function */ /* definition is compiler-generated. */ /* - TB_HASVTABLE - a TagBinder attribute_() if the class has a */ /* vtable member. */ /* - TB_HASDTOR - a TagBinder attribute_() set if any base has a dtor */ /* or a dtor is declared in this class. */ static void inherit_tagbindbits(TagBinder *b) { ClassMember *m; ClassMemo memo; forClassMember(m, tagbindmems_(b), &memo) { TagBinder *mb = 0; if (h0_(m) != s_member) continue; if (qualifiersoftype(memtype_(m)) & bitoftype_(s_const)) tagbindbits_(b) |= TB_HASCMEM; if (attributes_(m) & (CB_BASE|CB_VBASE)) { mb = typespectagbind_(memtype_(m)); if (attributes_(m) & CB_VBASE) tagbindbits_(b) |= TB_HASVBASE; } else if (attributes_(m) & CB_VTAB) { int32 sz = base_vtable_sz(b); memtype_(m) = globalize_typeexpr( ptrtotype_(mk_typeexpr1(t_subscript, te_ulint, mkintconst(te_int, sz, 0)))); tagbindbits_(b) |= TB_HASVTABLE; } else { TypeExpr *pt = princtype(memtype_(m)); (void)isarraytype(pt, &pt); if (isclasstype_(pt)) mb = typespectagbind_(pt); } if (mb != 0) { tagbindbits_(b) |= (tagbindbits_(mb) & TB_HASDTOR); tagbindbits_(b) &= (tagbindbits_(mb) | ~(TB_HASCONSTCCTOR|TB_HASCONSTOPEQ)); tagbindbits_(b) |= (tagbindbits_(mb) & (TB_NEEDSCCTOR|TB_NEEDSOPEQ|TB_NEEDSCTOR|TB_HASCMEM)); } } } void syn_note_generated_fn(TopDecl *d) { syn_generatedfns = (GenFnList *) syn_list3(syn_generatedfns, d, 0); /* The following protects the function definition until later unmark()'d */ /* by syn.c::rd_topdecl(). This avoids spurious globalization and deals */ /* naturally with compiler-generated fns in nested classes. */ syn_generatedfns->mark = alloc_mark(); } static void generate_fn_body(TagBinder *cl, int sort, Binder *fnbinder, SynBindList *argbinders, MemInitList **mip) { CmdList *cmds = 0; Expr *e = 0, *vtabinit = 0; /* Assert: argbinders is non-empty and has >=2 elements for OP_ASSIGN */ Binder *thisb = argbinders->bindlistcar; Binder *srcb = (argbinders->bindlistcdr == 0) ? 0 : argbinders->bindlistcdr->bindlistcar; if (var_cc_private_flags & 0x200000) cc_msg("generating $b in $c\n", fnbinder, cl); if (sort & (CTOR_DEFAULT|CTOR_COPY)) { if (!(sort & IN_CORE)) { Expr *thislv = 0; Cmd *alloc = alloc_cmd(cl, thisb); if (alloc) cmds = mkCmdList(cmds, alloc); if ((sort & HAS_CORE) || (tagbindbits_(cl) & TB_HASVTABLE)) { thislv = mk_expr1(s_content, typearg_(bindtype_(thisb)), (Expr *)thisb); } if (tagbindbits_(cl) & TB_HASVTABLE) vtabinit = vtab_init(cl, thislv); /* save up for later */ if (sort & HAS_CORE) e = vbase_init(cl, thislv); /* init vbase pointers */ } if (sort & CTOR_DEFAULT) e = commacons(e, meminit_expr(cl, thisb, mip)); else /* CTOR_COPY */ e = commacons(e, copy_expr(cl, ctorsym, thisb, srcb)); } else if (sort & OP_ASSIGN) e = copy_expr(cl, assignsym, thisb, srcb); if ((sort & HAS_CORE) && !(sort & IN_CORE)) /* call the core function of this sort... */ { TypeExpr *fntype = bindtype_(fnbinder); FormTypeList *ft; SynBindList *a = argbinders; ExprList *l = 0; for (ft = typefnargs_(fntype); ft != 0 && a != 0; ft = ft->ftcdr) { TypeExpr *t = princtype(ft->fttype); Expr *e = (Expr *)(a->bindlistcar); if (h0_(t) == t_ref) e = mk_expr1(s_content, typearg_(t), e); l = mkExprList(l, e); /* /* core dtors really only need one argument */ if (sort & DTOR_DEFAULT) { l = mkExprList(l, lit_zero); break; } a = a->bindlistcdr; } /* /* for op= and ctors it would be nice if this were a tail call */ /* when possible (always?) */ e = commacons(e, mkfnap((Expr *)realbinder_(fnbinder), dreverse(l))); } /* vtabinit != 0 iff: (sort & (CTOR_DEFAULT|CTOR_COPY)) && */ /* !(sort & IN_CORE) && */ /* (tagbindbits_(cl) & TB_HASVTABLE)) */ e = commacons(e, vtabinit); if (sort & DTOR_DEFAULT) e = commacons(e, memdtor_expr(cl, thisb)); if (e) { cmds = mkCmdList(cmds, mk_cmd_e(s_semicolon, curlex.fl, optimise0(mkcast(s_semicolon, e, te_void)))); } if (sort & OP_ASSIGN) { TypeExpr *restype = typearg_(bindtype_(fnbinder)); e = optimise0(mkcast(s_cast, mkunary(s_content, (Expr *)thisb), restype)); cmds = mkCmdList(cmds, mk_cmd_e(s_return, curlex.fl, e)); } else if (sort & (CTOR_DEFAULT|CTOR_COPY)) cmds = mkCmdList(cmds, mk_cmd_e(s_return, curlex.fl, (Expr*)thisb)); else if ((sort & DTOR_DEFAULT) && !(sort & IN_CORE)) cmds = mkCmdList(cmds, conditionalised_delete(thisb, srcb, cl)); syn_note_generated_fn(mkTopDeclFnDef(s_fndef, fnbinder, argbinders, mk_cmd_block(curlex.fl, 0, (CmdList *)dreverse((List *)cmds)), 0)); } static void mk_generated_fn(TagBinder *cl, int sort, Binder *fnbinder) { TypeExpr *fnrtype = bindtype_(fnbinder); FormTypeList *ft = typefnargs_(fnrtype); SynBindList *argbinders = 0; Binder *thisb = mk_binder(ft->ftname, bitofstg_(s_auto), ft->fttype); binduses_(thisb) |= u_referenced; if ((ft = ft->ftcdr) != 0) { Symstr *argsym = (sort & DTOR_DEFAULT) ? deletesym : sym_insert_id("__src"); Binder *srcb = mk_binder(argsym, bitofstg_(s_auto), ft->fttype); argbinders = (SynBindList *) syn_list3(0, srcb, 0); } argbinders = (SynBindList *) syn_list3(argbinders, thisb, 0); generate_fn_body(cl, sort, fnbinder, argbinders, 0); } #define declsort_(d) ((d)->u.stgval) static DeclRhsList *generate_fndecl(DeclRhsList *dl, TagBinder *cl, int sort) { TypeExprFnAux s, *fnaux; TypeExpr *fnrtype = te_void, *argt = 0; DeclRhsList *d; Binder *bspecific; FormTypeList *fnargs = 0; Symstr *sv; switch (sort) { case CTOR_DEFAULT: fnaux = packTypeExprFnAux(s, 0, 0, 0, 0, 0); fnrtype = ptrtotype_(tagbindtype_(cl)); sv = ctorsym; break; case DTOR_DEFAULT: fnaux = packTypeExprFnAux(s, 0, 0, 0, 0, 0); sv = dtorsym; break; case CTOR_COPY: argt = mk_typeexpr1(t_ref, mkqualifiedtype(tagbindtype_(cl), tagbindbits_(cl) & TB_HASCONSTCCTOR ? bitoftype_(s_const) : 0), 0); fnaux = packTypeExprFnAux(s, 1, 1, 0, 0, 0); fnrtype = ptrtotype_(tagbindtype_(cl)); sv = ctorsym; break; case OP_ASSIGN: argt = mk_typeexpr1(t_ref, mkqualifiedtype(tagbindtype_(cl), tagbindbits_(cl) & TB_HASCONSTOPEQ ? bitoftype_(s_const) : 0), 0); fnrtype = mk_typeexpr1(t_ref, tagbindtype_(cl), 0); fnaux = packTypeExprFnAux(s, 1, 1, 0, 0, 0); sv = assignsym; break; default: syserr("generate_fndecl(%d)", sort); return dl; } if (argt != 0) fnargs = mkFormTypeList(0, 0, argt, 0); d = mkDeclRhsList(sv, mkTypeExprfn(t_fnap, fnrtype, 0, fnargs, fnaux), b_generated | stgaccof_(s_public) | bitofstg_(s_inline) | b_fnconst); bspecific = instate_member(d, bind_scope); attributes_(bspecific) |= CB_CGEN; binduses_(bspecific) |= u_referenced; bspecific = realbinder_(bspecific); bindstg_(bspecific) &= ~b_undef; attributes_(bspecific) |= CB_CGEN; d->declbind = bspecific; d->declcdr = dl; declsort_(d) = sort; return d; } static void generate_fndef(DeclRhsList *d, TagBinder *cl) { int sort = (int)declsort_(d); Binder *bspecific = d->declbind; TagBinder *core = core_class(cl); if (tagbindbits_(cl) & TB_TEMPLATE) return; if (core != cl) sort |= HAS_CORE; mk_generated_fn(cl, sort, bspecific); if (sort & HAS_CORE) mk_generated_fn(core, sort|IN_CORE, realbinder_(bspecific)); } static void bind_function_default_arguments(Binder *bimpl) { TypeExpr *t2 = princtype(bindtype_(bimpl)); FormTypeList *f; Expr *init; for (f = typefnargs_(t2); f != 0; f = f->ftcdr) { SynBindList *bl = NULL; TypeExpr *t; if (f->ftdefault == 0 || exb_(arg2_(f->ftdefault)) != &deferred_default_arg_expr) continue; lex_openbody(evaluate(f->ftdefault), NO, NO, NULL, NULL); /* AM is now of the opinion that the following code (and similar code */ /* in mkfnap()) to widen_formaltype() is somewhat wrong-minded. */ /* It means that "void f(char); void g() { f(257); }" is treated */ /* differently from the similar "char x = 257". Maybe we should defer */ /* some of this code to cg.c. */ push_saved_temps(synscopeid); push_exprtemp_scope(); init = optimise0(mkcast(s_fnap, rd_expr(UPTOCOMMA), (t = widen_formaltype(f->fttype)))); add_expr_dtors(killexprtemp()); bl = pop_saved_temps(bl); if (init && bl) { init = (!expr_dtors) ? mk_exprlet(s_let, t, bl, init) : mk_exprlet(s_qualified|s_let, t, bl, commacons(init, expr_dtors)); expr_dtors = NULL; extra_flags = NULL; } /* Note that optimise0() on the next line means (1) the top-type may */ /* be incompatibly changed (so don't check it again) and moreover that */ /* (2) optimise0() will get called on it again. Hmm @@@. */ /* Add a special 'optimise0'd flag node? */ /* optimise0() maps errornode => NULL; moved above */ /* LDS: 12-Jul-94 - need to globalize here or disaster can ensue... */ f->ftdefault = (init) ? globalize_expr(init) : NULL; lex_closebody(); } } static void bind_default_arguments(TagBinder *cl) { ClassMember *m = tagbindmems_(cl); Friend *fr; if (m && attributes_(m) & CB_CORE) m = tagbindmems_(typespectagbind_(memtype_(m))); for (; m != 0; m = memcdr_(m)) { if (h0_(m) == s_binder) { TypeExpr *t = memtype_(m); BindList *bl; if (h0_(t) != t_ovld) continue; /* found a class member function */ for (bl = typeovldlist_(t); bl != 0; bl = bl->bindlistcdr) bind_function_default_arguments(realbinder_(bl->bindlistcar)); } } for (fr = cl->friends; fr != 0; fr = fr->friendcdr) if (h0_(fr->u.friendfn) == s_binder) bind_function_default_arguments(fr->u.friendfn); } /* /* should fault if any ref mems or const mems and no user ctor */ static void cpp_end_strdecl(TagBinder *cl) { Binder *mb; int has_user_copy_ctor = NO; /* until shown otherwise */ int has_user_const_copy_ctor = NO; /* until shown otherwise */ int has_user_ctor = NO; DeclRhsList *fndecl = 0; bind_default_arguments(cl); tagbindbits_(cl) |= TB_HASCONSTCCTOR|TB_HASCONSTOPEQ; /* until proven otherwise... */ inherit_tagbindbits(cl); if ((mb = findbinding(ctorsym, cl, INCLASSONLY)) != 0) /* There are constructors, so mark CB_CGEN and check for a copy ctor. */ { TypeExpr *t1 = memtype_(mb), *thistype = tagbindtype_(cl); BindList *bl; bool semantics_differ = YES; Binder* armb = NULL; if (h0_(t1) != t_ovld) syserr("odd ctor type in $c", cl); for (bl = bindftlist_(mb) ? bindftlist_(mb) : typeovldlist_(t1); bl != NULL; bl = bl->bindlistcdr) { Binder *bspecific = bl->bindlistcar; TypeExpr *t2 = princtype(bindtype_(bspecific)); FormTypeList *f = typefnargs_(t2); if (h0_(t2) != t_fnap) continue; /* @@@ what else could it be? */ /* A user-defined constructor nontheless has compiler-generated parts... */ attributes_(realbinder_(bspecific)) |= CB_CGEN; if (!has_user_ctor && (f == 0 || qualfree_equivtype(princtype(f->fttype), thistype) != 2)) has_user_ctor = YES; if ((!has_user_const_copy_ctor || semantics_differ) && f != NULL && minargs_(t2) <= 1) { /* at least one formal and any args from 2 up optional. */ TypeExpr *t3 = princtype(f->fttype); TypeExpr *t4 = h0_(t3) == t_ref ? typearg_(t3) : t3; const bool equiv = qualfree_equivtype(t4, thistype); const bool derived = type_derived_from(t4, thistype) != NULL; /* Here we check A.R.M. semantics as well as DRAFT semantics. In Cfront */ /* mode we implement A.R.M. semantics, otherwise we implement DRAFT */ /* semantics. We warn in either mode if the semantics differ. */ /* For "A.R.M." semantics we allow a copy constructor to take as formal */ /* argument an object of a class which is a base class of the class */ /* which the operator belongs. The A.R.M. is even more generous and */ /* allows any conversion. This is also done below for operator=. */ if (equiv || ((feature & FEATURE_CFRONT) && derived)) { if (h0_(t3) != t_ref) syserr("self-copying $c constructor", cl); has_user_copy_ctor = YES; if (equiv) semantics_differ = NO; else armb = bspecific; if (qualifiersoftype(t4) & bitoftype_(s_const)) has_user_const_copy_ctor = YES; } else if (derived) armb = bspecific; } } if (semantics_differ && armb) cc_warn((feature & FEATURE_CFRONT) ? xsyn_warn_ARM_cctor_suppress : xsyn_warn_ISO_cctor_no_suppress, armb); if (has_user_copy_ctor) { if (has_user_const_copy_ctor) tagbindbits_(cl) |= TB_HASCONSTCCTOR; else tagbindbits_(cl) &= ~TB_HASCONSTCCTOR; } } if (tagbindbits_(cl) & (TB_HASVTABLE|TB_HASVBASE)) tagbindbits_(cl) |= TB_NEEDSCTOR|TB_NEEDSCCTOR; else { if (has_user_ctor) tagbindbits_(cl) |= TB_NEEDSCTOR; if (has_user_copy_ctor) tagbindbits_(cl) |= TB_NEEDSCCTOR; } /* declare the default ctor if there is no suitable ctor and */ /* declare the default copy ctor if there isn't a copy ctor... */ if (mb == 0 && (tagbindbits_(cl) & TB_NEEDSCTOR)) fndecl = generate_fndecl(fndecl, cl, CTOR_DEFAULT); /* declare the default cctor if there isn't one in class */ if (!has_user_copy_ctor && (tagbindbits_(cl) & (TB_NEEDSCTOR|TB_NEEDSCCTOR))) fndecl = generate_fndecl(fndecl, cl, CTOR_COPY); { /* may need to declare a generated operator=()... */ BindList *bl; int has_user_op_assign = NO; /* until shown otherwise... */ int has_user_const_op_assign = NO; /* until shown otherwise... */ if ((mb = findbinding(assignsym, cl, INCLASSONLY)) != 0) { /* There are some assignment operators... */ TypeExpr *t1 = memtype_(mb); bool semantics_differ = YES; Binder* armb = NULL; if (h0_(t1) != t_ovld) syserr("odd operator=() type in $c", cl); for (bl = bindftlist_(mb) ? bindftlist_(mb) : typeovldlist_(t1); bl != NULL; bl = bl->bindlistcdr) { Binder *bspecific = bl->bindlistcar; TypeExpr *t2 = princtype(bindtype_(bspecific)); FormTypeList *f = typefnargs_(t2); /* NB. user-defined operator=() contain no compiler-generated parts so */ /* don't give the binder the CB_CGEN attribute: ctors/dtors only. */ if (h0_(t2) == t_fnap && f != NULL && minargs_(t2) <= 1) { /* > 0 formals and any arg from 2 up optional... */ TypeExpr *t3 = princtype(f->fttype); TypeExpr *t4 = h0_(t3) == t_ref ? typearg_(t3) : t3; const bool equiv = qualfree_equivtype(t4, tagbindtype_(cl)); const bool derived = type_derived_from(t4, tagbindtype_(cl)) != NULL; if (equiv || ((feature & FEATURE_CFRONT) && derived)) { has_user_op_assign = YES; if (equiv) semantics_differ = NO; else armb = bspecific; if (h0_(t3) != t_ref || (qualifiersoftype(t4) & bitoftype_(s_const))) { has_user_const_op_assign = YES; /* break if there's no point in scanning the rest */ if (!semantics_differ) break; } } else if (derived) armb = bspecific; } } if (semantics_differ && armb) cc_warn((feature & FEATURE_CFRONT) ? xsyn_warn_ARM_opeq_suppress : xsyn_warn_ISO_opeq_no_suppress, armb); if (has_user_op_assign) { if (has_user_const_op_assign) tagbindbits_(cl) |= TB_HASCONSTOPEQ; else tagbindbits_(cl) &= ~TB_HASCONSTOPEQ; } } /* TB_HASVTABLE is needed to force skipping of the vtable pointers */ if (tagbindbits_(cl) & (TB_HASVTABLE|TB_HASVBASE)) tagbindbits_(cl) |= TB_NEEDSOPEQ; else if (has_user_op_assign) tagbindbits_(cl) |= TB_NEEDSOPEQ; /* declare the default operator=() if there isn't one in class or one of its base class has one */ /* but make sure there is no const mem around ... */ if (!has_user_op_assign && (tagbindbits_(cl) & TB_NEEDSOPEQ) && !(tagbindbits_(cl) & TB_HASCMEM)) fndecl = generate_fndecl(fndecl, cl, OP_ASSIGN); } if ((mb = findbinding(dtorsym, cl, INCLASSONLY)) != 0) { TypeExpr *t1 = memtype_(mb); BindList *bl; if (h0_(t1) == t_ovld && (bl = (bindftlist_(mb) ? bindftlist_(mb) : typeovldlist_(t1)))->bindlistcdr == 0) /* This predicate can only fail as a result of previous diagnosed errors */ { attributes_(realbinder_(bl->bindlistcar)) |= CB_CGEN; tagbindbits_(cl) |= TB_HASDTOR; } } else if (tagbindbits_(cl) & TB_HASDTOR) fndecl = generate_fndecl(fndecl, cl, DTOR_DEFAULT); { TagBinder *core = core_class(cl); if (core != cl) tagbindbits_(core) |= tagbindbits_(cl) & (TB_HASDTOR | TB_HASCONSTCCTOR | TB_HASCONSTOPEQ | TB_NEEDSCTOR | TB_NEEDSCCTOR | TB_NEEDSOPEQ); } { TagBinder *core = core_class(cl); tagbindbits_(core) = (tagbindbits_(core) & ~TB_BEINGDEFD) | TB_DEFD; tagbindbits_(cl) = (tagbindbits_(cl) & ~TB_BEINGDEFD) | TB_DEFD; /* (perhaps redundantly. Another redundant setting of TB_DEFD is */ /* coming up in pop_scope, but is needed for C. */ } for (; fndecl != 0; fndecl = fndecl->declcdr) generate_fndef(fndecl, cl); } static ScopeSaver template_formals_filter(ScopeSaver popplings) { /* Lose the tagbinders, but they still hang around in global store */ ScopeSaver h, p = (popplings && h0_(popplings) != s_binder) ? bindcdr_(popplings) : popplings; h = p; for (; p != NULL; p = bindcdr_(p)) { ScopeSaver q = bindcdr_(p); if (q != NULL && h0_(q) != s_binder) bindcdr_(p) = bindcdr_(q); } return dreverse_binder(h); } /* Keep reasonably in step with scope actions with rd_formals(). */ static ScopeSaver rd_template_formals() { ScopeSaver popplings = NULL; if (curlex.sym == s_greater) /* no formal */; else { int scope_level = push_scope(0, Scope_TemplateArgs); for (;;) { DeclRhsList *temp = rd_decl2(TFORMAL, 0); if (curlex.sym == s_nothing) nextsym(); for (; temp != 0; temp = temp->declcdr) { if (debugging(DEBUG_TEMPLATE)) cc_msg("template-formal: $r\n", temp->declname); if (temp->declname == 0) temp->declname = gensymval(1); /* fixup to continue */ } if (curlex.sym == s_semicolon) /* error recovery */ cc_rerr(syn_rerr_semicolon_in_arglist); else if (curlex.sym != s_comma) break; nextsym(); } popplings = template_formals_filter(pop_scope_no_check(scope_level)); } checkfor_2ket(s_greater, s_comma); return popplings; } static Binder *find_typename(Symstr *sv, TagBinder *scope) { ExprList *p = (cur_template_actuals) ? *cur_template_actuals : NULL; Binder *b = NULL; for (; p != NULL; p = p->cdr) { Expr *e = exprcar_(p); if (e && isprimtype_(type_(e), s_typedefname) && bindsym_(typespecbind_(type_(e))) == sv && tagbindsym_(bindparent_(typespecbind_(type_(e)))) == tagbindsym_(scope)) return typespecbind_(type_(e)); } if (!scope || (b = findbinding(sv, scope, INCLASSONLY)) == NULL) b = findbinding(sv, NULL, ALLSCOPES); if (b) { if (!isprimtype_(bindtype_(b), s_typedefname) || !istypevar(bindtype_(b))) b = NULL; } return b; } static ExprList *rd_template_actuals(bool check) { ExprList *p = 0, *q = 0, *temp; TagBinder *old_curlex_scope = curlex_scope; Binder *old_curlex_binder = curlex_binder, *old_curlex_typename = curlex_typename; Expr *old_curlex_path = curlex_path; cur_template_actuals = &p; if (curlex.sym != s_greater) for (;;) { Expr *e; rd_cpp_name(&TAS); /* here we need to read a 't' or a 'e': generalise this routine. */ if (isdeclstarter2_(curlex)) { TypeExpr *t = rd_typename(TYPENAME); check_temp_type_arg_linkage(t); if (t != NULL) e = mk_expr1(s_typespec, t, 0); else e = errornode; } else { e = rd_expr(UPTORELOP); check_temp_arg_linkage(e); } /* The above line represents an ambiguity in [ES]. Page 345 gives a */ /* good example. Consider template-name<2*1>x... We can't determine */ /* from the read above whether '>' is greater-than or close-paren. */ /* Resolve by reading a 'shift-expression' not a general expression. */ if (h0_(e) != s_error) { temp = (ExprList *)syn_cons2(0, e); if (p == 0) p = q = temp; else cdr_(q) = temp, q = temp; } if (!check || curlex.sym != s_comma) break; nextsym(); } else if (curlex.sym == s_greater) p = (ExprList *)syn_cons2(0, 0); /* empty actuals */ if (check) checkfor_2ket(s_greater, s_comma); curlex_binder = old_curlex_binder; curlex_scope = old_curlex_scope; curlex_path = old_curlex_path; curlex_typename = old_curlex_typename; cur_template_actuals = NULL; return p; } static Handler *rd_handler() { Handler *p = 0, *q = 0, *temp; int ellipsis_yet = 0; if (curlex.sym == s_catch) while (curlex.sym == s_catch) { int scope_level = push_scope(0, Scope_Ord); SynBindList *b = 0; Cmd *c; TypeExpr* caught_type = 0; bool handler_arg = false; nextsym(); checkfor_ket(s_lpar); if (ellipsis_yet != 0) cc_err(sem_err_dotdotdot_handler_not_last); if (curlex.sym == s_ellipsis) {ellipsis_yet=1; nextsym();} else { DeclRhsList *d = rd_decl2(CATCHER, 0); /* should we default declname to a gensym? */ if (d && d->declname) { handler_arg = true; b = mkSynBindList(0, instate_declaration(d, CATCHER)); caught_type = b -> bindlistcar -> bindtype; } else caught_type = d -> decltype; /* there's no handler arg */ { Handler* pp = p; while (pp != 0) { if (0 == type_derived_from(caught_type, pp->caught_type)) cc_warn(xsem_warn_unreachable_handler), pp=0; else pp = pp -> handcdr; } } } checkfor_ket(s_rpar); c = rd_compound_statement(s_catch); /* do we wish to read with blk_BODY (c.f. fn args and local body scope? */ pop_scope(scope_level); temp = mkHandler(0, b, c, caught_type); if (p==0) p = q = temp; else q->handcdr = temp, q = temp; } else cc_err(syn_err_missing_catch_after_try); if (ellipsis_yet == 0) { /* if there is no ... case, add catch(...){throw;} */ Cmd* c = mkthrow(syn_invented_fl, 0); temp = mkHandler(0, (SynBindList*) 0, c, 0); if (p==0) p = q = temp; else q->handcdr = temp, q = temp; } return p; } static void add_pendingfn_0(PendingFnList **pp, Symstr *name, Symstr *realname, TypeExpr *t, SET_BITMAP stg, TagBinder *scope, ScopeSaver formaltags, int tokhandle, ScopeSaver templateformals, bool tfn) { PendingFnList *x, *p; while ((p = *pp) != NULL) pp = &p->pfcdr; x = (PendingFnList *)GlobAlloc(SU_Other, sizeof(*x)); x->pfcdr = NULL; x->pfname = name; x->pfrealname = realname; x->pftype = t; x->pfstg = stg; x->pfscope = scope; x->pf_formaltags = formaltags; x->pf_toklist_handle = tokhandle; x->pf_templateformals = templateformals; x->pf_tfn = tfn; *pp = x; } static void add_memfn_template(TagBinder *p, Symstr *name, Symstr *realname, TypeExpr *t, SET_BITMAP stg, TagBinder *scope, ScopeSaver formaltags, int tokhandle, ScopeSaver templateformals) { add_pendingfn_0((PendingFnList **)&tagmemfns_(p), name, realname, t, stg, scope, formaltags, tokhandle, templateformals, YES); } void add_pendingfn(Symstr *name, Symstr *realname, TypeExpr *t, SET_BITMAP stg, TagBinder *scope, ScopeSaver formaltags, int tokhandle, ScopeSaver templateformals, bool tfn) { bool parse_only = (scope && ((tagbindbits_(scope) & TB_TEMPLATE)) || has_template_parameter(templateformals)); if (tfn && !parse_only) { TopDecl *fd; DeclRhsList *d; int sl; int save_bind_scope = bind_scope; /* will be changed by rd_fndef */ TagBinder *old_access_context = set_access_context(NULL, NULL); SynBindList *old_syn_reftemps = syn_reftemps; FuncMisc tmp; Mark* mark; syn_reftemps = NULL; save_curfn_misc(&tmp); if (scope && tagactuals_(scope)) { /*if (!tagscope_(scope)) syserr("weird template $c", scope);*/ sl = push_var_scope(tagscope_(scope), Scope_TemplateDef); (void) push_var_scope(tagactuals_(scope), Scope_TemplateArgs); (void) push_var_scope(templateformals, Scope_TemplateArgs); } else sl = push_var_scope(templateformals, Scope_TemplateArgs); mark = alloc_mark(); cg_reinit(); /* If I'm cg'ing on the fly, I can be a bit more adventurous. A bitofstg_(s_inline) may help performance. But the function becomes static. Dump the function in a common code area? */ d = reinvent_fn_DeclRhsList(name, realname, t, stg); if (stg & b_memfna) memfn_typefix(d, scope); (void) set_access_context(scope, NULL); if (debugging(DEBUG_TEMPLATE)) cc_msg("template fn $r ...\n", realname != NULL ? realname : d->declname); push_nested_context(xsyn_info_instantiate_fn, (IPtr)scope, (IPtr)(realname != NULL ? realname : d->declname)); lex_openbody(tokhandle, tfn, NO, NULL, NULL); fd = rd_fndef(d, TOPLEVEL, scope, formaltags, templateformals); bind_scope = save_bind_scope; pop_scope_no_check(sl); lex_closebody(); (void)set_access_context(old_access_context, NULL); cg_topdecl(fd, curlex.fl); drop_local_store(); pop_nested_context(); alloc_unmark(mark); syn_reftemps = old_syn_reftemps; restore_curfn_misc(&tmp); } else add_pendingfn_0(&syn_pendingfns, name, realname, t, stg, scope, formaltags, tokhandle, templateformals, tfn); } static void rebind_typename_typedef(BindList *cc, ScopeSaver env) { for (; cc; cc = cc->bindlistcdr) /* misnomer here, the intention is to fix up class specific typedef's which were originally hidden away by typename. */ fixup_template_arg_type(bindtype_(cc->bindlistcar), env); } void syn_attempt_template_memfn(Binder *generic, Binder *specific) { PendingFnList *x, **prev; TagBinder *primary; if (realbinder_(specific) == NULL) syserr("weird member $b\n", specific); { BindList *bl; if ((bl = bindftlist_(generic)) != NULL) { FormTypeList *ft = typefnargs_(bindtype_(specific)); int len = length((List *)ft); ExprList *l = NULL; BindList *tmpts = NULL; for (; ft; ft = ft->ftcdr) l = mkExprList(l, (Expr *)gentempbinder(ft->fttype)); l = (ExprList *)dreverse(l); for (; bl; bl = bl->bindlistcdr) { Binder *ftemp = bl->bindlistcar; int len2 = length((List *)typefnargs_(bindtype_(ftemp))); if (bindstg_(ftemp) & b_undef || len != len2) continue; tmpts = binder_cons2(tmpts, ftemp); } if ((tmpts = temp_reduce(tmpts, l, NULL, generic)) != NULL) { BindList *ins = bindinstances_(tmpts->bindlistcar); for (; ins; ins = ins->bindlistcdr) if (ins->bindlistcar == specific) return; } } } prev = (PendingFnList **)&tagmemfns_(bindparent_(specific)); x = *prev; for (; x != NULL; prev = &x->pfcdr, x = x->pfcdr) if (x->pfname == bindsym_(realbinder_(specific))) { add_pendingfn(x->pfname, x->pfrealname, x->pftype, x->pfstg, x->pfscope, x->pf_formaltags, x->pf_toklist_handle, x->pf_templateformals, x->pf_tfn); bindstg_(specific) &= ~b_undef; *prev = x->pfcdr; return; } /* try again for out-of-class definition for the specific of the primary, but not if it an explicitly specialized instance */ if (!(tagbindbits_(bindparent_(specific)) & TB_SPECIALIZED) && (primary = tagprimary_(bindparent_(specific))) != NULL) { Binder *b; Symstr *sv = bindsym_(generic); if (generic == specific) { char *tmp = symname_(sv); bool a = (strncmp(tmp, symname_(ctorsym), strlen(symname_(ctorsym))) == 0), b = (strncmp(tmp, symname_(dtorsym), strlen(symname_(dtorsym))) == 0); if (!a && !b) syserr("syn_attempt_template_memfn: what kind of generic is this $b?", generic); sv = a ? ctorsym : dtorsym; } b = findbinding(sv, primary, INCLASSONLY); if (b != NULL && h0_(bindtype_(b)) == t_ovld) { BindList *tmpts; ExprList *args = NULL; FormTypeList *ft = typefnargs_(bindtype_(specific)); int temp_scope; BindList *candidates = clone_bindlist(typeovldlist_(bindtype_(b)), NO); for (; ft; ft = ft->ftcdr) args = mkExprList(args, (Expr *)gentempbinder(ft->fttype)); args = (ExprList *)dreverse((List *)args); rebind_typename_typedef(candidates, tagbindmems_(bindparent_(specific))); temp_scope = push_var_scope(tagactuals_(bindparent_(specific)), Scope_TemplateArgs); tmpts = temp_reduce(candidates, args, NULL, generic); if (tmpts == NULL) { /* try again for template memfn */ candidates = clone_bindlist(bindftlist_(b), NO); rebind_typename_typedef(candidates, tagbindmems_(bindparent_(specific))); tmpts = temp_reduce(bindftlist_(b), args, NULL, generic); } pop_scope_no_check(temp_scope); if (tmpts != NULL && !(bindstg_(realbinder_(b = tmpts->bindlistcar)) & b_undef)) { FormTypeList *ft = typefnargs_(bindtype_(specific)), *ft2 = typefnargs_(bindtype_(realbinder_(b))); ScopeSaver env = dup_env_actuals(bindformals_(realbinder_(b)), NULL); for (ft2 = ft2->ftcdr; ft && ft2; ft = ft->ftcdr, ft2 = ft2->ftcdr) if (ft->ftname == NULL) ft->ftname = ft2->ftname; if (env) { ScopeSaver tmp = env; #if 0 for (; tmp; tmp = bindcdr_(tmp)) { ScopeSaver actuals_env = tagactuals_(bindparent_(specific)); for (; actuals_env; actuals_env = bindcdr_(actuals_env)) if (bindsym_(actuals_env) == bindsym_(tmp)) bindtype_(tmp) = bindtype_(actuals_env); } #else ScopeSaver actuals_env = tagactuals_(bindparent_(specific)); for (; tmp && actuals_env; tmp = bindcdr_(tmp), actuals_env = bindcdr_(actuals_env)) bindtype_(tmp) = bindtype_(actuals_env); if (tmp || actuals_env) syserr("incompatible type env"); #endif } add_pendingfn(bindsym_(realbinder_(specific)), ovld_tmptfn_instance_name(bindsym_(realbinder_(b)), env), globalize_typeexpr_no_default_arg_vals(bindtype_(specific)), bindstg_(realbinder_(b)), bindparent_(specific), tagactuals_(bindparent_(specific)), bindtext_(realbinder_(b)), env, YES); bindstg_(specific) &= ~b_undef; } } else if (b != NULL && h0_(bindtype_(b)) == s_fnap) { Binder *realb = realbinder_(b); if (realb != NULL && bindtext_(realb) >= 0) { add_pendingfn(bindsym_(realbinder_(specific)), ovld_tmptfn_instance_name(bindsym_(realb), bindenv_(realb)), globalize_typeexpr_no_default_arg_vals(bindtype_(specific)), bindstg_(realb), bindparent_(specific), tagactuals_(bindparent_(specific)), bindtext_(realb), bindformals_(realb), YES); bindstg_(specific) &= ~b_undef; } } } } static ScopeSaver applicable_template_formals(void) { ScopeSaver t = NULL; if (cur_template_formals) { t = cur_template_formals->bindlistcar; cur_template_formals = (BindList *) discard2((VoidStar)cur_template_formals); } return t; } ScopeSaver cur_tformals(void) { return (cur_template_formals) ? cur_template_formals->bindlistcar : NULL; } static void syn_implicit_instantiate(TagBinder *primary, TagBinder *instance) { TagBinder *instantiatetemplate; if ((tagbindbits_(instance) & TB_DEFD) || (tagbindbits_(instance) & TB_BEINGDEFD)) return; instantiatetemplate = class_template_reduce(primary, taginstances_(primary), tagactuals_(instance)); if (tagbindbits_(instantiatetemplate) & TB_DEFD) { int h = tagtext_(instantiatetemplate); BindList *old_cur_template_formals = cur_template_formals; if (debugging(DEBUG_TEMPLATE)) cc_msg("instantiate $c buffer[%d]\n", instantiatetemplate, h); if (h < 0) syserr("template symbol buffer lost"); else { int instantiatescope = push_var_scope(tagscope_(instance), Scope_TemplateDef); (void) push_var_scope(tagactuals_(instance), Scope_TemplateArgs); push_nested_context(xsyn_info_instantiate_class, (IPtr)instance, 0); lex_openbody(h, YES, NO, bindsym_(instantiatetemplate), bindsym_(instance)); tagbindbits_(instance) |= TB_BEINGDEFD; rd_classdecl_(instance); /* more to do c.f. rd_declspec */ tagbindbits_(instance) = (tagbindbits_(instance) & ~TB_BEINGDEFD)|TB_DEFD; tagprimary_(instance) = instantiatetemplate; lex_closebody(); pop_scope_no_check(instantiatescope); if (syn_generatedfns || syn_pendingfns) { TagBinder *old_access_context = set_access_context(NULL, NULL); PendingFnList *old_pendingfns; FuncMisc tmp; Mark* mark; save_pendingfns(&old_pendingfns), save_curfn_misc(&tmp); mark = alloc_mark(); chk_for_auto = YES; while (syn_generatedfns || syn_pendingfns) { TopDecl *d; cg_reinit(); /* BEFORE rd_topdecl() */ /* there is a alloc_unmark() in case of syn_generatedfns */ d = rd_topdecl(NO); /* careful about function template */ if (h0_(d) != s_fndef) continue; cg_topdecl(d, curlex.fl); } chk_for_auto = NO; alloc_unmark(mark); restore_curfn_misc(&tmp), restore_pendingfns(old_pendingfns); (void)set_access_context(old_access_context, NULL); } pop_nested_context(); } cur_template_formals = old_cur_template_formals; } } /* Almost rd_template_postfix() but without the tokens available */ TagBinder *syn_implicit_instantiate_2(TagBinder *tb) { Symstr *sv; TagBinder *tb2; ScopeSaver env = tagformals_(tb); ExprList *actuals = NULL; bool newtag = NO; for (; env; env = bindcdr_(env)) { Binder *b = findbinding(bindsym_(env), 0, FB_LOCALS|FB_THISSCOPE); Expr *e; if (!b) syserr("Odd template type arg $r", bindsym_(env)); e = (Expr *)syn_list4(s_typespec, primtype2_(bitoftype_(s_typedefname), b), 0, 0); actuals = (ExprList *)syn_cons2(actuals, e); } actuals = (ExprList *)dreverse((List *)actuals); env = tagformals_(tb); sv = ovld_template_app(bindsym_(tb), env, actuals); tb2 = instate_tagbinding(sv, tagbindsort(tb), TD_Decl, TOPLEVEL|TEMPLATE, &newtag); if (newtag) { Binder *b = instate_classname_typedef(tb2, TOPLEVEL); tagprimary_(tb2) = tb; tb2->tagparent = NULL; tagscope_(tb2) = tagscope_(tb); attributes_(b) |= A_TEMPLATE; tagactuals_(tb2) = globalize_template_arg_binders(env, actuals); } syn_implicit_instantiate(tb, tb2); return tb2; } void parameter_names_transfer(FormTypeList *from, FormTypeList *to) { if (length((List*)from) != length((List *)to)) syserr("incompatible parameter type lists"); for (; to && from; to = to->ftcdr, from = from->ftcdr) to->ftname = from->ftname; } void xsyn_reinit() { rootOfPath = NULL; recursing = 0; } static void xsyn_init(void) { saved_temps = NULL; recursing = 0; } /* End of cppfe/xsyn.c */
stardot/ncc
tests/2131.c
<gh_stars>0 /* * ARM C compiler regression test $RCSfile$ * Copyright (C) 1995 Advanced Risc Machines Ltd. All rights reserved. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <string.h> #include "testutil.h" /********************* 2131 ***********************/ /* may syserr - must be compiled with -g -apcs /reent */ unsigned char const arr[2] [1] = { {1}, {1} }; #define m(s) { int *r; r = (int *)(s); } int f_2131 ; int *p_2131; void t_2131() { int i ; switch (i) { case 1 : if ( f_2131 == 1 ) f_2131 = 1 ; else f_2131 = -1 ; break ; case 2 : m(p_2131[1]); t_2131(); f_2131 = 1 ; f_2131 = 1 ^ f_2131 ; break ; case 3 : case 4 : m(p_2131[1]); f_2131 = 3 ; f_2131 = 3 ; f_2131 = 3 ; f_2131 = 3 ; f_2131 = 1 ; f_2131 = 1 ^ f_2131 ; break; case 5 : m(arr[1]); break; } } /* no executable test */ int main(void) { BeginTest(); t_2131(); EndTest(); return 0; }
stardot/ncc
thumb/tmcdep.c
<gh_stars>0 /* * mcdep.c - miscellaneous target-dependent things. * Copyright (C) Acorn Computers Ltd., 1988. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <ctype.h> #include <string.h> #include <stdlib.h> #include "globals.h" #include "mcdep.h" #include "mcdpriv.h" #include "errors.h" #include "pp.h" #include "compiler.h" #include "toolenv.h" #include "toolenv2.h" #include "tooledit.h" int arthur_module; int32 config; int32 pcs_flags; #ifdef TARGET_IS_HELIOS int in_stubs; #endif typedef struct { char const *name; char const *val; } EnvItem; #define str(s) #s #define xstr(s) str(s) static EnvItem const builtin_defaults[] = { { "-cpu", "#ARM7TM"}, { "-arch", "#4T" }, #if (PCS_DEFAULTS & PCS_NOSTACKCHECK) { "-apcs.swst", "#/noswst"}, #else { "-apcs.swst", "#/swst"}, #endif #if (PCS_DEFAULTS & PCS_REENTRANT) { "-apcs.reent", "#/reent"}, #else { "-apcs.reent", "#/noreent"}, #endif #if (PCS_DEFAULTS & PCS_INTERWORK) { "-apcs.inter", "#/interwork"}, #else { "-apcs.inter", "#/nointerwork"}, #endif { "-apcs.32bit", "#/32"}, { "-apcs.softfp", "#/softfp"}, { "-apcs.fpis", "#/fpe3"}, { "-apcs.fp", "#/nofp"}, { "-apcs.fpr", "#/nofpregargs"}, { "-zr", "=" xstr(LDM_REGCOUNT_MAX_DEFAULT) }, { "-zi", "=" xstr(INTEGER_LOAD_MAX_DEFAULT) }, { "-zas", "=4" }, { ".areaperfn", "=-z+o" }, #if (PCS_DEFAULTS & PCS_UNWIDENED_NARROW_ARGS) { "-apcs.wide", "#/narrow"}, #else { "-apcs.wide", "#/wide"}, #endif #ifdef CPLUSPLUS { ".debugtable", "=-dwarf" }, #else { ".debugtable", "=-asd" }, #endif {NULL, NULL} }; int mcdep_toolenv_insertdefaults(ToolEnv *t) { EnvItem const *p = builtin_defaults; for (; p->name != NULL; p++) { ToolEdit_InsertStatus rc = tooledit_insert(t, p->name, p->val); if (rc == TE_Failed) return 1; } return 0; } static char *EqualString(char *b, char const *s) { b[0] = '='; strcpy(&b[1], s); return b; } bool mcdep_config_option(char name, char const tail[], ToolEnv *t) { char b[64]; switch (safe_tolower(name)) { #ifndef TARGET_IS_UNIX #ifdef TARGET_IS_HELIOS case 'r': suppress_module = 1; return YES; #else case 'm': { int m = 1; if (isdigit(tail[0])) m += (tail[0]-'0'); sprintf(b, "=%d", m); tooledit_insert(t, "-zm", b); return YES; } #endif #endif case 'a': if (tail[0] == '\0' || isdigit(tail[0])) { tooledit_insert(t, "-za", tail[0] == '0' ? "=0" : "=1"); return YES; } break; case 'd': tooledit_insert(t, "-zd", tail[0] == '0' ? "=0" : "=1"); return YES; case 'i': return tooledit_insert(t, "-zi", EqualString(b, tail)) != TE_Failed; case 'r': return tooledit_insert(t, "-zr", EqualString(b, tail)) != TE_Failed; } return NO; } typedef struct { char const *opt; char const *name; char const *val; } kw; static kw const pcs_keywords[] = { { "reentrant", "-apcs.reent", "#/reent" }, { "nonreentrant", "-apcs.reent", "#/noreent"}, { "noreentrant", "-apcs.reent", "#/noreent"}, { "reent", "-apcs.reent", "#/reent" }, { "nonreent", "-apcs.reent", "#/noreent"}, { "noreent", "-apcs.reent", "#/noreent"}, { "interwork", "-apcs.inter", "#/interwork"}, { "nointerwork", "-apcs.inter", "#/nointerwork"}, { "inter", "-apcs.inter", "#/interwork"}, { "nointer", "-apcs.inter", "#/nointerwork"}, { "fpe3", "-apcs.fpis", "#/fpe3"}, { "swstackcheck", "-apcs.swst", "#/swst"}, { "noswstackcheck", "-apcs.swst", "#/noswst"}, { "swst", "-apcs.swst", "#/swst"}, { "noswst", "-apcs.swst", "#/noswst"}, { "32bit", "-apcs.32bit", "#/32"}, { "32", "-apcs.32bit", "#/32"}, { "nofpregargs", "-apcs.fpr", "#/nofpregargs"}, { "nofpr", "-apcs.fpr", "#/nofpregargs"}, { "nofp", "-apcs.fp", "#/nofp"}, { "softfp", "-apcs.softfp", "#/softfp"}, { "wide", "-apcs.wide", "#/wide"}, { "narrow", "-apcs.wide", "#/narrow"} }; static char const * const debug_table_keywords[] = { #ifdef TARGET_HAS_ASD "-asd", "-asd-old", #endif #ifdef TARGET_HAS_DWARF "-dwarf1", "-dwarf2", "-dwarf", #endif "" }; KW_Status mcdep_keyword(char const *key, char const *nextarg, ToolEnv *t) { char str[64]; int ch; unsigned i; if (cistreq(key, "-apcs")) { Uint count = 0; if (nextarg == NULL) return KW_MISSINGARG; if (nextarg[0] == '3') nextarg++; for (;; count++) { ch = *nextarg; i = 0; if (ch == 0) return (count == 0) ? KW_BADNEXT: KW_OKNEXT; if (ch != '/') return KW_BADARG; for (; (ch = *++nextarg) != '/' && ch != 0; ) str[i++] = safe_tolower(ch); str[i] = 0; for (i = 0; i < sizeof(pcs_keywords) / sizeof(pcs_keywords[0]); i++) if (StrEq(str, pcs_keywords[i].opt)) { tooledit_insert(t, pcs_keywords[i].name, pcs_keywords[i].val); break; } if (i == sizeof(pcs_keywords) / sizeof(pcs_keywords[0])) return KW_BADNEXT; } } for (i = 0; i < sizeof(debug_table_keywords) / sizeof(debug_table_keywords[0]); i++) if (cistreq(key, debug_table_keywords[i])) { tooledit_insert(t, ".debugtable", EqualString(str, debug_table_keywords[i])); return KW_OK; } return KW_NONE; } static char lib_variant[16]; void target_lib_variant(char *b) { strcpy(b, lib_variant); } char const *target_lib_name(ToolEnv *t, char const *name) { static char namebuf[64]; int len = strlen(name); IGNORE(t); if (name[len-2] == '.' && name[len-1] == 'o') { memcpy(namebuf, name, len-2); target_lib_variant(&namebuf[len-2]); return namebuf; } return name; } char *target_asm_options(ToolEnv *t) { int i; static char v[32]; config_init(t); strcpy(v, (config & CONFIG_BIG_ENDIAN) ? "-bi" : "-li"); i = 3; if (pcs_flags & (PCS_REENTRANT+PCS_FPE3+PCS_CALLCHANGESPSR)) { if (i != 0) v[i++] = ' '; strcpy(&v[i], "-apcs 3"); if (pcs_flags & PCS_REENTRANT) strcat(&v[i], "/reent"); strcat(&v[i], (pcs_flags & PCS_CALLCHANGESPSR) ? "/32bit" : "/26bit"); } return v; } /*************************************************************/ /* */ /* Code to configure compiler for host system */ /* */ /*************************************************************/ static bool EnvHasValue(ToolEnv *t, char const *name, char const *val) { char const *tval = toolenv_lookup(t, name); return tval != NULL && StrEq(val, tval); } typedef struct { char const *name; char const *val; uint32 flag; } Opt; static Opt const config_opts[] = { {".bytesex", "=-bi", CONFIG_BIG_ENDIAN}, {"-apcs.reent", "#/reent", CONFIG_REENTRANT_CODE}, {"-apcs.wide", "#/narrow", CONFIG_UNWIDENED_NARROW_ARGS}, {NULL, NULL, 0} }; static Opt const pcs_opts[] = { {"-apcs.swst", "#/noswst", PCS_NOSTACKCHECK}, {"-apcs.reent", "#/reent", PCS_REENTRANT}, {"-apcs.inter", "#/interwork", PCS_INTERWORK}, {"-zd", "=1", PCS_ACCESS_CONSTDATA_WITH_ADR}, {NULL, NULL, 0} }; void config_init(ToolEnv *t) { Uint i; config = CONFIG_SOFTWARE_FP; for (i = 0; config_opts[i].name != NULL; i++) if (EnvHasValue(t, config_opts[i].name, config_opts[i].val)) config |= config_opts[i].flag; integer_load_max = TE_Integer(t, "-zi", INTEGER_LOAD_MAX_DEFAULT); ldm_regs_max = TE_Integer(t, "-zr", LDM_REGCOUNT_MAX_DEFAULT); pcs_flags = PCS_SOFTFP | PCS_NOFP | PCS_CALLCHANGESPSR; for (i = 0; pcs_opts[i].name != NULL; i++) if (EnvHasValue(t, pcs_opts[i].name, pcs_opts[i].val)) pcs_flags |= pcs_opts[i].flag; dbg_setformat(toolenv_lookup(t, ".debugtable")); { char v[8]; char *p = v; char *b = lib_variant; size_t vlen; if (!(pcs_flags & PCS_NOSTACKCHECK)) *p++ = 's'; if (pcs_flags & PCS_INTERWORK) *p++ = 'i'; if (pcs_flags & PCS_REENTRANT) *p++ = 'e'; vlen = p - v; if (vlen != 0) { *b++ = '_'; memcpy(b, v, vlen); b += vlen; } sprintf(b, ".16%c", (config & CONFIG_BIG_ENDIAN) ? 'b' : 'l'); } } void mcdep_set_options(ToolEnv *t) { IGNORE(t); } /**********************************************************************************/ #include "jopcode.h" #include "mcdpriv.h" #include "ops.h" #include "aeops.h" #include "inlnasm.h" #include "flowgraf.h" #include "simplify.h" int32 a_loads_r1(const PendingOp *const p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; return (op > J_LAST_JOPCODE) ? a_attributes(op) & _a_set_r1: loads_r1(op); } int32 a_uses_r1(const PendingOp *const p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; return (op > J_LAST_JOPCODE) ? a_attributes(op) & (_a_set_r1 | _a_read_r1) : uses_r1(op); } int32 a_reads_r1(const PendingOp *const p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; return (op > J_LAST_JOPCODE) ? a_attributes(p->ic.op) & _a_read_r1 : reads_r1(op); } int32 a_loads_r2(const PendingOp *const p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; return (op > J_LAST_JOPCODE) ? a_attributes(op) & _a_set_r2: loads_r2(op); } int32 a_uses_r2(const PendingOp *const p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; return (op > J_LAST_JOPCODE) ? a_attributes(op) & (_a_set_r2 | _a_read_r2) : uses_r2(op); } int32 a_reads_r2(const PendingOp *const p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; return (op > J_LAST_JOPCODE) ? a_attributes(op) & _a_read_r2 : reads_r2(op); } int32 a_uses_r3(const PendingOp *const p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; return (op > J_LAST_JOPCODE) ? a_attributes(op) & _a_read_r3 : uses_r3(op); } int32 a_uses_r4(const PendingOp *const p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; return ((op > J_LAST_JOPCODE) ? a_attributes(op) & _a_read_r4 : uses_r4(op)); } int32 a_uses_mem(const PendingOp *const p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; if (a_modifies_mem(p)) return YES; return (op) > J_LAST_JOPCODE ? a_attributes(op) & (_a_modify_mem | _a_read_mem) : j_is_ldr_or_str(op); } bool sets_psr(const Icode *ic) { J_OPCODE op = ic->op & J_TABLE_BITS; if (op == J_CMPR || op == J_MOVR || op == J_NEGR || op == J_NOTR || (op == J_MOVK && ic->r3.i >= 0 && ic->r3.i < 256) || op == J_SHRK || op == J_SHLK || op == J_RORK || op == J_SHLR || op == J_SHRR || op == J_RORR || op == J_RORK || op == J_SUBK || op == J_ADDK || op == J_CMPK || op == J_MULK || op == J_ANDK || op == J_ORRK || op == J_EORK || op == J_ADDR || op == J_SUBR || op == J_ANDR || op == J_ORRR || op == J_EORR || op == J_MULR || op == J_BICR #ifdef THUMB_INLINE_ASSEMBLER || op == J_ADCK || op == J_ADCR || op == J_SBCK || op == J_SBCR || op == J_TSTK || op == J_TSTR || op == J_CMNK || op == J_CMNR || op == J_BICK || op == J_MVNR #endif /* HACK: these two are here because they may otherwise generate corrupt-register. Need to find out how/why. SetSPEnv for example should not corrupt the PSR. */ || op == J_CASEBRANCH || op == J_BXX || J_SETSPENV ) return 1; if (op == J_CALLK && ic->r2.i & K_RESULTINFLAGS) return YES; return NO; } bool reads_psr(const Icode *ic) { J_OPCODE op = ic->op & J_TABLE_BITS; /* WD: asm BL can be assumed to read the PSR as well */ /* TODO problem: some instructions don't modify the V or C bit, and should probably be regarded as reading the PSR. But for C generated code, flags from previous instr are NEVER used, so we have a problem here... */ return ((op == J_B && ic->op & Q_MASK != 0) #ifdef THUMB_INLINE_ASSEMBLER || op == J_ADCK || op == J_ADCR || op == J_SBCK || op == J_SBCR || op == J_TSTK || op == J_TSTR || ((op == J_BL || op == J_SWI) && (ic->r2.i & regbit(R_PSR))) #endif ); } bool uses_psr(const Icode *ic) { return reads_psr(ic) || sets_psr(ic); } bool corrupts_psr(const Icode *ic) { J_OPCODE op = ic->op & J_TABLE_BITS; /* Some operatons might set the PSR as a side-effect (eg. LDRx) */ if ( (op == J_MOVK && (ic->r3.i < 0 || ic->r3.i >= 256)) || op == J_OPSYSK || op == J_CALLR ||op == J_CLRC || op == J_LDRBK || op == J_LDRWK || op == J_LDRK || op == J_STRBK || op == J_STRWK || op == J_STRK || op == J_LDRBV || op == J_LDRWV || op == J_LDRV || op == J_STRBV || op == J_STRWV || op == J_STRV || op == J_LDRBVK || op == J_LDRWVK || op == J_LDRVK || op == J_STRBVK || op == J_STRWVK || op == J_STRVK) return 1; if (op == J_CALLK) { if (ic->r2.i & K_RESULTINFLAGS) return NO; return (pcs_flags & PCS_CALLCHANGESPSR); } if (op == J_MOVC) return ic->r3.i > MOVC_LOOP_THRESHOLD; if (op == J_ADCON) return 1; return 0; } int32 a_modifies_mem(const PendingOp *const p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; return (op & J_TABLE_BITS) > J_LAST_JOPCODE ? a_attributes(op) & _a_modify_mem : writes_mem(op); } bool corrupts_r1(const Icode *ic) { uint32 op = ic->op & J_TABLE_BITS; return op == J_MOVC || op == J_CLRC; } bool corrupts_r2(const Icode *ic) { uint32 op = ic->op & J_TABLE_BITS; return op == J_MOVC; } bool a_corrupts_r1(PendingOp const* p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; return op == J_MOVC || op == J_CLRC; } bool a_corrupts_r2(PendingOp const* p) { J_OPCODE op = p->ic.op & J_TABLE_BITS; return op == J_MOVC; } static bool OutputsClashWithIP(const Icode *const p) { RealRegister r1, r2, mr; int32 m; r1 = p->r1.rr; r2 = p->r2.rr; mr = p->r3.rr; m = p->r3.i; #if 0 printf("op = %08x, r1 = %d, r2 = %d, m = %d\n", p->op & J_TABLE_BITS, r1, r2, m); #endif switch (p->op & J_TABLE_BITS) { case J_RORK: return YES; case J_SETSPENV: { BindList *to, *from; Binder *b; int32 diff; from = p->r2.bl; to = p->r3.bl; diff = 0; while (from) { b = from->bindlistcar; diff += bindmcrep_(b) & MCR_SIZE_MASK; from = from->bindlistcdr; } while (to) { b = to->bindlistcar; diff -= bindmcrep_(b) & MCR_SIZE_MASK; to = to->bindlistcdr; } if (diff <= -512 || diff >= 512) return YES; return NO; } default: return NO; } } static bool InputsClashWithIP(const Icode *const p) { RealRegister r1, r2, mr; int32 m; r1 = p->r1.rr; r2 = p->r2.rr; mr = p->r3.rr; m = p->r3.i; #if 0 printf("op = %08x, r1 = %d, r2 = %d, m = %d\n", p->op & J_TABLE_BITS, r1, r2, m); #endif switch (p->op & J_TABLE_BITS) { case J_MOVC: case J_CLRC: return YES; case J_RORK: case J_ORRK: case J_EORK: case J_MULK: case J_CASEBRANCH: return YES; case J_SHRR: case J_SHLR: case J_RORR: return YES; case J_SUBK: m = -m; case J_ADDK: if (r2 == R_SP) { if (r1 == R_SP) return m <= -512 || m >= 512; return NO; } return m < -(2*255+7) || m > 2*255+7; #ifdef THUMB_INLINE_ASSEMBLER case J_ADCK: case J_SBCK: case J_SBCR: return YES; case J_CMNK: return m > 0 || m < -255; case J_TSTK: case J_BICK: return YES; #endif case J_SETSPGOTO: case J_SETSP: { int32 diff; diff = m - r2; return diff <= -512 || diff >= 512; } case J_ANDK: return power_of_two(m+1) == -1 && power_of_two(-m) == -1; case J_CMPK: return m < 0 || m > 255; #ifdef THUMB_CPLUSPLUS case J_THUNKTABLE: return NO; #endif default: return NO; } } static int32 movc_workregs1(const Icode * const ic) { /* p->op is known to be one of CLRC, MOVC or PUSHC */ int32 set = regbit(R_A4) | regbit(R_IP); /* R_IP happens to be R_A4 */ if (ic->r3.i > MOVC_LOOP_THRESHOLD) set |= regbit(R_A2) | regbit(R_A3); return set; } int32 movc_workregs(const PendingOp *const p) { /* p->op is known to be one of CLRC, MOVC or PUSHC */ int32 set = movc_workregs1(&p->ic) | p->ic.r4.rr; set &= ~regbit(p->ic.r1.rr); return set; } bool movc_preserving_r1r2(PendingOp *p, bool dead_r2) { IGNORE(p); IGNORE(dead_r2); return NO; } #ifdef DEBUG_THUMB_CPLUSPLUS int sanity_check_has_callr; #endif bool UnalignedLoadMayUse(RealRegister r) { /* Some cases use A2: we must be pessimistic, since the interface doesn't */ /* give enough information for us to know for certain. */ return r == R_IP || r == R_A1+2; } int32 MaxMemOffset(J_OPCODE op) { if ((op & J_ALIGNMENT) == J_ALIGN1) return uses_stack(op) ? 1020+31 : 31; switch (j_memsize(op)) { case MEM_B: return (uses_stack(op) && reads_mem(op)) ? 1020 + 31 : 31; case MEM_W: return (uses_stack(op) && reads_mem(op)) ? 1020 + 62 : 62; case MEM_I: return uses_stack(op) ? 1020 : 124; case MEM_F: case MEM_D: case MEM_LL: default: /* that was a complete enumeration, but keep the */ /* compiler quiet. */ return 0; } } int32 MinMemOffset(J_OPCODE op) { IGNORE(op); return 0; } int32 MemQuantum(J_OPCODE op) { if ((op & J_ALIGNMENT) == J_ALIGN1) return 1; switch(j_memsize(op)) { case MEM_B: return 1; case MEM_W: return 2; case MEM_I: return 4; case MEM_F: case MEM_D: case MEM_LL: default: /* that was a complete enumeration, but keep the */ /* compiler quiet. */ return 4; } } static bool OverlargeMemOffset(const Icode *ic) { int32 maxoffset, offset; J_OPCODE op = ic->op; if (reads_r3(ic->op)) /* filter out LDRxRs */ return NO; /* turn a LDRK with SP as base back into LDRV - these have different offsets... */ if (!uses_stack(op) && ic->r2.r == R_SP) op += J_STRV - J_STRK; maxoffset = MaxMemOffset(op); if (uses_stack(ic->op)) { if ((bindaddr_(ic->r3.b) & BINDADDR_MASK) == BINDADDR_ARG) { /* argument */ offset = max_argsize + greatest_stackdepth + TARGET_MAX_FRAMESIZE; } else { /* local variable */ offset = greatest_stackdepth; } return offset > maxoffset; } else return ic->r3.i < 0 || ic->r3.i > maxoffset; } static uint32 GetUsedRegs(Binder *b) { Symstr *s = (h0_(b) == s_binder) ? bindsym_(b) : (Symstr *) b; uint32 volatile_regs = regbit(R_IP) | reglist(R_A1, NARGREGS) | reglist(R_F0, NFLTARGREGS); /* The code below is because of the fact that there are 2 different representations * of binders, depending of whether you are pre or post regalloc. * This code tries to find out in which stage we are... * Note that symext_(sym) might not be initialized. */ if (var_cc_private_flags & 1024L) /* usedregs optimization disabled */ return volatile_regs; return (symext_(s) != NULL) ? symext_(s)->usedregs.map[0] : volatile_regs; } static uint32 resultregs(Icode const* ic) /* pre: iscall_(ic) */ { /* return result registers including the default result reg */ if (k_resultregs_(ic->r2.i) == 0) return regbit(ic->r1.r); /* 0 means 1 result!!! */ return reglist(R_A1, k_resultregs_(ic->r2.i)); /* > 0 means N results */ } static uint32 argumentregs(uint32 argdesc) { uint32 regs; regs = reglist(R_A1, k_intregs_(argdesc)); if (argdesc & K_SPECIAL_ARG) regs |= regbit(TARGET_SPECIAL_ARG_REG); return regs; } void RealRegisterUse(const Icode *ic, RealRegUse *u) { uint32 use = 0, def = 0, c_in = 0, c_out = 0; switch (ic->op & (J_TABLE_BITS | J_ALIGNMENT)) { case J_MOVC+J_ALIGN4: case J_CLRC+J_ALIGN4: c_in = movc_workregs1(ic); break; case J_LDRBV: case J_LDRBVK: if (ic->op & J_SIGNED) c_out |= regbit(R_IP); break; case J_LDRBK: if (ic->r2.r == R_SP && ic->op & J_SIGNED) c_out |= regbit(R_IP); if (ic->op & J_SIGNED) c_in |= regbit(R_IP); break; case J_LDRBR: if (ic->r2.r == R_SP) /* is this possible (peephole)? */ c_in |= regbit(R_IP); break; case J_STRBV: case J_STRBVK: c_in |= regbit(R_IP); break; case J_STRBK: if (ic->r2.r == R_SP) c_in |= regbit(R_IP); break; case J_STRBR: if (ic->r2.r == R_SP) /* is this possible (peephole)? */ c_in |= regbit(R_IP); break; case J_LDRWV+J_ALIGN1: case J_LDRWVK+J_ALIGN1: c_in |= regbit(R_IP); c_out |= regbit(R_IP); break; case J_LDRWK+J_ALIGN1: if (ic->r2.r == R_SP) c_in |= regbit(R_IP); c_out |= regbit(R_IP); break; case J_LDRWV+J_ALIGN2: case J_LDRWVK+J_ALIGN2: if (ic->op & J_SIGNED) c_out |= regbit(R_IP); break; case J_LDRWK+J_ALIGN2: if (ic->op & J_SIGNED) c_in |= regbit(R_IP); if (ic->r2.r == R_SP && ic->op & J_SIGNED) c_out |= regbit(R_IP); break; case J_LDRWR+J_ALIGN2: if (ic->r2.r == R_SP) /* is this possible (peephole)? */ c_in |= regbit(R_IP); break; case J_STRWV+J_ALIGN1: case J_STRWVK+J_ALIGN1: c_in |= regbit(R_IP) | regbit(R_A3); break; case J_STRWK+J_ALIGN1: c_in |= regbit(R_IP); if (ic->r2.r == R_SP) c_in |= regbit(R_A3); break; case J_STRWV+J_ALIGN2: case J_STRWVK+J_ALIGN2: c_in |= regbit(R_IP); break; case J_STRWK+J_ALIGN2: if (ic->r2.r == R_SP) c_in |= regbit(R_IP); break; case J_STRWR+J_ALIGN2: if (ic->r2.r == R_SP) c_in |= regbit(R_IP); break; case J_LDRK+J_ALIGN1: case J_LDRVK+J_ALIGN1: c_in |= regbit(R_A3); /* IP may be used for r2 */ c_out |= regbit(R_IP) | regbit(R_A3); break; case J_LDRV+J_ALIGN4: case J_LDRVK+J_ALIGN4: break; case J_LDRK+J_ALIGN4: break; case J_LDRR+J_ALIGN4: if (ic->r2.r == R_SP) c_in |= regbit(R_IP); break; case J_STRV+J_ALIGN1: /* ??? */ case J_STRVK+J_ALIGN1: c_in |= regbit(R_IP) | regbit(R_A3); break; case J_STRK+J_ALIGN1: c_in |= regbit(R_IP); if (ic->r2.r == R_SP) c_in |= regbit(R_A3); break; case J_STRV+J_ALIGN4: case J_STRVK+J_ALIGN4: break; case J_STRK+J_ALIGN4: break; case J_STRR+J_ALIGN4: if (ic->r2.r == R_SP) c_in |= regbit(R_IP); break; case J_PUSHM: def = regbit(R_SP); use = regbit(R_SP) | ic->r3.i; break; #ifdef THUMB_INLINE_ASSEMBLER case J_LDM: case J_LDMW: def |= ic->r3.i; break; case J_STM: case J_STMW: use |= ic->r3.i; break; case J_SWI: case J_BL: use = ic->r2.i; def = ic->r3.i; c_out = ic->r4.i; break; #endif case J_OPSYSK: use = argumentregs(ic->r2.i); def = resultregs(ic); if (feature & FEATURE_INLINE_CALL_KILLS_LINKREG) c_in |= M_LR; c_out = reglist(R_A1, NARGREGS); c_out &= ~resultregs(ic); break; case J_CALLK: { uint32 usedregs = GetUsedRegs(ic->r3.b); uint32 volatile_regs = regbit(R_IP) | reglist(R_A1, NARGREGS) | reglist(R_F0, NFLTARGREGS); use = argumentregs(ic->r2.i); def = resultregs(ic); if (ic->r2.i & K_RESULTINFLAGS) def |= regbit(R_PSR); c_in = regbit(R_LR); c_out = (usedregs & volatile_regs) & ~resultregs(ic); break; } case J_CALLR: #ifdef DEBUG_THUMB_CPLUSPLUS sanity_check_has_callr = 1; #endif use = argumentregs(ic->r2.i); def = resultregs(ic); c_in = regbit(R_LR); c_out = regbit(R_IP) | reglist(R_A1, NARGREGS); c_out &= ~resultregs(ic); break; case J_TAILCALLK: use = argumentregs(ic->r2.i); def = 0; break; case J_TAILCALLR: /* NOT IMPLEMENTED in backend! */ break; /* J_ENTER & J_SAVE have quite complex register usage. As they are currently not * used in neither register allocation nor peepholing, this isn't implemented yet. * Therefore their register usage is only implemented for gen.c * BEWARE for changes in this! */ case J_SAVE: break; case J_ENTER: def = argumentregs(ic->r3.i); break; default: if (InputsClashWithIP(ic)) c_in = regbit(R_IP); if (OutputsClashWithIP(ic)) c_out = regbit(R_IP); break; } if ((ic->op & J_TABLE_BITS) < J_LAST_JOPCODE && j_is_ldr_or_str(ic->op) && OverlargeMemOffset(ic)) c_in |= regbit(R_IP); u->use.map[0] = use; u->def.map[0] = def; u->c_in.map[0] = c_in; u->c_out.map[0] = c_out; } char *CheckJopcode(const Icode *ic, CheckJopcode_flags flags) { PendingOp p; p.ic = *ic; p.peep = 0; p.dataflow = p.ic.op & J_DEADBITS; p.cond = p.ic.op & Q_MASK; return CheckJopcodeP(&p, flags); } char *CheckJopcodeP(const PendingOp *p, CheckJopcode_flags flags) { char *errmsg = NULL; const Icode *ic = &p->ic; /* Check alignment of memory instructions */ if ((flags & JCHK_MEM) && (ic->op & J_TABLE_BITS) < J_LAST_JOPCODE && j_is_ldr_or_str(ic->op)) { if (!reads_r3(ic->op) && !uses_stack(ic->op)) /* LDRK/STRK */ { if (ic->r3.i & (MemQuantum(ic->op) - 1)) errmsg = "alignment error"; } switch (ic->op & (J_TABLE_BITS | J_ALIGNMENT)) { case J_LDRWK+J_ALIGN1: case J_STRWK+J_ALIGN1: if (ic->r2.r != R_SP && (ic->r3.i < 0 || ic->r3.i >= 32)) errmsg = "unaligned LDRWK/STRWK with overlarge offset"; break; case J_LDRK+J_ALIGN1: case J_STRK+J_ALIGN1: if (ic->r2.r != R_SP && (ic->r3.i < 0 || ic->r3.i >= 32)) errmsg = "unaligned LDRK/STRK with overlarge offset"; break; } } /* Check register numbers, usage, clashes and deadbits */ if (flags & JCHK_REGS) { bool fault = NO; RegisterUsage u; /* Consistency check on deadbits */ if (!a_uses_r1(p) && p->dataflow & J_DEAD_R1) fault = YES; if (!a_uses_r2(p) && p->dataflow & J_DEAD_R2) fault = YES; if (!a_uses_r3(p) && p->dataflow & J_DEAD_R3) fault = YES; if (!a_uses_r4(p) && p->dataflow & J_DEAD_R4) fault = YES; if (fault) errmsg = "corrupted deadbits"; /* Consistency check on physical register numbers */ fault = NO; if (a_uses_r1(p) && (uint32)p->ic.r1.rr >= 16) fault = YES; if (a_uses_r2(p) && (uint32)p->ic.r2.rr >= 16) fault = YES; if (a_uses_r3(p) && (uint32)p->ic.r3.rr >= 16) fault = YES; if (a_uses_r4(p) && (uint32)p->ic.r4.rr >= 16) fault = YES; if (fault) errmsg = "illegal register number"; if (GetRegisterUsage(p, &u)) errmsg = "corrupted register"; fault = NO; switch (ic->op) { case J_MULR: if (p->ic.r1.r == p->ic.r3.r) fault = YES; break; } if (fault) errmsg = "register clash"; } if ((flags & JCHK_SYSERR) && errmsg != NULL) { if (strcmp(errmsg, "alignment error") != 0) syserr(errmsg); else cc_warn("illegal unaligned load or store access - use __packed instead"); } return errmsg; } /* WD TODO: Need to alter this... has_side_effects should be a backend function, looking at a volatile bit, etc. Certain types of calls could be regarded as memory modifyable too. Also need something to prevent assembler loads/stores to be removed! */ bool has_side_effects(Icode const *ic) { J_OPCODE op = ic->op & J_TABLE_BITS; if (writes_mem(op)) return YES; #ifdef THUMB_INLINE_ASSEMLBER if (op == J_SWI || op == J_BL) return YES; #endif return NO; } /* WD: TODO remove writeback should be a backend function, with the dead flags as inputs (are dead register set), and returns a NOOP, a modified instruction or the same instruction... */ void remove_writeback(Icode *ic) { IGNORE(ic); } /* Returns the register usage of a pendingop. Returns true if the register usage * is incorrect (where inputs or outputs are being corrupted). */ bool GetRegisterUsage(const PendingOp *c, RegisterUsage *u) { RealRegUse usage; bool corrupted = NO; u->use = u->def = u->corrupt = u->dead = 0; if (a_loads_r1(c)) u->def |= regbit(c->ic.r1.rr); if (a_loads_r2(c)) u->def |= regbit(c->ic.r2.rr); if (sets_psr(&c->ic) || (c->peep & P_CMPZ)) u->def |= regbit(R_PSR); if (a_corrupts_r1(c)) u->corrupt |= regbit(c->ic.r1.rr); if (a_corrupts_r2(c)) u->corrupt |= regbit(c->ic.r2.rr); if (corrupts_psr(&c->ic)) u->corrupt |= regbit(R_PSR); if (a_reads_r1(c)) u->use |= regbit(c->ic.r1.rr); if (a_reads_r2(c)) u->use |= regbit(c->ic.r2.rr); if (a_uses_r3(c)) u->use |= regbit(c->ic.r3.rr); if (a_uses_r4(c)) u->use |= regbit(c->ic.r4.rr); if (reads_psr(&c->ic)) u->use |= regbit(R_PSR); RealRegisterUse(&c->ic, &usage); u->use |= usage.use.map[0]; u->def |= usage.def.map[0]; if (u->use & usage.c_in.map[0]) /* inputs & corrupted inputs CANNOT overlap */ corrupted = YES; if (u->def & usage.c_out.map[0]) /* output & corrupted output CANNOT overlap */ corrupted = YES; /* corrupted inputs may overlap with definitions, hence we clear out the definitions */ u->corrupt |= (usage.c_in.map[0] & ~u->def) | usage.c_out.map[0]; if (c->dataflow & J_DEAD_R1) u->dead |= regbit(c->ic.r1.rr); if (c->dataflow & J_DEAD_R2) u->dead |= regbit(c->ic.r2.rr); if (c->dataflow & J_DEAD_R3) u->dead |= regbit(c->ic.r3.rr); if (c->dataflow & J_DEAD_R4) u->dead |= regbit(c->ic.r4.rr); u->dead &= ~u->def; /* LDM R0, {R0} case - clear out all defined regs */ if (a_loads_r1(c) && (c->dataflow & J_DEAD_R1)) /* ADD R0, R0, #1 case */ u->dead |= regbit(c->ic.r1.rr); if (a_loads_r2(c) && (c->dataflow & J_DEAD_R2)) u->dead |= regbit(c->ic.r2.rr); return corrupted; } /* end of arm/mcdep.c */
stardot/ncc
mip/flowgraf.h
<reponame>stardot/ncc /* * mip/flowgraf.h * Copyright (C) Acorn Computers Ltd., 1988. * Copyright (C) Codemist Ltd., 1988. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _flowgraf_LOADED #define _flowgraf_LOADED 1 #ifndef _defs_LOADED # include "defs.h" #endif #ifndef _cgdefs_LOADED # include "cgdefs.h" #endif #ifndef _jopcode_LOADED # include "jopcode.h" #endif extern BlockHead *top_block, *bottom_block; /* exported to cg/regalloc */ extern struct CGState { /* Shared between flowgraf and cg, used during jopcode emission only */ BindListList *curenv; BindList *active; /* statistics */ int32 icode_cur, block_cur; struct { Binder *var; VRegnum reg; } juststored; } cgstate; #define current_env cgstate.curenv #define active_binders cgstate.active extern int32 sizeofbinders(BindList *l, bool countall); extern void finishblock(void); extern void end_emit(void); extern Icode *newicodeblock(int32 size); extern void freeicodeblock(Icode *p, int32 size); extern void reopen_block(BlockHead *p); #define start_new_basic_block(l) \ start_basic_block_at_level(l, active_binders) extern BlockHead *insertblockbetween(BlockHead *before, BlockHead *after, bool insertingraph); /* make a new block, and insert it between blocks before and after in the blockup_/down_ sense. If insertingraph is true, also insert it between before and after in the blknext_ sense. (error if there is no arc from before to after). */ extern void changesuccessors(BlockHead *b,LabelNumber *newl,LabelNumber *oldl); /* change all arcs from b whose destination is oldl to have destination newl instead. */ extern BlockHead *start_basic_block_at_level(LabelNumber *l, BindList *active_on_entry); extern bool is_exit_label(LabelNumber *ll); /* exported to jopprint.c (lab_xname_); */ extern void emitfl(J_OPCODE op, FileLine fl); extern void emitshift(J_OPCODE op, VRegnum r1, VRegnum r2, VRegnum r3, int32 m); extern void emitstring(J_OPCODE op, VRegnum r1, StringSegList *m); extern void emitbranch(J_OPCODE op, LabelNumber *m); extern void emitbinder(J_OPCODE op, VRegnum r1, Binder *m); extern void emitvk(J_OPCODE op, VRegnum r1, int32 n, Binder *m); extern void emitreg(J_OPCODE op, VRegnum r1, VRegnum r2, VRegnum m); extern void emitreg4(J_OPCODE op, int flags, VRegnum r1, VRegnum r2, VRegnum r3, VRegnum r4); extern void emitfloat(J_OPCODE op, VRegnum r1, VRegnum r2, FloatCon *m); extern void emitint64(J_OPCODE op, VRegnum r1, VRegnum r2, Int64Con *m); extern void emitsetsp(J_OPCODE op, BindList *b2); extern void emitsetspandjump(BindList *b2, LabelNumber *l); extern void emitcall(J_OPCODE op, VRegnum r1, int32 argwords, Binder *m); extern void emitcallreg(J_OPCODE op, VRegnum r1, int32 argwords, VRegnum m); extern void emitsetspgoto(BindList *r2, LabelNumber *m); extern void emitsetspenv(BindList *r2, BindList *m); extern void emitcasebranch(J_OPCODE op, VRegnum r1, LabelNumber **r2, int32 m); extern void emit(J_OPCODE op, VRegnum r1, VRegnum r2, int32 m); extern void emitic(const Icode *const ic); extern bool is_compare(J_OPCODE op); extern void lose_dead_code(void); extern void linearize_code(void); extern void flowgraph_reinit(void); #endif /* end of mip/flowgraf.h */
stardot/ncc
thumb/mcvsn.h
/* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #define MC_VERSION "500"
stardot/ncc
mip/cseeval.c
/* * mip/cseeval.c: CSE compile-time evaluation * Copyright (C) Acorn Computers Ltd., 1988. * Copyright 1991-1997 Advanced Risc Machines Limited. All rights reserved * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 0 * Checkin $Date$ * Revising $Author$ */ #include "globals.h" #include "aeops.h" #include "cgdefs.h" #include "jopcode.h" #include "builtin.h" /* for sim */ #include "errors.h" #include "cseguts.h" #include "ieeeflt2.h" #include "aetree.h" #include "sem.h" static bool IsLibraryFunction(Expr const *fn, Symstr const *sym) { return (bindstg_((Binder const *)fn) & bitofstg_(s_extern)) && bindsym_((Binder const *)fn) == sym; } static bool sdiv(int32 *resp, int32 a0, int32 a1) { /* nb arguments reversed from natural order */ if (a0 == 0) { cc_warn(sem_warn_divrem_0, s_div); return NO; } *resp = a1 / a0; return YES; } static bool srem(int32 *resp, int32 a0, int32 a1) { /* nb arguments reversed from natural order */ if (a0 == 0) { cc_warn(sem_warn_divrem_0, s_rem); return NO; } *resp = a1 % a0; return YES; } static bool udiv(int32 *resp, int32 a0, int32 a1) { /* nb arguments reversed from natural order */ a0 = just32bits_(a0); a1 = just32bits_(a1); if (a0 == 0) { cc_warn(sem_warn_divrem_0, s_div); return NO; } *resp = (int32)(((unsigned32)a1) / a0); return YES; } static bool urem(int32 *resp, int32 a0, int32 a1) { /* nb arguments reversed from natural order */ a0 = just32bits_(a0); a1 = just32bits_(a1); if (a0 == 0) { cc_warn(sem_warn_divrem_0, s_rem); return NO; } *resp = (int32)(((unsigned32)a1) % a0); return YES; } #ifndef TARGET_HAS_MULTIPLY static bool mul(int32 *resp, int32 a0, int32 a1) { *resp = a0 * a1; return YES; } #endif FloatCon *CSE_NewDCon(DbleBin const *val) { FloatCon *fc = real_of_string("<expr>", 0); fc->floatlen = ts_double; fc->floatbin.db = *val; return CSE_CanonicalFPConst(fc); } static FloatCon *D_Evaluated(DbleBin const *dr) { FloatCon *a = CSE_NewDCon(dr); if (debugging(DEBUG_CSE) && CSEDebugLevel(1)) cc_msg("Compile-time evaluable\n"); return a; } FloatCon *CSE_NewFCon(FloatBin const *val) { FloatCon *fc = real_of_string("<expr>", 0); fc->floatlen = ts_float; fc->floatbin.fb = *val; return CSE_CanonicalFPConst(fc); } static FloatCon *F_Evaluated(FloatBin const *fr) { FloatCon *a = CSE_NewFCon(fr); if (debugging(DEBUG_CSE) && CSEDebugLevel(1)) cc_msg("Compile-time evaluable\n"); return a; } Int64Con *CSE_NewLLCon(int64 const *ip) { Int64Con *lc = mkint64const(0, ip); return CSE_CanonicalLLConst(lc); } FloatCon *CSE_EvalUnary_F(J_OPCODE op, ExSet *ex) { J_OPCODE baseop = op & J_TABLE_BITS; ExSet *c1; DbleBin dr; FloatBin fr; bool done = NO; if ((c1 = MOVFKinSet(ex)) != NULL) { DbleBin d; if (baseop == J_NEGFR) { fltrep_widen(&e1f_(c1->exprn)->floatbin.fb, &d); if (flt_negate(&dr, &d) <= flt_ok) done = YES; } } else if ((c1 = MOVKinSet(ex)) != NULL) { if (baseop == J_FLTFR && flt_itod(&dr, e1k_(c1->exprn)) <= flt_ok) done = YES; } return (done && fltrep_narrow(&dr, &fr) <= flt_ok) ? F_Evaluated(&fr) : NULL; } FloatCon *CSE_EvalUnary_D(J_OPCODE op, ExSet *ex) { J_OPCODE baseop = op & J_TABLE_BITS; ExSet *c1; DbleBin dr; bool done = NO; if ((c1 = MOVDKinSet(ex)) != NULL) { if (baseop == J_NEGDR && flt_negate(&dr, &e1f_(c1->exprn)->floatbin.db) <= flt_ok) done = YES; } else if ((c1 = MOVKinSet(ex)) != NULL) { if (baseop == J_FLTDR && flt_itod(&dr, e1k_(c1->exprn)) <= flt_ok) done = YES; } return (done) ? D_Evaluated(&dr) : NULL; } #if defined TARGET_HAS_SCALED_ADDRESSING || defined TARGET_HAS_SCALED_OPS || \ defined TARGET_HAS_SCALED_ADD int32 ShiftedVal(J_OPCODE op, int32 b) { if (OpIsShifted(op)) { int32 msh = (op & J_SHIFTMASK) >> J_SHIFTPOS; if ((msh & SHIFT_RIGHT) == 0) b = b << (msh & SHIFT_MASK); else if (msh & SHIFT_ARITH) b = b >> (msh & SHIFT_MASK); else b = (int32) ((just32bits_((unsigned32)b)) >> (msh & SHIFT_MASK)); } if (op & J_NEGINDEX) b = -b; return widen32bitint_(b); } #endif bool CSE_EvalUnary_I(J_OPCODE op, int32 *resp, ExSet *ex) { J_OPCODE baseop = op & J_TABLE_BITS; ExSet *c1 = MOVKinSet(ex); int32 n; bool done = NO; if (c1 != NULL) { n = ShiftedVal(op, e1k_(c1->exprn)); switch (baseop) { case J_NOTR: n = ~n; break; case J_MOVR: n = n; break; case J_NEGR: n = -n; break; } done = YES; } else if (baseop == J_FIXFR && (c1 = MOVFKinSet(ex)) != NULL) { DbleBin d; fltrep_widen(&e1f_(c1->exprn)->floatbin.fb, &d); { int status = (op & J_UNSIGNED) ? flt_dtou((unsigned32 *)&n, &d) : flt_dtoi(&n, &d); done = status == flt_ok; } } else if (baseop == J_FIXDR && (c1 = MOVDKinSet(ex)) != NULL) { DbleBin *d = &e1f_(c1->exprn)->floatbin.db; { int status = (op & J_UNSIGNED) ? flt_dtou((unsigned32 *)&n, d) : flt_dtoi(&n, d); done = status == flt_ok; } } /* TODO: add FIXFRM / FIXDRM handling code here */ if (done) { if (debugging(DEBUG_CSE) && CSEDebugLevel(1)) cc_msg("Compile-time evaluable = %ld\n", n); *resp = widen32bitint_(n); } return done; } bool CSE_EvalBinary_I(J_OPCODE op, int32 *resp, Exprn *ax, int32 b) { int32 a, res; bool done = YES; if (exop_(ax) != J_MOVK) return NO; a = e1k_(ax); switch (op & J_TABLE_BITS) { case J_EXTEND:if (b == 0 || b == 1) res = (a & 0x80) ? a | ~0x7f : a & 0x7f; else res = (a & 0x8000) ? a | ~0x7fff : a & 0x7fff; break; case J_ADDK: res = a + b; break; case J_MULK: res = a * b; break; case J_ANDK: res = a & b; break; case J_ORRK: res = a | b; break; case J_EORK: res = a ^ b; break; case J_SUBK: res = a - b; break; case J_RSBK: res = b - a; break; case J_DIVK: done = op & J_UNSIGNED ? udiv(&res, b, a) : sdiv(&res, b, a); break; case J_REMK: done = op & J_UNSIGNED ? urem(&res, b, a) : srem(&res, b, a); break; #ifdef TARGET_LACKS_RIGHTSHIFT case J_SHLK: if (b >= 0) { res = a << b; break; } b = -b; /* fall through to shrk */ #else case J_SHLK: res = a << b; break; #endif case J_SHRK: res = (op & J_UNSIGNED) ? (int32) ((0xffffffff & (unsigned32) a) >> b) : TARGET_RIGHTSHIFT(a, b); break; #ifdef TARGET_HAS_ROTATE /* Hmm, ROLK is probably more common than RORK. */ case J_RORK: res = ((unsigned32)a << (32-b)) | ((0xffffffff & (unsigned32)a) >> b); break; #endif default: syserr(syserr_evalconst, (long)op); return NO; } res = widen32bitint_(res); if (done) *resp = res; if (done && debugging(DEBUG_CSE) && CSEDebugLevel(1)) cc_msg("Compile-time evaluable = %ld\n", (long int)res); return done; } FloatCon *CSE_EvalBinary_D(J_OPCODE op, ExSet *as, FloatCon const *b) { FloatCon *a; DbleBin db; int status; as = MOVDKinSet(as); if (as == NULL) return NULL; a = e1f_(as->exprn); switch (op) { case J_ADDDK: status = flt_add(&db, &a->floatbin.db, &b->floatbin.db); break; case J_MULDK: status = flt_multiply(&db, &a->floatbin.db, &b->floatbin.db); break; case J_SUBDK: status = flt_subtract(&db, &a->floatbin.db, &b->floatbin.db); break; case J_DIVDK: status = flt_divide(&db, &a->floatbin.db, &b->floatbin.db); break; default: syserr(syserr_evalconst, (long)op); return NULL; } return (status > flt_ok) ? NULL : D_Evaluated(&db); } static bool EvalBinary_F_1(J_OPCODE op, FloatBin const *a, FloatBin const *b, FloatBin *r) { DbleBin dr, da, db; int status; fltrep_widen(a, &da); fltrep_widen(b, &db); switch (op) { case J_ADDFK: status = flt_add(&dr, &da, &db); break; case J_MULFK: status = flt_multiply(&dr, &da, &db); break; case J_SUBFK: status = flt_subtract(&dr, &da, &db); break; case J_DIVFK: status = flt_divide(&dr, &da, &db); break; default: syserr(syserr_evalconst, (long)op); return NO; } if (status > flt_ok) return NO; if (fltrep_narrow(&dr, r) > flt_ok) return NO; return YES; } FloatCon *CSE_EvalBinary_F(J_OPCODE op, ExSet *as, FloatCon const *b) { FloatBin fr; as = MOVFKinSet(as); if (as == NULL) return NULL; { FloatCon *a = e1f_(as->exprn); return EvalBinary_F_1(op, &a->floatbin.fb, &b->floatbin.fb, &fr) ? F_Evaluated(&fr) : NULL; } } bool CSE_Compare_F(int *res, FloatBin const *a, FloatBin const *b) { /* Currently, flt_compare() can return only -1, 0, or 1 (all argument values are considered comparable). Code here anticipates an interface change which allows a 'not comparable' return value outside this set. */ DbleBin da, db; int r; fltrep_widen(a, &da); fltrep_widen(b, &db); r = flt_compare(&da, &db); if (!(-1 <= r && r <= 1)) return NO; *res = r; return YES; } bool CSE_Compare_D(int *res, FloatCon const *a, FloatCon const *b) { int r = flt_compare(&a->floatbin.db, &b->floatbin.db); if (!(-1 <= r && r <= 1)) return NO; *res = r; return YES; } #define RemoveInexact(s) ((s) == flt_inexact ? flt_bad : (s)) static int dpow(DbleBin *res, DbleBin const *a0, DbleBin const *a1) { int32 n1; int status; DbleBin t; if ((status = flt_dtoi(&n1, a1)) != flt_ok) return RemoveInexact(status); if ((status = flt_itod(&t, n1)) != flt_ok) return RemoveInexact(status); if (flt_compare(&t, a1) != 0) return flt_bad; if (!(-256 <= n1 && n1 <= 256)) return flt_bad; if (n1 == 0) { flt_itod(&t, 0); if (flt_compare(a0, &t) == 0) return flt_invalidop; return flt_itod(res, 1); } { int32 bit = 256; bool invert = NO; if (n1 < 0) { invert = YES; n1 = -n1; } *res = *a0; while (!(bit & n1)) bit = bit >> 1; bit = bit >> 1; for (; bit != 0; bit = bit >> 1) { if ((status = flt_multiply(res, res, res)) != flt_ok) return RemoveInexact(status); if (bit & n1) if ((status = flt_multiply(res, res, a0)) != flt_ok) return RemoveInexact(status); } if (invert) { flt_itod(&t, 1); return flt_divide(res, &t, res); } else return flt_ok; } } static Exprn *AdconXInSet(ExSet *s, int32 n, J_OPCODE adcon) { for (;; s = cdr_(s)) { Location *loc; s = ExSet_OpMember(s, J_LDRK, J_ALIGNMENT); if (s == NULL) return NULL; loc = exloc_(s->exprn); if (!(loctype_(loc) & LOC_anyVAR) && (exop_(locbase_(loc)) & ~J_BASEALIGN4) == adcon) return locoff_(loc) == n ? locbase_(loc) : NULL; } } static Exprn *ConstantWordxInSet(ExSet *s, J_OPCODE wordx) { for (; s != NULL && (s = ExSet_OpMember(s, wordx, 0)) != NULL; s = cdr_(s)) if (exop_(e1_(s->exprn)) == J_MOVDK) return e1_(s->exprn); return NULL; } static FloatCon *DoubleLoadedToIntPair(ExSet *a0s, ExSet *a1s) { if (software_doubles_enabled) { Exprn *adcond = AdconXInSet(a0s, 0, J_ADCOND); if (adcond != NULL && AdconXInSet(a1s, 4, J_ADCOND) == adcond) return e1f_(adcond); adcond = AdconXInSet(a0s, 0, J_ADCON); if (adcond != NULL) { Binder *b = e1b_(adcond); Expr *ex = bindconst_(b); if (ex != NULL && h0_(ex) == s_floatcon) { SET_BITMAP t = exf_(ex)->floatlen & ~CVBITS; if ((t == ts_double || t == ts_longdouble) && AdconXInSet(a1s, 4, J_ADCON) == adcond) return CSE_CanonicalFPConst(exf_(ex)); } } return NULL; } { Exprn *e0 = ConstantWordxInSet(a0s, CSE_WORD1); if (e0 != NULL) { Exprn *e1 = ConstantWordxInSet(a1s, CSE_WORD2); if (e0 == e1) return e1f_(e0); } } return NULL; } static Int64Con *LongLongLoadedToIntPair(ExSet *a0s, ExSet *a1s) { Exprn *adconll = AdconXInSet(a0s, 0, J_ADCONLL); if (adconll != NULL && AdconXInSet(a1s, 4, J_ADCONLL) == adconll) return e1i64_(adconll); adconll = AdconXInSet(a0s, 0, J_ADCON); if (adconll != NULL) { Binder *b = e1b_(adconll); Expr *ex = bindconst_(b); if (ex != NULL && h0_(ex) == s_int64con && AdconXInSet(a1s, 4, J_ADCON) == adconll) return CSE_CanonicalLLConst(exi64_(ex)); } return NULL; } static I64_Status i64_rsb(int64 *res, int64 const *a1, int64 const *a2) { return I64_SSub(res, a2, a1); } static I64_Status i64_sdiv(int64 *res, int64 const *a1, int64 const *a2) { int64 t; return I64_SDiv(res, &t, a1, a2); } static I64_Status i64_srdv(int64 *res, int64 const *a1, int64 const *a2) { int64 t; return I64_SDiv(res, &t, a2, a1); } static I64_Status i64_srem(int64 *res, int64 const *a1, int64 const *a2) { int64 t; return I64_SDiv(&t, res, a1, a2); } static I64_Status i64_srrem(int64 *res, int64 const *a1, int64 const *a2) { int64 t; return I64_SDiv(&t, res, a2, a1); } static I64_Status i64_udiv(int64 *res, int64 const *a1, int64 const *a2) { uint64 t; return I64_UDiv((uint64 *)res, &t, (uint64 const *)a1, (uint64 const *)a2); } static I64_Status i64_urdv(int64 *res, int64 const *a1, int64 const *a2) { uint64 t; return I64_UDiv((uint64 *)res, &t, (uint64 const *)a2, (uint64 const *)a1); } static I64_Status i64_urem(int64 *res, int64 const *a1, int64 const *a2) { uint64 t; return I64_UDiv(&t, (uint64 *)res, (uint64 const *)a1, (uint64 const *)a2); } static I64_Status i64_urrem(int64 *res, int64 const *a1, int64 const *a2) { uint64 t; return I64_UDiv(&t, (uint64 *)res, (uint64 const *)a2, (uint64 const *)a1); } static I64_Status i64_not(int64 *res, int64 const *a1) { I64_Not(res, a1); return i64_ok; } static I64_Status i64_and(int64 *res, int64 const *a1, int64 const *a2) { I64_And(res, a2, a1); return i64_ok; } static I64_Status i64_or(int64 *res, int64 const *a1, int64 const *a2) { I64_Or(res, a2, a1); return i64_ok; } static I64_Status i64_eor(int64 *res, int64 const *a1, int64 const *a2) { I64_Eor(res, a2, a1); return i64_ok; } #define Arg_D 0x10 #define Arg_DD 0x20 #define Arg_L 0x30 #define Arg_LL 0x40 #define Arg_LI 0x50 #define Res_D 0x60 #define Res_L 0x70 #define Arg_F 0x80 #define ArgCount 0xf typedef union { int (*dunaryu)(DbleBin *res, uint32 n); int (*dunaryi)(DbleBin *res, int32 n); int (*unaryd)(DbleBin *res, DbleBin const *a1); int (*binaryd)(DbleBin *res, DbleBin const *a1, DbleBin const *a2); void (*fwiden)(FloatBin const *a1, DbleBin *res); I64_Status (*lunaryu)(int64 *res, uint32 n); I64_Status (*lunaryi)(int64 *res, int32 n); I64_Status (*unaryl)(int64 *res, int64 const *a1); I64_Status (*binaryll)(int64 *res, int64 const *a1, int64 const *a2); I64_Status (*binaryli)(int64 *res, int64 const *a1, Uint a2); I64_Status (*binarylui)(uint64 *res, uint64 const *a1, Uint a2); } FPEvalFn; static int32 EvaluableDoubleValuedFn(Expr const *fn, VRegnum res, FPEvalFn *ev) { if (IsLibraryFunction(fn, sim.dabs)) { ev->unaryd = flt_abs; return 2+Arg_D; } if (IsLibraryFunction(fn, sim.dfloor)) { ev->unaryd = flt_floor; return 2+Arg_D; } if (IsLibraryFunction(fn, sim.dceil)) { ev->unaryd = flt_ceil; return 2+Arg_D; } if (IsLibraryFunction(fn, sim.dpow)) { ev->binaryd = dpow; return 4+Arg_DD; } if (IsLibraryFunction(fn, sim.dmod)) { ev->binaryd = flt_fmod; return 4+Arg_DD; } if (fn == sim.dfloat) { ev->dunaryi = flt_itod; return 1+Res_D; } if (fn == sim.dfloatu) { ev->dunaryu = flt_utod; return 1+Res_D; } if (fn == sim.dwiden) { ev->fwiden = fltrep_widen; return 1+Arg_F; } if (fn == sim.dnegate) { ev->unaryd = flt_negate; return 2+Arg_D; } if (fn == sim.dadd) { ev->binaryd = flt_add; return 4+Arg_DD; } if (fn == sim.dsubtract) { ev->binaryd = flt_subtract; return 4+Arg_DD; } if (fn == sim.dmultiply) { ev->binaryd = flt_multiply; return 4+Arg_DD; } if (fn == sim.ddivide) { ev->binaryd = flt_divide; return 4+Arg_DD; } if (fn == sim.llnot) { ev->unaryl = i64_not; return 2+Arg_L; } if (fn == sim.llneg) { ev->unaryl = I64_Neg; return 2+Arg_L; } if (fn == sim.lladd) { ev->binaryll = I64_SAdd; return 4+Arg_LL; } if (fn == sim.llsub) { ev->binaryll = I64_SSub; return 4+Arg_LL; } if (fn == sim.llrsb) { ev->binaryll = i64_rsb; return 4+Arg_LL; } if (fn == sim.llmul) { ev->binaryll = I64_SMul; return 4+Arg_LL; } if (fn == sim.llsdiv) { ev->binaryll = res == R_A1 ? i64_sdiv : i64_srem; return 4+Arg_LL; } if (fn == sim.llsrdv) { ev->binaryll = res == R_A1 ? i64_srdv : i64_srrem; return 4+Arg_LL; } if (fn == sim.lludiv) { ev->binaryll = res == R_A1 ? i64_udiv : i64_urem; return 4+Arg_LL; } if (fn == sim.llurdv) { ev->binaryll = res == R_A1 ? i64_urdv : i64_urrem; return 4+Arg_LL; } if (fn == sim.lland) { ev->binaryll = i64_and; return 4+Arg_LL; } if (fn == sim.llor) { ev->binaryll = i64_or; return 4+Arg_LL; } if (fn == sim.lleor) { ev->binaryll = i64_eor; return 4+Arg_LL; } if (fn == sim.llfroml) { ev->lunaryi = I64_IToS; return 1+Res_L; } if (fn == sim.llshiftl) { ev->binaryli = I64_Lsh; return 3+Arg_LI; } if (fn == sim.llushiftr) { ev->binarylui = I64_URsh; return 3+Arg_LI; } if (fn == sim.llsshiftr) { ev->binaryli = I64_SRsh; return 3+Arg_LI; } return 0; } bool CSE_EvaluableDoubleValuedCall( Expr const *fn, VRegnum res, int32 argres, ExSet *arg[], DRes *dresp) { FPEvalFn op; int32 args = EvaluableDoubleValuedFn(fn, res, &op); bool done = NO; if (args == 0) return NO; if (argres & K_RESULTINFLAGS) return NO; if ((args & ArgCount) == k_argregs_(argres)) switch(args) { case 1+Res_D: if (!k_argisfp_(argres, 0) && arg[0] != NULL) { ExSet *c0 = MOVKinSet(arg[0]); done = (c0 != NULL && op.dunaryi(&dresp->val.d, e1k_(c0->exprn)) <= flt_ok); dresp->isdouble = YES; } break; case 1+Arg_F: if (!k_argisfp_(argres, 0) && arg[0] != NULL) { ExSet *c0 = MOVKinSet(arg[0]); if (c0 != NULL) { FloatBin fb; fb.val = e1k_(c0->exprn); op.fwiden(&fb, &dresp->val.d); done = dresp->isdouble = YES; } } break; case 2+Arg_D: if ( !k_argisfp_(argres, 0) && arg[0] != NULL && !k_argisfp_(argres, 1) && arg[1] != NULL) { FloatCon *a0 = DoubleLoadedToIntPair(arg[0], arg[1]); done = (a0 != NULL && op.unaryd(&dresp->val.d, &a0->floatbin.db) <= flt_ok); dresp->isdouble = YES; } break; case 4+Arg_DD: if ( !k_argisfp_(argres, 0) && arg[0] != NULL && !k_argisfp_(argres, 1) && arg[1] != NULL && !k_argisfp_(argres, 2) && arg[2] != NULL && !k_argisfp_(argres, 3) && arg[3] != NULL) { FloatCon *a0 = DoubleLoadedToIntPair(arg[0], arg[1]); FloatCon *a1 = DoubleLoadedToIntPair(arg[2], arg[3]); done = (a0 != NULL && a1 != NULL && op.binaryd(&dresp->val.d, &a0->floatbin.db, &a1->floatbin.db) <= flt_ok); dresp->isdouble = YES; } break; case 1+Res_L: if (!k_argisfp_(argres, 0) && arg[0] != NULL) { ExSet *c0 = MOVKinSet(arg[0]); done = (c0 != NULL && op.lunaryi(&dresp->val.i, e1k_(c0->exprn))); dresp->isdouble = NO; } break; case 2+Arg_L: if ( !k_argisfp_(argres, 0) && arg[0] != NULL && !k_argisfp_(argres, 1) && arg[1] != NULL) { Int64Con *a0 = LongLongLoadedToIntPair(arg[0], arg[1]); done = (a0 != NULL && op.unaryl(&dresp->val.i, &a0->bin.i) == i64_ok); dresp->isdouble = NO; } break; case 3+Arg_LI: if ( !k_argisfp_(argres, 0) && arg[0] != NULL && !k_argisfp_(argres, 1) && arg[1] != NULL && !k_argisfp_(argres, 2) && arg[2] != NULL) { Int64Con *a0 = LongLongLoadedToIntPair(arg[0], arg[1]); ExSet *c1 = MOVKinSet(arg[2]); done = (a0 != NULL && c1 != NULL && op.binaryli(&dresp->val.i, &a0->bin.i, (Uint)e1k_(c1->exprn)) == i64_ok); dresp->isdouble = NO; } break; case 4+Arg_LL: if ( !k_argisfp_(argres, 0) && arg[0] != NULL && !k_argisfp_(argres, 1) && arg[1] != NULL && !k_argisfp_(argres, 2) && arg[2] != NULL && !k_argisfp_(argres, 3) && arg[3] != NULL) { Int64Con *a0 = LongLongLoadedToIntPair(arg[0], arg[1]); Int64Con *a1 = LongLongLoadedToIntPair(arg[2], arg[3]); done = (a0 != NULL && a1 != NULL && op.binaryll(&dresp->val.i, &a0->bin.i, &a1->bin.i) == i64_ok); dresp->isdouble = NO; } break; } if (done && debugging(DEBUG_CSE) && CSEDebugLevel(1)) { cc_msg("Compile-time evaluable fn = "); if (dresp->isdouble) { char b[256]; fltrep_sprintf(b, "%g", &dresp->val.d); cc_msg("%s\n", b); } else { pr_int64(&dresp->val.i); cc_msg("\n"); } } return done; } static bool fadd(int32 *resp, int32 a0, int32 a1) { return EvalBinary_F_1(J_ADDFK, (FloatBin *)&a0, (FloatBin *)&a1, (FloatBin *)resp); } static bool fsub(int32 *resp, int32 a0, int32 a1) { return EvalBinary_F_1(J_SUBFK, (FloatBin *)&a0, (FloatBin *)&a1, (FloatBin *)resp); } static bool fmul(int32 *resp, int32 a0, int32 a1) { return EvalBinary_F_1(J_MULFK, (FloatBin *)&a0, (FloatBin *)&a1, (FloatBin *)resp); } static bool fdiv(int32 *resp, int32 a0, int32 a1) { return EvalBinary_F_1(J_DIVFK, (FloatBin *)&a0, (FloatBin *)&a1, (FloatBin *)resp); } static bool fgreater(int32 *resp, int32 a0, int32 a1) { int r; if (CSE_Compare_F(&r, (FloatBin *)&a0, (FloatBin *)&a1)) { *resp = (r > 0); return YES; } return NO; } static bool fgeq(int32 *resp, int32 a0, int32 a1) { int r; if (CSE_Compare_F(&r, (FloatBin *)&a0, (FloatBin *)&a1)) { *resp = (r >= 0); return YES; } return NO; } static bool fless(int32 *resp, int32 a0, int32 a1) { int r; if (CSE_Compare_F(&r, (FloatBin *)&a0, (FloatBin *)&a1)) { *resp = (r < 0); return YES; } return NO; } static bool fleq(int32 *resp, int32 a0, int32 a1) { int r; if (CSE_Compare_F(&r, (FloatBin *)&a0, (FloatBin *)&a1)) { *resp = (r <= 0); return YES; } return NO; } static bool fequal(int32 *resp, int32 a0, int32 a1) { int r; if (CSE_Compare_F(&r, (FloatBin *)&a0, (FloatBin *)&a1)) { *resp = (r == 0); return YES; } return NO; } static bool fneq(int32 *resp, int32 a0, int32 a1) { int r; if (CSE_Compare_F(&r, (FloatBin *)&a0, (FloatBin *)&a1)) { *resp = (r != 0); return YES; } return NO; } static bool fneg(int32 *resp, int32 a0) { DbleBin dr, da; fltrep_widen((FloatBin *)&a0, &da); return (flt_negate(&dr, &da) == flt_ok && fltrep_narrow(&dr, (FloatBin *)resp) == flt_ok); } static bool fnarrow(int32 *resp, FloatCon const *a0) { return fltrep_narrow(&a0->floatbin.db, (FloatBin *)resp) == flt_ok; } static bool ffix(int32 *resp, int32 a0) { DbleBin da; fltrep_widen((FloatBin *)&a0, &da); return (flt_dtoi(resp, &da) == flt_ok); } static bool ffixu(int32 *resp, int32 a0) { DbleBin da; fltrep_widen((FloatBin *)&a0, &da); return (flt_dtou((unsigned32 *)resp, &da) == flt_ok); } static bool ffloat(int32 *resp, int32 a0) { DbleBin dr; return (flt_itod(&dr, a0) == flt_ok && fltrep_narrow(&dr, (FloatBin *)resp) == flt_ok); } static bool ffloatu(int32 *resp, int32 a0) { DbleBin dr; return (flt_utod(&dr, a0) == flt_ok && fltrep_narrow(&dr, (FloatBin *)resp) == flt_ok); } static bool dgreater(int32 *resp, FloatCon const *a0, FloatCon const *a1) { int r; if (CSE_Compare_D(&r, a0, a1)) { *resp = (r > 0); return YES; } return NO; } static bool dgeq(int32 *resp, FloatCon const *a0, FloatCon const *a1) { int r; if (CSE_Compare_D(&r, a0, a1)) { *resp = (r >= 0); return YES; } return NO; } static bool dless(int32 *resp, FloatCon const *a0, FloatCon const *a1) { int r; if (CSE_Compare_D(&r, a0, a1)) { *resp = (r < 0); return YES; } return NO; } static bool dleq(int32 *resp, FloatCon const *a0, FloatCon const *a1) { int r; if (CSE_Compare_D(&r, a0, a1)) { *resp = (r <= 0); return YES; } return NO; } static bool dequal(int32 *resp, FloatCon const *a0, FloatCon const *a1) { int r; if (CSE_Compare_D(&r, a0, a1)) { *resp = (r == 0); return YES; } return NO; } static bool dneq(int32 *resp, FloatCon const *a0, FloatCon const *a1) { int r; if (CSE_Compare_D(&r, a0, a1)) { *resp = (r != 0); return YES; } return NO; } static bool dfix(int32 *resp, FloatCon const *a0) { return flt_dtoi(resp, &a0->floatbin.db) == flt_ok; } static bool dfixu(int32 *resp, FloatCon const *a0) { return flt_dtou((unsigned32 *)resp, &a0->floatbin.db) == flt_ok; } typedef union { bool (*unaryi)(int32 *, int32); bool (*binaryi)(int32 *, int32, int32); bool (*unaryd)(int32 *, FloatCon const *); bool (*binaryd)(int32 *, FloatCon const *, FloatCon const *); } EvalFn; static int32 EvaluableIntValuedFn(Expr const *fn, VRegnum res, EvalFn *ev) { #ifndef TARGET_HAS_DIVIDE if (fn == arg1_(sim.divfn)) { ev->binaryi = res == R_A1 ? sdiv : srem; return 2; } if (fn == arg1_(sim.udivfn)) { ev->binaryi = res == R_A1 ? udiv : urem; return 2; } #endif #if defined(TARGET_LACKS_REMAINDER) || !defined(TARGET_HAS_DIVIDE) if (fn == arg1_(sim.remfn)) { ev->binaryi = srem; return 2; } if (fn == arg1_(sim.uremfn)) { ev->binaryi = urem; return 2; } #endif #ifndef TARGET_HAS_MULTIPLY if (fn == arg1_(sim.mulfn)) { ev->binaryi = mul; return 2; } #endif if (fn == sim.fadd) { ev->binaryi = fadd; return 2; } if (fn == sim.fsubtract) { ev->binaryi = fsub; return 2; } if (fn == sim.fmultiply) { ev->binaryi = fmul; return 2; } if (fn == sim.fdivide) { ev->binaryi = fdiv; return 2; } if (fn == sim.fnegate) { ev->unaryi = fneg; return 1; } if (fn == sim.ffix) { ev->unaryi = ffix; return 1; } if (fn == sim.ffixu) { ev->unaryi = ffixu; return 1; } if (fn == sim.ffloat) { ev->unaryi = ffloat; return 1; } if (fn == sim.ffloatu) { ev->unaryi = ffloatu; return 1; } if (fn == sim.fgreater) { ev->binaryi = fgreater; return 2; } if (fn == sim.fgeq) { ev->binaryi = fgeq; return 2; } if (fn == sim.fless) { ev->binaryi = fless; return 2; } if (fn == sim.fleq) { ev->binaryi = fleq; return 2; } if (fn == sim.fequal) { ev->binaryi = fequal; return 2; } if (fn == sim.fneq) { ev->binaryi = fneq; return 2; } if (fn == sim.dfix) { ev->unaryd = dfix; return 2+Arg_D; } if (fn == sim.dfixu) { ev->unaryd = dfixu; return 2+Arg_D; } if (fn == sim.fnarrow) { ev->unaryd = fnarrow; return 2+Arg_D; } if (fn == sim.dgreater) { ev->binaryd = dgreater; return 4+Arg_DD; } if (fn == sim.dgeq) { ev->binaryd = dgeq; return 4+Arg_DD; } if (fn == sim.dless) { ev->binaryd = dless; return 4+Arg_DD; } if (fn == sim.dleq) { ev->binaryd = dleq; return 4+Arg_DD; } if (fn == sim.dequal) { ev->binaryd = dequal; return 4+Arg_DD; } if (fn == sim.dneq) { ev->binaryd = dneq; return 4+Arg_DD; } return 0; } bool CSE_EvaluableIntValuedCall( Expr const *fn, VRegnum res, int32 argres, ExSet *arg[], int32 *resp) { /* If fn is an integer-valued function (including float-valued if software * floating point) in the set we know how to evaluate, and this call has * constant arguments, see whether we can evaluate the call now (we may * not be able to, as for example in div(1, 0)) */ EvalFn op; int32 args = EvaluableIntValuedFn(fn, res, &op); bool done = NO; if (args == 0) return NO; if (argres & K_RESULTINFLAGS) return NO; if ((args & ArgCount) == k_argregs_(argres) && !k_argisfp_(argres, 0) && arg[0] != NULL) switch(args) { case 1: { ExSet *c0 = MOVKinSet(arg[0]); done = (c0 != 0 && op.unaryi(resp, e1k_(c0->exprn))); } break; case 2: if (!k_argisfp_(argres,1) && arg[1] != NULL) { ExSet *c0 = MOVKinSet(arg[0]); ExSet *c1 = MOVKinSet(arg[1]); done = (c0 != 0 && c1 != 0 && op.binaryi(resp, e1k_(c0->exprn), e1k_(c1->exprn))); } break; case 2+Arg_D: if (!k_argisfp_(argres,1) && arg[1] != NULL) { FloatCon *a0 = DoubleLoadedToIntPair(arg[0], arg[1]); done = (a0 != NULL && op.unaryd(resp, a0)); } break; case 4+Arg_DD: if (!k_argisfp_(argres,1) && arg[1] != NULL && !k_argisfp_(argres,2) && arg[2] != NULL && !k_argisfp_(argres,3) && arg[3] != NULL) { FloatCon *a0 = DoubleLoadedToIntPair(arg[0], arg[1]); FloatCon *a1 = DoubleLoadedToIntPair(arg[2], arg[3]); done = (a0 != NULL && a1 != NULL && op.binaryd(resp, a0, a1)); } break; } if (done && debugging(DEBUG_CSE) && CSEDebugLevel(1)) cc_msg("Compile-time evaluable fn = %ld\n", *resp); return done; } /* end of mip/cseeval.c */
stardot/ncc
thumb/tgen.c
/* C compiler file thumb/gen.c : Copyright (C) Codemist Ltd, 1994. */ /* SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ /* exports: void show_instruction(Icode *ic); RealRegister local_base(Binder *b); int32 local_address(Binder *b); bool immed_cmp(int32); bool fpliteral(FloatCon *val, J_OPCODE op); also (unfortunately for peephole): void setlabel(LabelNumber *); void branch_round_literals(LabelNumber *); */ #ifdef __STDC__ # include <string.h> #else # include <strings.h> #endif #include <assert.h> #include <stdlib.h> #define DEFINE_A_JOPTABLE 1 #include "globals.h" #include "builtin.h" #include "mcdep.h" #include "target.h" #include "mcdpriv.h" #include "xrefs.h" #include "ops.h" #include "jopcode.h" #include "store.h" #include "codebuf.h" #include "regalloc.h" #include "cg.h" /* for procflags, greatest_stackdepth */ #include "simplify.h" /* for MCR_SIZE_MASK */ #include "errors.h" #include "bind.h" #include "aeops.h" #include "arminst.h" #define NONLEAF (PROC_ARGPUSH | PROC_ARGADDR | PROC_BIGSTACK | BLKCALL) /* STACKCHECK (NONLEAF subset) defines when stack check is REALLY needed */ #define STACKCHECK (PROC_BIGSTACK | BLKCALL) #define ARGS2STACK (PROC_ARGPUSH | PROC_ARGADDR) #define IS_VARIADIC(m) ((m) == 0xfff) #define USES_BL_AS_B 1 #define ALL_REGS (0xffff) #define NoRegister ((RealRegister)-1) #define disable_opt (gen_opt_disabled) static int32 firstargoff; static int32 fp_minus_sp; typedef struct Branch { struct Branch *cdr; int32 codep; int32 condition; LabelNumber *dest; } Branch; Branch *available_branches; #define FREF_BRANCH 0 #define FREF_DCB 1 #define FREF_DCW 2 #define FREF_CONDITION(x) ((x) & 0xffff0000) #define FREF_TYPE(x) ((x) & 0xff) typedef struct FRef_Branch { struct FRef_Branch *cdr; int32 pcref; int32 codep; int32 flags; LabelNumber *real_dest; LabelNumber *chained_dest; } FRef_Branch; int32 mustbranchlitby = 0x10000000; int32 mustlitby = 0x10000000; static bool in_code; static int32 literal_pool_start; static int literal_pool_number; FRef_Branch *fref_branches; FRef_Branch **fref_branches_head; int32 branchpoolsize; static LabelNumber *returnlab; static LabelNumber *entrylab; /* 'spareregs' is a mask of the free regs at the start of the current opcode passed * to show instruction. * 'nspareregs' is the mask of the free regs when is opcode is finished. */ static int32 spareregs, nspareregs; #define AddCodeXref3(t, n) (codexrefs = (CodeXref *)global_list3(SU_Xref, codexrefs, t, n)) #define AddCodeXref4(t, n, x) (codexrefs = (CodeXref *)global_list4(SU_Xref, codexrefs, t, n, x)) #define AddCodeXref5(t, n, x, y) (codexrefs = (CodeXref *)global_list5(SU_Xref, codexrefs, t, n, x, y)) bool immed_cmp(int32 n) { return n >= 0 && n <= 0xff; } int integer_load_max; int ldm_regs_max; static LabelNumber *deadcode; static Symstr *call_via[8]; static Symstr *t_sym; #if 0 #undef addfref_ static void addfref_(LabelNumber *l, int32 v) { fprintf(stderr, "%.8x: (addfref_ @ %08x) F%dL%d\n", codebase + codep, v, current_procnum, lab_name_(l) & 0xfffff); l->u.frefs = (List *)binder_icons2((l)->u.frefs,(v)); } #endif RealRegister local_base(Binder const *b) { IGNORE(b); return R_SP; } static int32 c_of_q(int32 q) { switch (q & ~Q_UBIT) { case Q_EQ & ~Q_UBIT: return C_EQ; case Q_NE & ~Q_UBIT: return C_NE; case Q_HS & ~Q_UBIT: return C_HS; case Q_LO & ~Q_UBIT: return C_LO; case Q_PL & ~Q_UBIT: return C_PL; case Q_MI & ~Q_UBIT: return C_MI; case Q_HI & ~Q_UBIT: return C_HI; case Q_LS & ~Q_UBIT: return C_LS; case Q_GE & ~Q_UBIT: return C_GE; case Q_LT & ~Q_UBIT: return C_LT; case Q_GT & ~Q_UBIT: return C_GT; case Q_LE & ~Q_UBIT: return C_LE; case Q_AL & ~Q_UBIT: return C_AL; default: syserr("Unknown condition %lx", q); return 0; } } static int32 procmask; /* int regs to restore. */ static int32 pushed_args; static bool stack_args_split; static bool pushed_lr; static int32 r_fr; static int32 intsavewordsbelowfp, argwordsbelowfp, realargwordsbelowfp; #ifdef TARGET_HAS_FP_OFFSET_TABLES static struct { ProcFPDesc desc; FPList **tail; int32 offset; } fpd; static void fpdesc_init(void) { fpd.desc.fplist = NULL; fpd.tail = &fpd.desc.fplist; fpd.desc.startaddr = codebase+codep; fpd.desc.saveaddr = -1; fpd.desc.codeseg = bindsym_(codesegment); fpd.desc.initoffset = fpd.offset = -4; /* Ensure fpdesc_newsp gets the correct offset if called before routine_entry */ intsavewordsbelowfp = 0; realargwordsbelowfp = 0; argwordsbelowfp = 0; } static void fpdesc_enterproc(void) { fpd.desc.saveaddr = codebase+codep; } static void fpdesc_setinitoffset(int32 n) { fpd.desc.initoffset = fpd.offset = n; } static void fpdesc_endproc(void) { fpd.desc.endaddr = codebase+codep; if (fpd.desc.fplist != NULL) obj_notefpdesc(&fpd.desc); } static void fplist_add(int32 n) { FPList *p = (FPList *)SynAlloc(sizeof(FPList)); cdr_(p) = NULL; p->addr = codebase+codep; p->change = n; *fpd.tail = p; fpd.tail = &cdr_(p); fpd.offset += n; } static void fpdesc_notespchange(int32 n) { fplist_add(n); } static void fpdesc_newsp(int32 n) { n += 4*(intsavewordsbelowfp + realargwordsbelowfp) - 4; if (n - fpd.offset != 0) fplist_add(n - fpd.offset); } #else #define fpdesc_init() 0 #define fpdesc_newsp(n) 0 #define fpdesc_setinitoffset(n) 0 #define fpdesc_enterproc() 0 #define fpdesc_endproc() 0 #endif int32 local_address(Binder const *b) { int32 p = bindaddr_(b); int32 n = p & ~BINDADDR_MASK; #if 0 printf("BINDADDR = %x/%d for %s\n", p, p & ~BINDADDR_MASK, symname_(bindsym_(b))); #endif switch (p & BINDADDR_MASK) { default: syserr("local_address %lx", (long)p); case BINDADDR_LOC: return fp_minus_sp - n; case BINDADDR_ARG: if (stack_args_split) { if (n < NARGREGS * 4) { return fp_minus_sp + n; } else { return fp_minus_sp + firstargoff - NARGREGS * 4 + n; } } return fp_minus_sp + firstargoff + (p & ~BINDADDR_MASK); } } int32 local_fpaddress(Binder const *b) { int32 p = bindaddr_(b); int32 n = p & ~BINDADDR_MASK; switch (p & BINDADDR_MASK) { case BINDADDR_LOC: n = -(n + 4 * (intsavewordsbelowfp + realargwordsbelowfp)); break; case BINDADDR_ARG: n = (n >= 4*argwordsbelowfp) ? (n - 4 * argwordsbelowfp) : (n - 4 * (realargwordsbelowfp + intsavewordsbelowfp)); break; default: syserr(syserr_debug_addr); break; } return n+4; } RealRegister local_fpbase(Binder const *b) { IGNORE(b); return R_NOFPREG; } int32 power_of_two(int32 n) { /* If n is an exact power of two this returns the power, else -1 */ int32 s = 0, w; if (n != (n&(-n))) return(-1); for(w=1; w!=0; w = w<<1) if (w==n) return(s); else s++; return (-1); } static int32 casebranch_litpool = 0; static int32 casebranch_pending = -1; static int32 casebranch_pending_m; static int32 casebranch_codep; #define USE_DCB_FOR_CASEBRANCH 32 #define USE_DCW_FOR_CASEBRANCH 64 #define use_dcw use_bl static int use_bl; static void outDCB(unsigned32 w) { if (w & ~0xffL) syserr("outDCB(%lx)", (long)w); if ((codep & 3) == 0) { outcodeword(0, LIT_OPCODE); codep -= 4; /* ensure room */ } if ((codep & 1) == 0) code_flag_(codep) = LIT_BB; code_byte_(codep) = w; codep += 1; } static void outDCW(unsigned32 w) { if (w & ~0xffffL) syserr("outDCB(%lx)", (long)w); if (codep & 1) outDCB(0); if ((codep & 2) == 0) { outcodeword(0, LIT_OPCODE); codep -= 4; /* ensure room */ } code_flag_(codep) = LIT_H; code_hword_(codep) = w; codep += 2; } static void outHW(unsigned32 w) { if (w & ~0xffffL) syserr("outHW(%lx)", (long)w); if (codep & 1) outDCB(0); if ((codep & 2) == 0) { outcodeword(0, LIT_OPCODE); codep -= 4; /* ensure room */ } code_hword_(codep) = w; codep += 2; } static void outHWaux(unsigned32 w, void *s) { if (w & ~0xffffL) syserr("outHW(%lx)", (long)w); if (codep & 1) outDCB(0); if ((codep & 2) == 0) { outcodeword(0, LIT_OPCODE); codep -= 4; /* ensure room */ } code_hword_(codep) = (unsigned16)w; /* * To ensure that I have room here for the information needed I have to be * clear that consecutive instructions may NOT both contain an AUX entry. */ #ifndef NO_ASSEMBLER_OUTPUT if (asmstream) code_aux_(codep & (-2)) = s; #endif codep += 2; } typedef struct LDM_STM { int32 op; /* 0 / F_LDRI5 / F_STRI5 */ int32 base; /* Base reg */ int32 mask; int32 reg_off[8]; /* Offset from base of each reg loaded, -ve => not loaded */ } LDM_STM; static LDM_STM ldm_stm; #define CLM_MAX 16 typedef struct CLM { int32 z_reg; int32 base; int32 n; int32 offset[CLM_MAX]; } CLM; static CLM clm; #define REGV_UNKNOWN 0 /* Contents of reg are unknown */ #define REGV_CONSTANT 1 /* Register contains a constant */ #define REGV_BASE 2 /* Register contains reg + offset */ #define REGV_ADCON 3 /* Register contains adcon + offset */ typedef struct RegValue { char typ; int32 reg; Symstr *name; int32 value; } RegValue; static int32 pending_regs; static RegValue reg_values[16]; /* Set to a value to indicate the register which last affected the N & Z flags */ static RealRegister flags_reg; /* Set if the flags should have been set as the result of a cmp <flags_reg>, #0 * which was elided. * This is necessary if one of BCC, BCS, BVS, BVC, BHI, BLS, BGE, BLT, BGT or BLE * is issued in which case we must perform the following transformations * BCC, BCS, BVS, BVC -> ??? (syserr probably as this should never happen) * BHI -> BNE * BLS -> BEQ * BGE -> BPL * BLT -> BMI * BGT, BLE -> Reinsert CMP <flags_reg>, #0 */ static int cmpz_flag; static uint32 andk_flag; static RealRegister cmp_reg; static int32 cmp_value; static void outop(int32 op, int32 r1, int32 r2, int32 m); static int outop0(int32 op, int32 r1, int32 r2, int32 m); static void outop2(int32 op, int32 r1, int32 r2, int32 m); static void outop_direct(int32 op, int32 r1, int32 r2, int32 m); static void flush_spareregs(int32 mask); static void flush_pending(int32 mask); static void check_pending(int32 op, int32 r1, int32 r2, int32 m, int nospcheck); int32 CheckSWIValue(int32 n) { if ((uint32)n > 0xff) { cc_err(gen_err_swi, n); n = 0xff; } return n; } #define InstructionFieldOverflow(op, r1, r2, m) \ syserr("Instruction field overflow, op = %x, r1 = %x, r2 = %x, m = %x",\ (int)(op), (int)(r1), (int)(r2), (int)(m)) static void outop_direct(int32 op, int32 r1, int32 r2, int32 m) { int32 spchange = 0; int i; #if 0 if (!(disable_opt)) { switch (op) { case F_CMP: case F_CMN: if (reg_values[m].typ == REGV_CONSTANT) { cmp_reg = r2; cmp_value = reg_values[m].value; if (op == F_CMN) cmp_value = -cmp_value; } else cmp_reg = NoRegister; flags_reg = NoRegister; cmpz_flag = 0; andk_flag = 0; break; case F_CMP8: andk_flag = 0; cmp_reg = r1; cmp_value = m; if (m == 0) { if (r1 == flags_reg) { cmpz_flag = 1; return; } else flags_reg = r1; } else flags_reg = NoRegister; cmpz_flag = 0; break; case F_ADDI8: case F_SUBI8: case F_ADDI3: case F_SUBI3: case F_ADD3R: case F_SUB3R: case F_LSLK: case F_LSRK: case F_ASRK: case F_MOV8: cmp_reg = r1; cmp_value = 0; flags_reg = r1; cmpz_flag = 0; andk_flag = 0; reg_values[r1].typ = REGV_UNKNOWN; if (pending_regs & (1L << r1)) syserr("op = %.4x: R%d pending", (int)op, (int)r1); break; case F_LDRSP: case F_LDRLIT: case F_ADDRPC: case F_ADDRSP: if (flags_reg == r1) { cmp_reg = NoRegister; flags_reg = NoRegister; } reg_values[r1].typ = REGV_UNKNOWN; if (pending_regs & (1L << r1)) syserr("op = %.4x: R%d pending", (int)op, (int)r1); break; case F_AND: case F_OR: case F_EOR: case F_BIC: case F_NEG: case F_MUL: case F_MVN: case F_LSL: case F_LSR: case F_ASR: case F_ROR: case F_ADC: case F_SBC: cmp_reg = r2; cmp_value = 0; flags_reg = r2; cmpz_flag = 0; andk_flag = 0; case F_MOVHL: case F_ADDHL: reg_values[r2].typ = REGV_UNKNOWN; if (pending_regs & (1L << r2)) syserr("op = %.4x: R%d pending", (int)op, (int)r2); break; case F_LDRHADDR: case F_LDSBADDR: case F_LDSHADDR: case F_LDRHI5: case F_LDRADDR: case F_LDRBADDR: case F_LDRI5: case F_LDRBI5: if (flags_reg == r2) { cmp_reg = NoRegister; flags_reg = NoRegister; } reg_values[r2].typ = REGV_UNKNOWN; if (pending_regs & (1L << r2)) syserr("op = %.4x: R%d pending", (int)op, (int)r2); break; case F_LDM: case F_STM: case F_POP: case F_PUSH: if (op == F_POP || op == F_PUSH) r1 = R_SP; reg_values[r1].typ = REGV_UNKNOWN; if (pending_regs & (1L << r1)) syserr("op = %.4x: R%d pending", (int)op, (int)r1); if (op == F_LDM || op == F_POP) { for (i = 0; i < 8; i++) { if (m & (1L << i)) { if (flags_reg == i) { cmp_reg = NoRegister; flags_reg = NoRegister; } reg_values[i].typ = REGV_UNKNOWN; if (pending_regs & (1L << i)) syserr("op = %.4x: R%d pending", (int)op, (int)i); } } } break; case F_ADDSP: case F_SUBSP: reg_values[R_SP].typ = REGV_UNKNOWN; if (pending_regs & (1 << R_SP)) syserr("op = %.4x: R%d pending", (int)op, R_SP); break; } } switch (op) { case F_ADDI3: case F_SUBI3: case F_ADD3R: case F_SUB3R: if ((unsigned32)m > 7) syserr("Instruction field overflow, op = %x, r1 = %x, r2 = %x, m = %x", (int)op, (int)r1, (int)r2, (int)m); case F_LSLK: case F_LSRK: case F_ASRK: if ((unsigned32)m > 31 || (unsigned32)r1 > 7 || (unsigned32)r2 > 7) syserr("Instruction field overflow, op = %x, r1 = %x, r2 = %x, m = %x", (int)op, (int)r1, (int)r2, (int)m); op |= (m << 6) | (r2 << 3) | r1; break; case F_STRHADDR: case F_LDRHADDR: case F_LDSBADDR: case F_LDSHADDR: case F_STRADDR: case F_STRBADDR: case F_LDRADDR: case F_LDRBADDR: if ((unsigned32)m > 7) syserr("Instruction field overflow, op = %x, r1 = %x, r2 = %x, m = %x", (int)op, (int)r1, (int)r2, (int)m); case F_STRHI5: case F_LDRHI5: case F_STRI5: case F_LDRI5: case F_STRBI5: case F_LDRBI5: if ((unsigned32)m > 31 || (unsigned32)r1 > 7 || (unsigned32)r2 > 7) syserr("Instruction field overflow, op = %x, r1 = %x, r2 = %x, m = %x", (int)op, (int)r1, (int)r2, (int)m); op |= (m << 6) | (r1 << 3) | r2; break; case F_AND: case F_EOR: case F_LSL: case F_LSR: case F_ASR: case F_ADC: case F_SBC: case F_ROR: case F_TST: case F_NEG: case F_CMP: case F_CMN: case F_OR: case F_MUL: case F_BIC: case F_MVN: case F_ADDHL: case F_ADDLH: case F_ADDHH: case F_CMPHL: case F_CMPLH: case F_CMPHH: case F_MOVHL: case F_MOVLH: case F_MOVHH: if ((unsigned32)m > 7 || (unsigned32)r2 > 7) syserr("Instruction field overflow, op = %x, r1 = %x, r2 = %x, m = %x", (int)op, (int)r1, (int)r2, (int)m); op |= (m << 3) | r2; break; case F_BX_L: case F_BX_H: if ((unsigned32)r2 > 7) syserr("Instruction field overflow, op = %x, r1 = %x, r2 = %x, m = %x", (int)op, (int)r1, (int)r2, (int)m); op |= r2 << 3; break; case F_MOV8: case F_CMP8: case F_ADDI8: case F_SUBI8: case F_LDRLIT: case F_STRSP: case F_LDRSP: case F_STM: case F_LDM: case F_ADDRPC: case F_ADDRSP: if ((unsigned32)m > 255 || (unsigned32)r1 > 7) syserr("Instruction field overflow, op = %x, r1 = %x, r2 = %x, m = %x", (int)op, (int)r1, (int)r2, (int)m); op |= (r1 << 8) | m; break; case F_PUSH: case F_POP: if ((unsigned32)m > 511) syserr("Instruction field overflow, op = %x, r1 = %x, r2 = %x, m = %x", (int)op, (int)r1, (int)r2, (int)m); spchange = bitcount(m) * 4; if (op == F_POP) spchange = -spchange; op |= m; break; case F_ADDSP: case F_SUBSP: if ((unsigned32)m > 127) syserr("Instruction field overflow, op = %x, r1 = %x, r2 = %x, m = %x", (int)op, (int)r1, (int)r2, (int)m); spchange = m * 4; if (op == F_ADDSP) spchange = - spchange; op |= m; break; case F_SWI: if ((unsigned32)m > 255) syserr("Instruction field overflow, op = %x, r1 = %x, r2 = %x, m = %x", (int)op, (int)r1, (int)r2, (int)m); case F_B: case F_CALL1: case F_CALL: if ((unsigned32)m > 0x7ff) syserr("Instruction field overflow, op = %x, r1 = %x, r2 = %x, m = %x", (int)op, (int)r1, (int)r2, (int)m); op |= m; break; case F_BC: if ((unsigned32)m > 255) syserr("Instruction field overflow, op = %x, r1 = %x, r2 = %x, m = %x", (int)op, (int)r1, (int)r2, (int)m); op |= r2 | m; break; default: syserr("unknown op 0x%x in outop_direct\n", op); break; } #else if (!(disable_opt)) { if (op == F_CMP || op == F_CMN) { if (reg_values[m].typ == REGV_CONSTANT) { cmp_reg = r2; cmp_value = reg_values[m].value; if (op == F_CMN) cmp_value = -cmp_value; } else cmp_reg = NoRegister; flags_reg = NoRegister; cmpz_flag = 0; andk_flag = 0; } else if (op == F_CMP8) { andk_flag = 0; cmp_reg = r1; cmp_value = m; if (m == 0) { if (r1 == flags_reg) { cmpz_flag = 1; return; } else flags_reg = r1; } else flags_reg = NoRegister; cmpz_flag = 0; } else if (op == F_ADDI8 || op == F_SUBI8 || op == F_ADDI3 || op == F_SUBI3 || op == F_ADD3R || op == F_SUB3R || op == F_LSLK || op == F_LSRK || op == F_ASRK || op == F_MOV8) { cmp_reg = r1; cmp_value = 0; flags_reg = r1; cmpz_flag = 0; andk_flag = 0; reg_values[r1].typ = REGV_UNKNOWN; if (pending_regs & (1L << r1)) syserr("op = %.4x: R%d pending", (int)op, (int)r1); } else if (op == F_LDRSP || op == F_LDRLIT || op == F_ADDRPC || op == F_ADDRSP) { if (flags_reg == r1) { cmp_reg = NoRegister; flags_reg = NoRegister; } reg_values[r1].typ = REGV_UNKNOWN; if (pending_regs & (1L << r1)) syserr("op = %.4x: R%d pending", (int)op, (int)r1); } else if (op == F_AND || op == F_OR || op == F_EOR || op == F_BIC || op == F_NEG || op == F_MUL || op == F_MVN || op == F_LSL || op == F_LSR || op == F_ASR || op == F_ROR || op == F_ADC || op == F_SBC) { cmp_reg = r2; cmp_value = 0; flags_reg = r2; cmpz_flag = 0; andk_flag = 0; reg_values[r2].typ = REGV_UNKNOWN; if (pending_regs & (1L << r2)) syserr("op = %.4x: R%d pending", (int)op, (int)r2); } else if (op == F_MOVHL || op == F_ADDHL) { reg_values[r2].typ = REGV_UNKNOWN; if (pending_regs & (1L << r2)) syserr("op = %.4x: R%d pending", (int)op, (int)r2); } else if (op == F_LDRHADDR || op == F_LDSBADDR || op == F_LDSHADDR || op == F_LDRHI5 || op == F_LDRADDR || op == F_LDRBADDR || op == F_LDRI5 || op == F_LDRBI5) { if (flags_reg == r2) { cmp_reg = NoRegister; flags_reg = NoRegister; } reg_values[r2].typ = REGV_UNKNOWN; if (pending_regs & (1L << r2)) syserr("op = %.4x: R%d pending", (int)op, (int)r2); } else if (op == F_LDM || op == F_POP || op == F_STM || op == F_PUSH) { if (op == F_POP || op == F_PUSH) r1 = R_SP; reg_values[r1].typ = REGV_UNKNOWN; if (pending_regs & (1L << r1)) syserr("op = %.4x: R%d pending", (int)op, (int)r1); if (op == F_LDM || op == F_POP) { for (i = 0; i < 8; i++) { if (m & (1L << i)) { if (flags_reg == i) { cmp_reg = NoRegister; flags_reg = NoRegister; } reg_values[i].typ = REGV_UNKNOWN; if (pending_regs & (1L << i)) syserr("op = %.4x: R%d pending", (int)op, (int)i); } } } } else if (op == F_ADDSP || op == F_SUBSP) { reg_values[R_SP].typ = REGV_UNKNOWN; if (pending_regs & (1 << R_SP)) syserr("op = %.4x: R%d pending", (int)op, (int)R_SP); } } if (op == F_ADDI3 || op == F_SUBI3 || op == F_ADD3R || op == F_SUB3R) { if ((unsigned32)m > 7) InstructionFieldOverflow(op, r1, r2, m); if ((unsigned32)m > 31 || (unsigned32)r1 > 7 || (unsigned32)r2 > 7) InstructionFieldOverflow(op, r1, r2, m); op |= (m << 6) | (r2 << 3) | r1; } else if (op == F_LSLK || op == F_LSRK || op == F_ASRK) { if ((unsigned32)m > 31 || (unsigned32)r1 > 7 || (unsigned32)r2 > 7) InstructionFieldOverflow(op, r1, r2, m); op |= (m << 6) | (r2 << 3) | r1; } else if (op == F_STRHADDR || op == F_LDRHADDR || op == F_LDSBADDR || op == F_LDSHADDR || op == F_STRADDR || op == F_STRBADDR || op == F_LDRADDR || op == F_LDRBADDR) { if ((unsigned32)m > 7) InstructionFieldOverflow(op, r1, r2, m); if ((unsigned32)m > 31 || (unsigned32)r1 > 7 || (unsigned32)r2 > 7) InstructionFieldOverflow(op, r1, r2, m); op |= (m << 6) | (r1 << 3) | r2; } else if (op == F_STRHI5 || op == F_LDRHI5 || op == F_STRI5 || op == F_LDRI5 || op == F_STRBI5 || op == F_LDRBI5) { if ((unsigned32)m > 31 || (unsigned32)r1 > 7 || (unsigned32)r2 > 7) InstructionFieldOverflow(op, r1, r2, m); op |= (m << 6) | (r1 << 3) | r2; } else if (op == F_AND || op == F_EOR || op == F_LSL || op == F_LSR || op == F_ASR || op == F_ADC || op == F_SBC || op == F_ROR || op == F_TST || op == F_NEG || op == F_CMP || op == F_CMN || op == F_OR || op == F_MUL || op == F_BIC || op == F_MVN || op == F_ADDHL || op == F_ADDLH || op == F_ADDHH || op == F_CMPHL || op == F_CMPLH || op == F_CMPHH || op == F_MOVHL || op == F_MOVLH || op == F_MOVHH) { if ((unsigned32)m > 7 || (unsigned32)r2 > 7) InstructionFieldOverflow(op, r1, r2, m); op |= (m << 3) | r2; } else if (op == F_BX_L || op == F_BX_H) { if ((unsigned32)r2 > 7) InstructionFieldOverflow(op, r1, r2, m); op |= r2 << 3; } else if (op == F_MOV8 || op == F_CMP8 || op == F_ADDI8 || op == F_SUBI8 || op == F_LDRLIT || op == F_STRSP || op == F_LDRSP || op == F_STM || op == F_LDM || op == F_ADDRPC || op == F_ADDRSP) { if ((unsigned32)m > 255 || (unsigned32)r1 > 7) InstructionFieldOverflow(op, r1, r2, m); op |= (r1 << 8) | m; } else if (op == F_ADDSP || op == F_SUBSP) { if ((unsigned32)m > 127) InstructionFieldOverflow(op, r1, r2, m); spchange = m * 4; if (op == F_ADDSP) spchange = - spchange; op |= m; } else if (op == F_SWI) { if ((unsigned32)m > 255) InstructionFieldOverflow(op, r1, r2, m); op |= m; } else if (op == F_PUSH || op == F_POP) { if ((unsigned32)m > 511) InstructionFieldOverflow(op, r1, r2, m); spchange = bitcount(m) * 4; if (op == F_POP) spchange = -spchange; op |= m; } else if (op == F_B || op == F_CALL1 || op == F_CALL) { if ((unsigned32)m > 0x7ff) InstructionFieldOverflow(op, r1, r2, m); op |= m; } else if (op == F_BC) { if ((unsigned32)m > 255) InstructionFieldOverflow(op, r1, r2, m); op |= r2 | m; } else syserr("unknown op 0x%x in outop_direct\n", (int)op); #endif outHW((unsigned)op); if (spchange) fpdesc_notespchange(spchange); } static void outop2(int32 op, int32 r1, int32 r2, int32 m) { #if 0 if (!(disable_opt)) { switch (op) { case F_ADDI8: case F_SUBI8: r2 = r1; case F_ADDI3: case F_SUBI3: reg_values[r1].typ = REGV_BASE; reg_values[r1].reg = r2; if (op == F_SUBI8 || op == F_SUBI3) m = -m; reg_values[r1].value = m; pending_regs |= 1L << r1; flags_reg = r1; andk_flag = 0; return; case F_ADDRSP: reg_values[r1].typ = REGV_BASE; reg_values[r1].reg = R_SP; reg_values[r1].value = m * 4; pending_regs |= 1L << r1; return; case F_ADDSP: case F_SUBSP: reg_values[R_SP].typ = REGV_BASE; reg_values[R_SP].reg = R_SP; if (op == F_SUBSP) m = -m; reg_values[R_SP].value = m * 4; pending_regs |= 1 << R_SP; return; } } #else if (!(disable_opt)) { if (op == F_ADDI8 || op == F_SUBI8 || op == F_ADDI3 || op == F_SUBI3) { if (op == F_ADDI8 || op == F_SUBI8) r2 = r1; reg_values[r1].typ = REGV_BASE; reg_values[r1].reg = r2; if (op == F_SUBI8 || op == F_SUBI3) m = -m; reg_values[r1].value = m; pending_regs |= 1L << r1; flags_reg = r1; andk_flag = 0; return; } if (op == F_ADDRSP) { reg_values[r1].typ = REGV_BASE; reg_values[r1].reg = R_SP; reg_values[r1].value = m * 4; pending_regs |= 1L << r1; return; } if (op == F_ADDSP || op == F_SUBSP) { reg_values[R_SP].typ = REGV_BASE; reg_values[R_SP].reg = R_SP; if (op == F_SUBSP) m = -m; reg_values[R_SP].value = m * 4; pending_regs |= 1 << R_SP; return; } } #endif outop_direct(op, r1, r2, m); } static void ldm_flush0(void) { int32 n = 0; unsigned32 regbits = 0; int32 offset, initial_offset; int32 op = ldm_stm.op; int32 base_loaded = 0; RealRegister i; RealRegister base = ldm_stm.base; RealRegister ldm_base = NoRegister; for (i = 0; i < 8; i++) { if ((offset = ldm_stm.reg_off[i]) != -1) break; } if (i == 8) { ldm_stm.op = 0; return; } if (offset < 0) syserr("ldm/stm offset < 0"); initial_offset = offset; for (; i < 8; i++) { if (offset == ldm_stm.reg_off[i]) { if (i == base) { if (op == F_STRI5 && regbits != 0) break; base_loaded = 1; } ldm_base = i; regbits |= 1L << i; n++; ldm_stm.reg_off[i] = -1; offset += 4; } } /* If the base is going to be destroyed in this LDR/LDM make * sure all other regs are flushed first. */ if (op == F_LDRI5) { if (base_loaded) ldm_flush0(); if ((n >= 2 && initial_offset <= 4 && base != R_SP) || n >= 3) { /* ECN: Now adjust offset for any pending offset in the base */ if (pending_regs & regbit(base) && reg_values[base].typ == REGV_BASE && reg_values[base].reg == base) { pending_regs &= ~regbit(base); offset -= reg_values[base].value; reg_values[base].value = 0; } if (base == R_SP) { outop_direct(F_ADDRSP, ldm_base, 0, initial_offset/4); outop_direct(F_LDM, ldm_base, 0, regbits); } else if (initial_offset == 4 && !base_loaded) { outop_direct(F_ADDI3, ldm_base, base, initial_offset); outop_direct(F_LDM, ldm_base, 0, regbits); } else { if (initial_offset) outop_direct(F_ADDI8, base, 0, initial_offset); outop_direct(F_LDM, base, 0, regbits); for (i = 0; i < 8; i++) if (ldm_stm.reg_off[i] != -1) break; if ((!base_loaded && !(spareregs & (1L << base))) || i < 8) outop_direct(F_SUBI8, base, 0, offset); else { for (i= 0; i < 8; i++) if (reg_values[i].typ == REGV_BASE && reg_values[i].reg == base) reg_values[i].value -= offset; if (reg_values[base].typ == REGV_BASE && reg_values[base].reg != base) reg_values[base].value += offset; } } regbits = 0; } } else { if ((n >= 2 && initial_offset == 0) || n >= 3) { /* ECN: Now adjust offset for any pending offset in the base */ if (pending_regs & regbit(base) && reg_values[base].typ == REGV_BASE && reg_values[base].reg == base) { pending_regs &= ~regbit(base); offset -= reg_values[base].value; reg_values[base].value = 0; } if (initial_offset) outop_direct(F_ADDI8, base, 0, initial_offset); outop_direct(F_STM, base, 0, regbits); for (i = 0; i < 8; i++) if (ldm_stm.reg_off[i] != -1) break; if (!(spareregs & (1L << base)) || i < 8) outop_direct(F_SUBI8, base, 0, offset); else { for (i= 0; i < 8; i++) if (reg_values[i].typ == REGV_BASE && reg_values[i].reg == base) reg_values[i].value -= offset; if (reg_values[base].typ == REGV_BASE && reg_values[base].reg != base) reg_values[base].value += offset; } regbits = 0; } } n = 0; base_loaded = -1; for (i = 0; regbits != 0; regbits >>= 1, i++) { if (regbits & 1) { if (i == base) base_loaded = n; else { if (base == R_SP) outop_direct(F_LDRSP, i, 0, initial_offset/4 + n); else outop_direct(op, base, i, initial_offset/4 + n); } n++; } } if (base_loaded >= 0) outop_direct(op, base, base, initial_offset/4 + base_loaded); /* Tailcall to finish off the rest of them */ ldm_flush0(); } static void clm_flush(void) { int32 i, n; int32 final_offset; #if 0 if (clm.n > 1) { printf("CLM [R%d", clm.base); for (i = 0; i < clm.n; i++) printf(", #&%x", clm.offset[i]); printf("] @ %.8x\n", codebase+codep); } #endif while (clm.n != 0) { int32 m = clm.offset[0]; int32 init_offset = m; RealRegister r = NoRegister; int32 regs = 0; int32 initregs = 0; int32 k = 0; for (n = 1; n < clm.n; n++) { m += 4; if (clm.offset[n] != m) break; } final_offset = init_offset + n * 4; for (i = 0; i < 8; i++) { if (reg_values[i].typ == REGV_CONSTANT && reg_values[i].value == 0) { if (r < 0) r = i; regs |= 1L << i; k++; } } if (n > 3 && k < 4 && k < (n+1)/2) { for (i = 0; i < 8; i++) { if (i != clm.base && (spareregs & (1L << i)) && !(regs & (1L << i))) { regs |= 1L << i; initregs |= 1L << i; k++; if (k >= 4 || k >= (n + 1)/2) break; } } } /* /* syserr, not assert */ assert(r != NoRegister); assert(init_offset >= 0 && (init_offset & 3) == 0); assert(init_offset > -256 && init_offset < 256); assert(final_offset > -256 && final_offset < 256); assert((init_offset & 3) == 0); assert((final_offset & 3) == 0); if ((n > 3 && k > 1) || (n == 3 && (k >= 3 || (k == 2 && init_offset == 0))) || (n == 2 && (k >= 2 && init_offset == 0))) { if (init_offset != 0) outop_direct(init_offset < 0 ? F_SUBI8 : F_ADDI8, clm.base, 0, init_offset); flush_spareregs(initregs); for (i = 0; i < 8; i++) { if (initregs & (1L << i)) { outop_direct(F_MOV8, i, 0, 0); reg_values[i].typ = REGV_CONSTANT; reg_values[i].value = 0; } } m = n; while (m >= k) { outop_direct(F_STM, clm.base, 0, regs); m -= k; } if (m > 0) { for (i = k-m; i!= 0; i--) regs ^= (regs & -regs); outop_direct(F_STM, clm.base, 0, regs); } if ((!(spareregs & (1L << clm.base)) && final_offset) || n < clm.n) outop_direct(final_offset < 0 ? F_ADDI8 : F_SUBI8, clm.base, 0, final_offset); else { for (i= 0; i < 8; i++) if (reg_values[i].typ == REGV_BASE && reg_values[i].reg == clm.base && i != clm.base) reg_values[i].value -= final_offset; if (reg_values[clm.base].typ == REGV_BASE) reg_values[clm.base].value += final_offset; } } else { for (i = 0; i < n; i++) { assert(clm.offset[i] >= 0 && clm.offset[i] < 128); assert((clm.offset[i] & 3) == 0); outop_direct(F_STRI5, clm.base, r, clm.offset[i]/4); } } for (i = n; i < clm.n; i++) clm.offset[i-n] = clm.offset[i]; clm.n -= n; } } static bool ldm_flush(void) { int r = NO; if (ldm_stm.op) ldm_flush0(), r = YES; if (clm.n > 0) clm_flush(), r = YES; return r; } static void ldm_op(int32 op, int32 r1, int32 r2, int32 m) { int32 i; if (op == F_LDRSP) { op = F_LDRI5; r2 = r1; r1 = R_SP; } m = m * 4; if (op == F_STRI5 && reg_values[r2].typ == REGV_CONSTANT && reg_values[r2].value == 0 && r1 != R_SP) { /* Storing a zero - add to clear memory struct */ if (ldm_stm.op != 0 || clm.n == CLM_MAX || (clm.n > 0 && r1 != clm.base)) ldm_flush(); clm.z_reg = r2; clm.base = r1; for (i = 0; i < clm.n; i++) if (clm.offset[i] == m) return; for (i = clm.n; i > 0; i--) { if (clm.offset[i-1] < m) break; clm.offset[i] = clm.offset[i-1]; } clm.offset[i] = m; clm.n++; return; } if (clm.n > 0) ldm_flush(); if (op != ldm_stm.op || r1 != ldm_stm.base || (ldm_stm.reg_off[r2] >= 0 && op == F_STRI5)) { ldm_flush(); ldm_stm.op = op; ldm_stm.base = r1; for (i = 0; i < 8; i++) ldm_stm.reg_off[i] = -1; ldm_stm.mask = 0; } /* If there are two stores to the same location, then we ensure we always * do the second one by removing all prior stores to that location from * the LDM/STM list */ if (op == F_STRI5) { for (i = 0; i < 8; i++) if (ldm_stm.reg_off[i] == m) { ldm_stm.reg_off[i] = -1; ldm_stm.mask &= ~(1L << i); } } ldm_stm.reg_off[r2] = m; ldm_stm.mask |= 1L << r2; if (op == F_LDRI5) reg_values[r2].typ = REGV_UNKNOWN; if (r2 == ldm_stm.base && op == F_LDRI5) ldm_flush(); } static void reissue_cmp(void) { int32 t = flags_reg; flags_reg = NoRegister; outop(F_CMP8, t, 0, 0); /* Flags *are* set as a result of cmp so cmpz_flag is 0 */ cmpz_flag = 0; } static int32 check_cmp(int32 condition) { if (andk_flag != 0) { switch (condition) { case Q_PL: if (andk_flag != 0x80000000) syserr("ANDK condition = Q_PL, n = %.8x", andk_flag); case Q_EQ: case Q_UEQ: condition = Q_LO; break; case Q_MI: if (andk_flag != 0x80000000) syserr("ANDK condition = Q_MI, n = %.8x", andk_flag); case Q_NE: case Q_UNE: condition = Q_HS; break; case Q_AL: break; default: syserr("ANDK condition = %lx\n", condition); break; } } else if (cmpz_flag && flags_reg != NoRegister) { switch (condition) { case Q_HS: condition = Q_AL; break; case Q_LO: condition = Q_NOT; break; case Q_HI: condition = Q_NE; break; case Q_LS: condition = Q_EQ; break; case Q_GE: condition = Q_PL; break; case Q_LT: condition = Q_MI; break; case Q_GT: case Q_LE: reissue_cmp(); break; } } return condition; } static void reg_flush(void) { RealRegister i; for (i = 0; i < 16; i++) reg_values[i].typ = REGV_UNKNOWN; flags_reg = NoRegister; cmp_reg = NoRegister; pending_regs = 0; andk_flag = 0; } /* * Here I do not even pretend to insert information about the name of * the thing called into any tables that the object code formatter will see, * I just stick info in the "aux" entry assocuated with the first part of the * CALL instruction pair. */ static int32 call_k(Symstr *name) { int32 d, w; int i; w = 0; ldm_flush(); flush_pending(0xff | (1 << R_SP)); /* the next two lines' data structures may be mergeable. */ d = obj_symref(name, xr_code, 0); if (d == -1) { AddCodeXref4(X_PCreloc | codebase+codep, name, 0); d = 0; } else obj_symdef(t_sym, xr_code+xr_defloc+xr_dataincode, codebase+codep); w += ((d - (codebase+codep+PC_OFFSET)) >> 1) & 0x003fffff; outHWaux(F_CALL1 + ((w >> 11) & 0x7ff), name); outHW(F_CALL + (w & 0x7ff)); for (i = 0; i < 4; i++) reg_values[i].typ = REGV_UNKNOWN; flags_reg = NoRegister; cmp_reg = NoRegister; andk_flag = 0; return d; } #ifdef THUMB_CPLUSPLUS static void arm_tailcall_k(Symstr *name) { if (pcs_flags & PCS_INTERWORK) { int32 w, d = obj_symref(name, xr_code, 0); if (d == -1) { AddCodeXref4(X_PCreloc_32 | codebase+codep, name, 0); d = 0; } w = ((d - (codebase+codep+8)) >> 2) & 0x00ffffff; outcodewordaux(ARM_AL|ARM_B|w, LIT_OPCODE_32, name); } else { outcodeword(ARM_AL|ARM_LDR_IP_PC_0, LIT_OPCODE_32); outcodeword(ARM_AL|ARM_BX|ARM_R_IP, LIT_OPCODE_32); obj_symref(name, xr_code, 0); AddCodeXref4(X_absreloc | codebase+codep, name, 0); outcodeword(0, LIT_ADCON); } } #endif static int reads_mem1(int32 op, int32 r1, int32 r2, int32 m) { assert(op != F_LDRI5 && op != F_STRI5); IGNORE(r1); IGNORE(r2); IGNORE(m); switch(op) { case F_LDRHADDR: case F_LDRHI5: case F_LDRSP: case F_LDRADDR: case F_LDRBADDR: case F_LDRBI5: case F_POP: case F_LDM: return 1; } return 0; } static int alters_mem(int32 op, int32 r1, int32 r2, int32 m) { assert(op != F_LDRI5 && op != F_STRI5); IGNORE(r1); IGNORE(r2); IGNORE(m); switch (op) { case F_STRHADDR: case F_STRHI5: case F_STRSP: case F_STRADDR: case F_STRBADDR: case F_STRBI5: case F_PUSH: case F_STM: return 1; } return 0; } #define destroys_r(op, r1, r2, m, r) destroys(op, r1, r2, m, 1L << (r)) static int32 destroys(int32 op, int32 r1, int32 r2, int32 m, int32 mask) { #if 0 switch (op) { case F_ADDI3: case F_SUBI3: case F_ADD3R: case F_SUB3R: case F_LSLK: case F_LSRK: case F_ASRK: case F_MOV8: case F_ADDI8: case F_SUBI8: case F_LDRSP: case F_LDRLIT: case F_ADDRPC: case F_ADDRSP: return mask & (1L << r1); case F_AND: case F_OR: case F_EOR: case F_BIC: case F_NEG: case F_MUL: case F_MVN: case F_LSL: case F_LSR: case F_ASR: case F_ROR: case F_ADC: case F_SBC: case F_MOVHL: case F_ADDHL: case F_LDRHADDR: case F_LDSBADDR: case F_LDSHADDR: case F_LDRHI5: case F_LDRADDR: case F_LDRBADDR: case F_LDRBI5: case F_LDRI5: return mask & (1L << r2); case F_ADDHH: case F_MOVHH: case F_ADDLH: case F_MOVLH: return mask & (1L << (r2 + 8)); case F_PUSH: return mask & (1L << R_SP); case F_POP: return mask & ((m & 0xff) | (1L << R_SP)); case F_STM: return mask & (1L << r1); case F_LDM: return mask & ((m & 0xff) | (1L << r1)); case F_ADDSP: case F_SUBSP: return mask & (1L << R_SP); } #else if (op == F_ADDI3 || op == F_SUBI3 || op == F_ADD3R || op == F_SUB3R || op == F_LSLK || op == F_LSRK || op == F_ASRK || op == F_MOV8 || op == F_ADDI8 || op == F_SUBI8 || op == F_LDRSP || op == F_LDRLIT || op == F_ADDRPC || op == F_ADDRSP) return mask & (1L << r1); if (op == F_AND || op == F_OR || op == F_EOR || op == F_BIC || op == F_NEG || op == F_MUL || op == F_MVN || op == F_LSL || op == F_LSR || op == F_ASR || op == F_ROR || op == F_ADC || op == F_SBC || op == F_MOVHL || op == F_ADDHL || op == F_LDRHADDR || op == F_LDSBADDR || op == F_LDSHADDR || op == F_LDRHI5 || op == F_LDRADDR || op == F_LDRBADDR || op == F_LDRBI5 || op == F_LDRI5) return mask & (1L << r2); if (op == F_ADDHH || op == F_MOVHH || op == F_ADDLH || op == F_MOVLH) return mask & (1L << (r2 + 8)); if (op == F_PUSH) return mask & (1L << R_SP); if (op == F_POP) return mask & ((m & 0xff) | (1L << R_SP)); if (op == F_STM) return mask & (1L << r1); if (op == F_LDM) return mask & ((m & 0xff) | (1L << r1)); if (op == F_ADDSP || op == F_SUBSP) return mask & (1L << R_SP); #endif return 0; } #define uses_r(op, r1, r2, m, r) uses(op, r1, r2, m, 1L << (r)) static int32 uses(int32 op, int32 r1, int32 r2, int32 m, int32 mask) { if (op == F_STRHADDR || op == F_STRADDR || op == F_STRBADDR) return mask & ((1L << r1) | (1L << r2) | (1L << m)); if (op == F_STRHI5 || op == F_STRBI5 || op == F_STRI5) return mask & ((1L << r1) | (1L << r2)); if (op == F_LDRHADDR || op == F_LDRADDR || op == F_LDRBADDR || op == F_LDSBADDR || op == F_LDSHADDR) return mask & ((1L << r1) | (1L << m)); if (op == F_ADD3R || op == F_SUB3R || op == F_AND || op == F_OR || op == F_EOR || op == F_BIC || op == F_MUL || op == F_LSL || op == F_LSR || op == F_ASR || op == F_ROR || op == F_ADC || op == F_SBC) return mask & ((1L << r2) | (1L << m)); if (op == F_ADDI8 || op == F_SUBI8 || op == F_LDRHI5 || op == F_LDRBI5 || op == F_LDRI5) return mask & (1L << r1); if (op == F_STRSP) return mask & ((1L << r1) | (1L << R_SP)); if (op == F_ADDI3 || op == F_SUBI3 || op == F_LSLK || op == F_LSRK || op == F_ASRK) return mask & (1L << r2); if (op == F_NEG || op == F_MVN) return mask & (1L << m); if (op == F_MOVLH) return mask & (1L << m); if (op == F_MOVHH || op == F_MOVHL) return mask & (1L << (m+8)); if (op == F_ADDHL || op == F_CMPHL) return mask & ((1L << (m+8)) | (1L << r2)); if (op == F_ADDLH || op == F_CMPLH) return mask & ((1L << (r2+8)) | (1L << m)); if (op == F_ADDHH || op == F_CMPHH) return mask & ((1L << (r2+8)) | (1L << (m+8))); if (op == F_PUSH) return mask & ((m & 0xff) | (1L << R_SP)); if (op == F_ADDRSP || op == F_ADDSP || op == F_SUBSP || op == F_LDRSP || op == F_POP) return mask & (1L << R_SP); if (op == F_LDM) return mask & (1L << r1); if (op == F_STM) return mask & ((m & 0xff) | (1L << r1)); return 0; } static int is_cmp_op(int32 op) { return op == F_CMP8 || op == F_CMP || op == F_CMN || op == F_TST; } static void flush_spareregs(int32 mask) { int32 pending; int i; pending = 0; for (i = 0; i < 8; i++) { if (reg_values[i].typ == REGV_BASE && (mask & (1L << reg_values[i].reg))) pending |= 1L << i; } if (pending) flush_pending(pending); } static void flush_pending(int32 mask) { int i; int32 r; int32 op; int32 m, n; mask &= pending_regs; pending_regs &= ~mask; for (i = 0; i < 8; i++) { if (mask & (1L << i)) { if (reg_values[i].typ != REGV_BASE) syserr("Not register based in flush pending"); m = reg_values[i].value; r = reg_values[i].reg; if (ldm_stm.op != 0 && i == ldm_stm.base) { for (n = 0; n < 8; n++) if (ldm_stm.reg_off[n] != -1) ldm_stm.reg_off[n] -= m; } if (r == R_SP) { n = (m & 0x3fc); if (m < 0) n = 0; outop_direct(F_ADDRSP, i, 0, n/4); m ^= n; r = i; } op = F_ADDI3; if (m < 0) op = F_SUBI3, m = -m; if (i != r) { n = m; if (m > 7) n = 7; outop_direct(op, i, r, n); m -= n; } op = (op == F_ADDI3) ? F_ADDI8 : F_SUBI8; while (m) { n = m; if (m > 255) n = 255; outop_direct(op, i, 0, n); m -= n; } reg_values[i].typ = REGV_BASE; } } if (mask & (1 << R_SP)) { if (reg_values[R_SP].typ != REGV_BASE) syserr("Not register based in flush pending"); assert(reg_values[R_SP].reg == R_SP); m = reg_values[R_SP].value; if (m & 3) syserr("Non word aligned offset from sp"); op = F_ADDSP; if (m < 0) op = F_SUBSP, m = -m; m /= 4; while (m) { n = m; if (m > 127) n = 127; outop_direct(op, 0, 0, n); m -= n; } } } static bool outop0(int32 op, int32 r1, int32 r2, int32 m) { assert(op != F_LDRI5 && op != F_STRI5); if (clm.n > 0) { if (destroys_r(op, r1, r2, m, clm.base) || destroys_r(op, r1, r2, m, clm.z_reg) || alters_mem(op, r1, r2, m) || reads_mem1(op, r1, r2, m)) { return ldm_flush(); } } if (ldm_stm.op) { if (ldm_stm.op == F_LDRI5) { if (uses(op, r1, r2, m, ldm_stm.mask) || destroys_r(op, r1, r2, m, ldm_stm.base) || destroys(op, r1, r2, m, ldm_stm.mask) || alters_mem(op, r1, r2, m)) { return ldm_flush(); } } else { if (destroys(op, r1, r2, m, ldm_stm.mask) || destroys_r(op, r1, r2, m, ldm_stm.base) || alters_mem(op, r1, r2, m) || reads_mem1(op, r1, r2, m)) { return ldm_flush(); } } } return NO; } static void check_pending(int32 op, int32 r1, int32 r2, int32 m, int nospcheck) { int i; int32 mask; int r; r = 0; mask = uses(op, r1, r2, m, pending_regs); if (nospcheck) mask &= ~(1 << R_SP); if (mask) flush_pending(mask); if ((mask = destroys(op, r1, r2, m, pending_regs)) != 0) pending_regs &= ~mask; for (i = 0; i < 8; i++) { if (reg_values[i].typ == REGV_BASE) { if (destroys_r(op, r1, r2, m, reg_values[i].reg)) { if (pending_regs & (1L << i)) flush_pending(1L << i); reg_values[i].typ = REGV_UNKNOWN; } } } if (!nospcheck) { if (reg_values[R_SP].typ == REGV_BASE) { if (destroys_r(op, r1, r2, m, R_SP)) { if (pending_regs & (1 << R_SP)) flush_pending(1 << R_SP); reg_values[R_SP].typ = REGV_UNKNOWN; } } } } static void outop(int32 op, int32 r1, int32 r2, int32 m) { int32 op_e, r1_e, r2_e, m_e; int32 i; int32 n; int32 f_r1; int nospcheck; op_e = op, r1_e = r1, r2_e = r2, m_e = m; op &= ~0x80000000; if (op == F_ADDI3 && r1 == r2) op = F_ADDI8, r2 = 0; if (op == F_SUBI3 && r1 == r2) op = F_SUBI8, r2 = 0; if (disable_opt) { outop_direct(op, r1, r2, m); } else { f_r1 = r1; nospcheck = 0; #if 0 if (op == F_LDRSP || op == F_STRSP) { if (pending_regs & (1 << R_SP)) { n = reg_values[R_SP].value; assert(reg_values[R_SP].reg == R_SP); n = (n >> 2) + m; if (n >= 0 && n < 256) { m = n; nospcheck = 1; } } } #endif if (op == F_ADDRSP) { if (reg_values[r1].typ == REGV_BASE && reg_values[r1].reg == R_SP) { n = reg_values[r1].value; n = m*4 - n; i = m; if (n >= 0 && n < 256) op = F_ADDI8, m = n; if (n <= 0 && n > -256) op = F_SUBI8, m = -n; if (n == 0) return; } } if (op == F_STRI5 || op == F_STRBI5 || op == F_LDRI5 || op == F_LDRBI5 || op == F_STRHI5 || op == F_LDRHI5) { if (pending_regs & (1L << r1)) { n = reg_values[r1].value; i = reg_values[r1].reg; if (op == F_LDRI5 || op == F_STRI5) { if (n & 3) i = NoRegister; n = (n >> 2) + m; #if 0 if (i == R_SP && n >= 0 && n < 256) { m = n; r1 = r2; r2 = 0; f_r1 = r1; nospcheck = 1; assert(!(pending_regs & (1 << R_SP))); op = op == F_LDRI5 ? F_LDRSP : F_STRSP; } #endif } else if (op == F_LDRHI5 || op == F_STRHI5) { if (n & 1) i = NoRegister; n = (n >> 1) + m; } else { n = n + m; } if (i != NoRegister && i < 8 && n >= 0 && n < 32) { /* STR Rs, [Rb, #N] where Rs == Rb but value of Rs if offset from Rb * causes problems so we must revert to * ADD/SUB Rs, Rs, #M * STR Rs, [Rb, #N] ; Rs != Rb */ if (!((pending_regs & (1L << i)) && i == r2 && !(op & 0x0800))) { m = n; r1 = i; f_r1 = 16; } } } } if (op == F_STRHADDR || op == F_STRBADDR || op == F_STRADDR || op == F_STRHI5 || op == F_STRBI5 || op == F_STRI5 || op == F_LSLK || op == F_LSRK || op == F_ASRK || op == F_ADDI3 || op == F_SUBI3 || op == F_ADD3R || op == F_SUB3R) { if (pending_regs & (1L << r2) && reg_values[r2].value == 0) { i = reg_values[r2].reg; if (i < 8) r2 = i; } } if (op == F_CMP8 && m != 0) { if (pending_regs & (1L << r1) && reg_values[r1].value == 0) { i = reg_values[r1].reg; if (i < 8) r1 = i; } } if (op == F_STRSP) { if (pending_regs & (1L << r1) && reg_values[r1].value == 0) { i = reg_values[r1].reg; if (i < 8) r1 = i; } } if (op == F_ADD3R || op == F_SUB3R || op == F_STRHADDR || op == F_LDRHADDR || op == F_LDSBADDR || op == F_LDSHADDR || op == F_STRADDR || op == F_STRBADDR || op == F_LDRADDR || op == F_LDRBADDR || IS_DATAPROC(op)) { if (pending_regs & (1L << m) && reg_values[m].value == 0) { i = reg_values[m].reg; if (i < 8) m = i; } } if (op == F_ADDI8 || op == F_SUBI8) { if (pending_regs & (1L << r1)) { if (op == F_SUBI8) m = -m; m += reg_values[r1].value; reg_values[r1].value = m; if (ldm_stm.op != 0 && r1 == ldm_stm.base) { for (i = 0; i < 8; i++) { if (ldm_stm.reg_off[i] != -1 && (ldm_stm.reg_off[i] - m < 0)) { ldm_flush(); break; } } for (i = 0; i < 8; i++) { if (ldm_stm.reg_off[i] != -1) ldm_stm.reg_off[i] -= m; } } if (r1 == clm.base) { for (i = 0; i < clm.n; i++) clm.offset[i] -= m; } return; } } if (op == F_ADDSP || op == F_SUBSP) { if (pending_regs & (1 << R_SP)) { if (op == F_SUBSP) m = -m; reg_values[R_SP].value += m * 4; return; } } if (is_cmp_op(op)) { if (ldm_flush()) { /* If ldm/stm flushes this may have invalidated some assumptions * about the register values earlier in this function, so we call * ourselves again with the original arguments */ if (op_e & 0x80000000) syserr("re-entry in outop(%lx)", op); outop(op_e | 0x80000000, r1_e, r2_e, m_e); return; } if (op == F_CMP8 && m == 0) flush_pending(0xff ^ (1L << r1)); flush_pending(0xff | (1 << R_SP)); } check_pending(op, f_r1, r2, m, nospcheck); if (op == F_LDRI5 || op == F_STRI5 || (op == F_LDRSP && m >= 0 && m < 512)) { ldm_op(op, r1, r2, m); } else { if (outop0(op, r1, r2, m)) { /* If ldm/stm flushes this may have invalidated some assumptions * about the register values earlier in this function, so we call * ourselves again with the original arguments */ if (op_e & 0x80000000) syserr("re-entry in outop(%lx)", op); outop(op_e | 0x80000000, r1_e, r2_e, m_e); return; } outop2(op, r1, r2, m); } } } void cnop(void) { if (codep & 1) outDCB(0); if (((codebase+codep) & 2) != 0) outop_direct(F_ADDI3, 0, 0, 0); } /* although the idea of setlabel is machine independent, it stays here because it back-patches code. In the long term setlabel should be in codebuf.c and call a machine dependent backpatch routine. */ List3 *label_values, *label_references; #define AddLabelReference(pos, lab) \ label_references = (List3 *)syn_list3(label_references, (pos),\ lab_name_(lab) & 0xfffff) #define AddLitPoolReference(pos, off) \ label_references = (List3 *)syn_list3(label_references, (pos),\ (lab_name_(litlab) & 0xfffff) | ((off) << 20)) int32 current_procnum; static void setlabel2(LabelNumber *ll, int32 codep) { List3 *l, **l_p; l_p = &label_values; while ((l = *l_p) != 0) { if ((int32)car_(l) <= codep) break; l_p = (List3 **)&cdr_(l); } *l_p = (List3 *)binder_icons3(l, codep, lab_name_(ll) & 0xfffff); lab_setloc_(ll, codep | 0x80000000); /* cheapo union checker for ->frefs */ } #define LABREF_B 0x01000000 #define LABREF_BC 0x02000000 #define LABREF_BL 0x03000000 #define LABREF_WORD8 0x04000000 #define LABREF_BXX_8 0x05000000 #define LABREF_BXX_16 0x06000000 #ifdef THUMB_CPLUSPLUS #define LABREF_WORD32 0x08000000 #endif static void setlabel1(LabelNumber *l) { List *p; #if 0 fprintf(stderr, "%.8x: (setlabel1) F%dL%d = %.8x (isset = %d)\n", codebase + codep, current_procnum, lab_name_(l) & 0xfffff, codebase + codep, lab_isset_(l)); #endif p = l->u.frefs; while (p) { int32 v = car_(p); int32 q = (v & 0x00ffffff); int32 w; unsigned32 d; switch (v & 0xff000000) { case LABREF_B: /* B xxx */ w = code_hword_(q); d = (codep-q-PC_OFFSET >> 1); if ((int32)d < -0x400 || (int32)d >= 0x400) syserr(syserr_displacement, (long)d); w = (w & ~0x7ff) | (d & 0x7ff); code_hword_(q) = (unsigned16)w; break; case LABREF_BC: /* BC xxx */ w = code_hword_(q); d = (codep-q-PC_OFFSET >> 1); if ((int32)d < -0x80 || (int32)d >= 0x80) syserr(syserr_displacement, (long)d); w = (w & ~0xff) | (d & 0xff); code_hword_(q) = (unsigned16)w; break; case LABREF_BL: /* BL xxx */ w = code_hword_(q); d = (codep-q-PC_OFFSET >> 1); w = (w & ~0x7ff) | ((d >> 11) & 0x7ff); code_hword_(q) = (unsigned16)w; w = code_hword_(q+2); w = (w & ~0x7ff) | (d & 0x7ff); code_hword_(q+2) = (unsigned16)w; break; case LABREF_WORD8: /* ADD Rd, pc, #nn */ /* LDR Rd, [pc, #nn] */ w = code_hword_(q); d = ((codebase+codep)-((codebase+q)&~3)-PC_OFFSET >> 2) + (w & 0xff); if (d >= 0x100) syserr(syserr_displacement, (long)d); w = (w & ~0xff) | d; code_hword_(q) = (unsigned16)w; break; #ifdef THUMB_CPLUSPLUS case LABREF_WORD32: { /* DCD L<N> */ Symstr *labname; char b[20]; sprintf(b, "$F%dL%d", current_procnum, lab_name_(l)); labname = sym_insert_id(b); obj_symdef(labname, xr_code+xr_defloc+xr_code_32, codebase+codep); AddCodeXref4(X_absreloc | codebase+q, labname, 0); AddLabelReference(q, l); break; } #endif case LABREF_BXX_8: w = code_byte_(q); d = (codep-(q&~1)-PC_OFFSET >> 1) + (w & 0xff); if (d >= 0x100) syserr(syserr_displacement, (long)d); code_byte_(q) = d; break; case LABREF_BXX_16: w = code_hword_(q); d = codep-q-PC_OFFSET + (w & 0xffff); if (d >= 0x10000) syserr(syserr_displacement, (long)d); code_hword_(q) = d; break; } p = (List *)discard2(p); } label_values = (List3 *)binder_icons3(label_values, codep, lab_name_(l) & 0xfffff); lab_setloc_(l, codep | 0x80000000); /* cheapo union checker for ->frefs */ } static int32 branch_range(int32 flags) { if (FREF_TYPE(flags) == FREF_DCB) return 512 - 24L; if (FREF_TYPE(flags) == FREF_DCW) return 65536 - 24L; return (FREF_CONDITION(flags) == Q_AL ? 2048L : 256L) - 24L; /* Margin for safety */ } static void describe_literal_pool(void) { if (!in_code) { if (codebase+codep != literal_pool_start) { char b[32]; sprintf(b, "x$litpool$%d", literal_pool_number); obj_symref(sym_insert_id(b), xr_code+xr_defloc+xr_dataincode, (literal_pool_start+3) & ~3); sprintf(b, "x$litpool_e$%d", literal_pool_number++); obj_symref(sym_insert_id(b), xr_code+xr_defloc+xr_dataincode, codebase+codep-1); } in_code = YES; } } static void recalc_mustbranchlitby(void) { FRef_Branch *fref = fref_branches; int32 litby = 0x10000000; int32 poolsize = 0; for (; fref != NULL; fref = cdr_(fref)) { if (fref->pcref + branch_range(fref->flags) - poolsize < litby) litby = fref->pcref + branch_range(fref->flags) - poolsize; poolsize += 2; } mustbranchlitby = litby; } void setlabel(LabelNumber *l) { FRef_Branch *fref; FRef_Branch **fref_p = &fref_branches; while ((fref = *fref_p) != 0) { if (l == fref->real_dest) { *fref_p = cdr_(fref); setlabel1(fref->chained_dest); branchpoolsize -= 2; } else fref_p = &cdr_(fref); } fref_branches_head = fref_p; recalc_mustbranchlitby(); setlabel1(l); if (l != litlab) describe_literal_pool(); } static void dump_branch_lits(int needs_jump, int32 poolsize) { FRef_Branch *fref, **fref_p; LabelNumber *ll = NULL; mustbranchlitby = 0x10000000; ldm_flush(); flush_pending(0xff | (1 << R_SP)); poolsize += branchpoolsize; if (needs_jump) { ll = nextlabel(); branch_round_literals(ll); } fref_p = &fref_branches; while ((fref = *fref_p) != 0) { int range = branch_range(fref->flags); range = range * 7 / 8; if (codep - fref->pcref + poolsize > range) { *fref_branches_head = fref; *fref_p = cdr_(fref); cdr_(fref) = 0; fref_branches_head = &cdr_(fref); setlabel1(fref->chained_dest); fref->chained_dest = nextlabel(); fref->flags = Q_AL | FREF_BRANCH; fref->pcref = codep; fref->codep = codep; AddLabelReference(codep, fref->chained_dest); addfref_(fref->chained_dest, codep | LABREF_B); outop(F_B, 0, 0, 0); poolsize -= 2; } else fref_p = &cdr_(fref); } if (needs_jump) setlabel(ll); /* recalculates mustbranchlitby */ else recalc_mustbranchlitby(); } static void dumplits(int needs_jump) { LabelNumber *ll = NULL; if (needs_jump) { ll = nextlabel(); branch_round_literals(ll); } dump_branch_lits(0, litpoolp * 4); literal_pool_start = codebase+codep; dumplits2(0); if (needs_jump) setlabel(ll); } static void addressability(int32 n) /* * "I can address up to n bytes beyond where I am now" */ { int32 litpoolsize;; n -= 24; /* margin for safety */ litpoolsize = 4*litpoolp; if (litpoolsize>=n) dumplits(YES); if (codep-litpoolsize+n < mustlitby) mustlitby = codep-litpoolsize+n; } static void load_lit(RealRegister r1, int32 n) { int32 i; ldm_flush(); flush_pending(0xff | (1 << R_SP)); if ((i = lit_findwordaux(n, LIT_NUMBER, 0, LITF_INCODE|LITF_FIRST|LITF_LAST|LITF_PEEK)) >=0) { addfref_(litlab, codep | LABREF_WORD8); AddLitPoolReference(codep, i); outop(F_LDRLIT, r1, 0, i/4); } else { addressability(1024); i = lit_findwordaux(n, LIT_NUMBER, 0, LITF_INCODE|LITF_FIRST|LITF_LAST|LITF_NEW); addfref_(litlab, codep | LABREF_WORD8); AddLitPoolReference(codep, i); outop(F_LDRLIT, r1, 0, i/4); } } static int add_integer0(RealRegister r1, RealRegister r2, int32 n, int len_only); static void add_integer(RealRegister r1, RealRegister r2, int32 n); static void load_adcon(RealRegister r1, Symstr *name, int32 offset) { int32 i; int32 d; RealRegister r; /* Try to find adcon in following order: 1. current literal pool, */ /* 2. new allocation in current pool. */ ldm_flush(); flush_pending(0xff | (1 << R_SP)); d = offset-reg_values[r1].value; if (pcs_flags & PCS_REENTRANT) { i = adconpool_find(offset, LIT_ADCON, name); AddCodeXref4(X_DataVal+codebase+codep, adconpool_lab, 0); outop_direct(F_MOV8, r1, 0, (i >> 7) & 0xff); outop_direct(F_LSLK, r1, r1, 7); outop_direct(F_ADDHL, 0, r1, R_SB-8); outop_direct(F_LDRI5, r1, r1, (i >> 2) & 0x1f); } else { if (reg_values[r1].typ == REGV_ADCON && reg_values[r1].name == name && add_integer0(r1, r1, d, 1) <= 1) { add_integer(r1, r1, d); } else if ((i = lit_findword(offset, LIT_ADCON, name, LITF_INCODE|LITF_FIRST|LITF_LAST|LITF_PEEK)) >= 0) { addfref_(litlab, codep | LABREF_WORD8); AddLitPoolReference(codep, i); outop(F_LDRLIT, r1, 0, i/4); } else { for (r = 0; r < 8; r++) { d = offset-reg_values[r].value; if (reg_values[r].typ == REGV_ADCON && reg_values[r].name == name && add_integer0(r1, r, d, 1) <= 2) { add_integer(r1, r, d); break; } } if (r >= 8) { addressability(1024); i = lit_findword(offset, LIT_ADCON, name, LITF_INCODE|LITF_FIRST|LITF_LAST|LITF_NEW); addfref_(litlab, codep | LABREF_WORD8); AddLitPoolReference(codep, i); outop(F_LDRLIT, r1, 0, i/4); } } } flush_pending(1<<r1); /* Make sure it really has this value */ if (!(disable_opt)) { reg_values[r1].typ = REGV_ADCON; reg_values[r1].name = name; reg_values[r1].value = offset; } } static void load_fp_adcon(RealRegister r1, J_OPCODE op, FloatCon *fc) { int32 disp; int size = (op==J_MOVDK || op==J_ADCOND) ? 2 : 1; ldm_flush(); flush_pending(0xff | (1 << R_SP)); addressability(1024); disp = lit_findwordsincurpool(fc->floatbin.irep, size, LIT_FPNUM); if (disp < 0) /* not found in current pool - don't look in previous */ { if (size == 1) { disp = lit_findwordaux(fc->floatbin.fb.val, LIT_FPNUM, fc->floatstr, LITF_INCODE|LITF_FIRST|LITF_LAST); } else { (void) lit_findwordaux(fc->floatbin.db.msd, LIT_FPNUM1, fc->floatstr, LITF_INCODE|LITF_FIRST); disp = lit_findwordaux(fc->floatbin.db.lsd, LIT_FPNUM2, fc->floatstr, LITF_INCODE|LITF_LAST) - 4; } } addfref_(litlab, codep | LABREF_WORD8); AddLitPoolReference(codep, disp); outop(F_ADDRPC, r1, 0, disp/4); } static void load_ll_adcon(RealRegister r1, J_OPCODE op, Int64Con *c) { int32 *w = (int32 *)&c->bin.i; int size = sizeof_longlong / sizeof_long; int32 disp; IGNORE(op); ldm_flush(); flush_pending(0xff | (1 << R_SP)); addressability(1024); disp = lit_findwordsincurpool(w, size, LIT_INT64_1); if (disp < 0) { (void)lit_findword(w[0], LIT_INT64_1, NULL, LITF_INCODE|LITF_FIRST); disp = lit_findword(w[1], LIT_INT64_2, NULL, LITF_INCODE|LITF_LAST) - 4; } addfref_(litlab, codep | LABREF_WORD8); AddLitPoolReference(codep, disp); outop(F_ADDRPC, r1, 0, disp/4); } static bool uses_IP; static bool return_pending; static int load_integer0(RealRegister r, int32 n, int len_only); static void load_integer(RealRegister r, int32 n); static void move_register(RealRegister r1, RealRegister r2) { /* r1 = r2 */ if (r1 == r2) return; if (r1 >= 8) { if (r2 >= 8) outop(F_MOVHH, 0, r1-8, r2-8); else outop(F_MOVLH, 0, r1-8, r2); } else { if (r2 >= 8) outop(F_MOVHL, 0, r1, r2-8); else outop(F_ADDI3, r1, r2, 0); } } static bool register_holds_value(RealRegister r, int32 n) { return !disable_opt && reg_values[r].typ == REGV_CONSTANT && !(ldm_stm.op != 0 && ldm_stm.reg_off[r] >= 0) && reg_values[r].value == n; } static bool value_is_constant(RealRegister r) { return !disable_opt && reg_values[r].typ == REGV_CONSTANT && !(ldm_stm.op != 0 && ldm_stm.reg_off[r] >= 0); } static RealRegister constant_available(int32 n) { RealRegister r; if (!disable_opt) for (r = 0; r < 8; r++) if (register_holds_value(r, n)) return r; return NoRegister; } static RealRegister get_register(void) { RealRegister r; for (r = 7; r >= 0; r--) if (r != R_IP && (spareregs & (1L << r))) return r; return R_IP; } static int add_integer0(RealRegister r1, RealRegister r2, int32 n, int len_only) { int l, minlen; unsigned32 m, v; int32 op1, op2; int32 r; m = n; op1 = F_ADDI3; op2 = F_ADDI8; if (n < 0) { m = -n; op1 = F_SUBI3; op2 = F_SUBI8; } if (m > 255 || (r1 != r2 && m > 7)) { if ((r = constant_available(n)) >= 0) { if (!len_only) outop(F_ADD3R, r1, r2, r); return 1; } else if ((r = constant_available(-n)) >= 0) { if (!len_only) outop(F_SUB3R, r1, r2, r); return 1; } } if (r1 == r2) { if (m <= 3 * 255) { l = 0; while (m) { v = m > 255 ? 255 : m; if (!len_only) outop(op2, r1, 0, v); m -= v; l++; } return l; } } else { if (m <= 2 * 255 + 7) { v = m > 7 ? 7 : m; if (!len_only) outop(op1, r1, r2, v); m -= v; l = 1; while (m) { v = m > 255 ? 255 : m; if (!len_only) outop(op2, r1, 0, v); m -= v; l++; } return l; } } uses_IP = YES; if (r2 == R_IP) { if (len_only) return 1000; /* cannot generate code for this, so return large number */ syserr("add_integer0: IP clash @ %.8lx", codebase+codep); } minlen = load_integer0(R_IP, n, 1); l = load_integer0(R_IP, -n, 1); if (l < minlen) { minlen = l; if (!len_only) { load_integer(R_IP, -n); outop(F_SUB3R, r1, r2, R_IP); } } else { if (!len_only) { load_integer(R_IP, n); outop(F_ADD3R, r1, r2, R_IP); } } return minlen+1; } static void add_integer(RealRegister r1, RealRegister r2, int32 n) { if (r2 == R_SP) { /* Magic special for SP-relative address calculation */ if (r1 < 8) { if ((n & 3) || n >= 1024 || n < 0) { int32 n1; n1 = n & 0x3fc; if ((n ^ n1) < 256 && (n ^ n1) > -256) { outop(F_ADDRSP, r1, 0, n1/4); add_integer0(r1, r1, n ^ n1, 0); } else { load_integer(r1, n); outop(F_ADDHL, 0, r1, R_SP-8); } return; } outop(F_ADDRSP, r1, 0, n/4); return; } else if (r1 == R_SP) { /* Change value in SP. Needn't set flags */ int32 n1 = n; int32 sign = 0; int loadlen; if (n & 3) syserr("Non word aligned offset from sp %.8lx\n", codebase+codep); if (n == 0) return; if (n1 < 0) { sign = 1; n1 = -n1; } n1 = n1 >> 2; loadlen = load_integer0(R_IP, n, 1); if (loadlen < (n1 >> 7)) { uses_IP = YES; load_integer0(R_IP, n, 0); outop(F_ADDLH, 0, R_SP-8, R_IP); } else while (n1 != 0) { int32 m = (n1 >= (1 << 7)) ? (1 << 7) - 1 : n1; outop(sign ? F_SUBSP : F_ADDSP, 0, 0, m); n1 -= m; } return; } else syserr("Add sp to bad reg %d", (int)r1); } add_integer0(r1, r2, n, 0); } static int load_integer0(RealRegister r, int32 n, int len_only) { int32 m, shift; int32 i; if (!(disable_opt)) { if (register_holds_value(r, n)) return 0; } if (n >= 0 && n < 256) { if (!len_only) outop(F_MOV8, r, 0, n); return 1; } if (!(disable_opt)) { for (m = 0; m < 8; m++) { if (value_is_constant(m)) { int32 k = reg_values[m].value; if (k == n) { if (!len_only) outop(F_ADDI3, r, m, 0); return 1; } if (k == -n) { if (!len_only) outop(F_NEG, 0, r, m); return 1; } if (k == ~n) { if (!len_only) outop(F_MVN, 0, r, m); return 1; } if (r == m && k >= n-255 && k <= n-255) { if (!len_only) { if (n-k >= 0) outop(F_ADDI8, r, 0, n-k); else outop(F_SUBI8, r, 0, k-n); } return 1; } if ((k >= n-7 && k <= n+7)) { if (!len_only) { if (n-k >= 0) outop(F_ADDI3, r, m, n-k); else outop(F_SUBI3, r, m, k-n); } return 1; } for (i = 1; i <= 31; i++) { if ((k << i) == n) { if (!len_only) outop(F_LSLK, r, m, i); return 1; } if (((uint32)k >> i) == (uint32)n) { if (!len_only) outop(F_LSRK, r, m, i); return 1; } if (signed_rightshift_(k, i) == n) { if (!len_only) outop(F_ASRK, r, m, i); return 1; } } } } } if (!(config & CONFIG_OPTIMISE_TIME)) { if ((i = lit_findwordaux(n, LIT_NUMBER, 0, LITF_INCODE|LITF_FIRST|LITF_LAST|LITF_PEEK)) >=0) { if (!len_only) load_lit(r, n); return 1; } } if (n < 0 && n >= -256) { if (!len_only) { outop(F_MOV8, r, 0, ~n); outop(F_MVN, 0, r, r); } return 2; } if (n >= 0 && n <= 255 * 2) { if (!len_only) { outop(F_MOV8, r, 0, 255); outop(F_ADDI8, r, 0, n - 255); } return 2; } m = n, shift = 0; while (!(m & 1)) m >>= 1, shift++; if (!(m & ~0xff)) { if (!len_only) { outop(F_MOV8, r, 0, m); outop(F_LSLK, r, r, shift); } return 2; } if (!len_only) load_lit(r, n); return 3; } /* Set register r to the integer n, setting condition codes on scc */ static void load_integer(RealRegister r, int32 n) { load_integer0(r, n, 0); if (!(pending_regs & (1L << r))) { reg_values[r].typ = REGV_CONSTANT; reg_values[r].value = n; } } static void and_integer(RealRegister r1, RealRegister r2, int32 n, int32 peep) { int len; unsigned m; int32 s, t; RealRegister r_ip; int32 dead_r1; dead_r1 = nspareregs & (1 << r1); if (n == 0) { outop(F_MOV8, r1, 0, 0); return; } if (!disable_opt && (peep & P_CMPZ) && dead_r1) { if ((s = power_of_two(n)) >= 0) { outop(F_LSRK, r1, r2, (s+1) & 0x1f); andk_flag = n; return; } else { m = (unsigned)n; s = 0; while (!(m & 1)) m = m / 2, s++; t = 0; while (m & 1) m = m / 2, t++; if (m == 0) { if (s) { outop(F_LSRK, r1, r2, s); r2 = r1; } if (s+t < 32) { outop(F_LSLK, r1, r2, 32 - t); } return; } } } if ((s = constant_available(n)) >= 0) { if (r1 == s) { outop(F_AND, 0, r1, r2); } else { if (nspareregs & (1L << r2)) { outop(F_AND, 0, r2, s); if (!dead_r1) move_register(r1, r2); } else { move_register(r1, r2); outop(F_AND, 0, r1, s); } } return; } else if ((s = constant_available(~n)) >= 0) { if (r1 != s) { move_register(r1, r2); outop(F_BIC, 0, r1, s); return; } } if (power_of_two(n+1) >=0 || power_of_two(-n) >= 0) { m = (unsigned)n; s = 0; while (m & 1) m = m / 2, s++; if (!m) { outop(F_LSLK, r1, r2, 32 - s); outop(F_LSRK, r1, r1, 32 - s); return; } m = (unsigned)n; s = 0; while (m & 0x80000000) m = m * 2, s++; if (!m) { outop(F_LSRK, r1, r2, 32 - s); outop(F_LSLK, r1, r1, 32 - s); return; } } r_ip = R_IP; if (r2 == R_IP) syserr("and_integer: IP clash @ %.8lx", codebase+codep); len = load_integer0(R_IP, n, 1); if ((nspareregs & (1L << r2)) && load_integer0(R_IP, ~n, 1) < len) { load_integer(r_ip, ~n); outop(F_BIC, 0, r2, r_ip); if (!dead_r1) move_register(r1, r2); uses_IP = YES; } else { if (r1 == r2) { load_integer(r_ip, n); outop(F_AND, 0, r1, r_ip); uses_IP = YES; } else { load_integer(r1, n); outop(F_AND, 0, r1, r2); } } } static void multiply_integer(RealRegister r1, RealRegister r2, int32 n) { int32 s, k; RealRegister workreg; if (r2 == R_IP) syserr("multiply_integer: IP clash @ %.8lx", codebase+codep); /* Generate code for r1 = r2 * n. */ #if 0 printf("Multiply integer: R%d = R%d * %d\n", r1, r2, n); #endif workreg = r1; if (r1 == r2) workreg = R_IP; if (n==0) load_integer(r1, 0); else if (n==1) move_register(r1, r2); else if (n==-1) outop(F_NEG, 0, r1, r2); else if ((s = power_of_two(n)) >= 0) outop(F_LSLK, r1, r2, s); else if ((s = power_of_two(-n)) >= 0) { outop(F_LSLK, r1, r2, s); outop(F_NEG, 0, r1, r1); } else if ((s = power_of_two(n-1)) >= 0) { outop(F_LSLK, workreg, r2, s); outop(F_ADD3R, r1, workreg, r2); } else if ((s = power_of_two(n+1)) >= 0) { outop(F_LSLK, workreg, r2, s); outop(F_SUB3R, r1, workreg, r2); } else if ((s = power_of_two(1-n)) >= 0) { outop(F_LSLK, workreg, r2, s); outop(F_SUB3R, r1, r2, workreg); } else { if ((s = constant_available(n)) >= 0 && ((r1 != s) || (r2 != s))) { if (r1 == s && s != r2) outop(F_MUL, 0, s, r2); else { if ((nspareregs & (1L << r2)) && s != r2) { /* This may allow a subsequent elimination of the move */ outop(F_MUL, 0, r2, s); move_register(r1, r2); } else { move_register(r1, r2); outop(F_MUL, 0, r1, s); } } return; } /* ECN: not sure this is sensible */ if ((n < 0 || n > 255) || !(config & CONFIG_OPTIMISE_SPACE)) { k = 0; while (!(n & 1)) n /= 2, k++; if ((s = power_of_two(n-1)) >= 0) { outop(F_LSLK, workreg, r2, s); outop(F_ADD3R, r1, workreg, r2); outop(F_LSLK, r1, r1, k); return; } else if ((s = power_of_two(n+1)) >= 0) { outop(F_LSLK, workreg, r2, s); outop(F_SUB3R, r1, workreg, r2); outop(F_LSLK, r1, r1, k); return; } n <<= k; } load_integer(workreg, n); if (r1 == r2) outop(F_MUL, 0, r1, R_IP); else outop(F_MUL, 0, r1, r2); } } /* Fix up correctly a big displacement by using R_IP which has been */ /* reserved by regalloc.c */ static int32 bigindex(RealRegister r, int32 m) { if ((m & 3) == 0 && m >= 0 && m < 128) return -1; uses_IP = YES; add_integer(R_IP, r, m & ~(0x1f << 2)); return m & (0x1f << 2); } static int32 bigindexshort(RealRegister r, int32 m) { if ((m & 1) == 0 && m >= 0 && m < 64) return -1; uses_IP = YES; add_integer(R_IP, r, m & ~(0x1f << 1)); return m & (0x1f << 1); } static int32 bigindexbyte(RealRegister r, int32 m) { if (m >= 0 && m < 32) return -1; uses_IP = YES; add_integer(R_IP, r, m & ~0x1f); return m & 0x1f; } #define M_VARREGS (regbit(R_V1+NVARREGS)-regbit(R_V1)) #ifdef DEBUG_THUMB_CPLUSPLUS extern int sanity_check_has_callr; #endif static void routine_entry(int32 m) { int32 mask = (regmask & M_VARREGS); int32 n; int32 sp_offset; int32 res_regs; int32 i; if (procauxflags & bitoffnaux_(s_irq)) cc_err(gen_err_irq, compiler_name()); current_procnum++; label_values = label_references = NULL; fp_minus_sp = 0; available_branches = 0; reg_flush(); pushed_args = 0; firstargoff = -16; stack_args_split = 0; res_regs = currentfunction.nresultregs; nspareregs = (regmask & M_VARREGS) & ((1 << 4) | (1 << 5) | (1 << 6) | (1 << 7)); if (R_IP >= R_V1) mask |= regbit(R_IP); r_fr = R_IP; m = k_argwords_(m); #ifdef DEBUG_THUMB_CPLUSPLUS if (sanity_check_has_callr && !(mask & regbit(R_FR))) syserr("function at %08x has CALLR but R7 not saved", codebase); sanity_check_has_callr = 0; #endif if ((0 && usrdbg(DBG_PROC)) || ((procflags & STACKCHECK) && !no_stack_checks && !(pcs_flags & PCS_NOSTACKCHECK) && greatest_stackdepth > 256) || ((procflags & BLK0EXIT) && m >= NARGREGS)) { r_fr = R_FR; mask |= regbit(R_FR); } n = (m <= NARGREGS) ? m : NARGREGS; if (procflags & BLK0EXIT && m >= NARGREGS) { r_fr = R_FR; mask |= regbit(R_FR); } for (i = n; i < 4; i++) nspareregs |= 1L << i; if (procflags & ARGS2STACK) { BindList *bl; Binder *b; int32 p; bl = currentfunction.argbindlist; p = 0; while (bl && p < 16) { b = bl->bindlistcar; p = bindaddr_(b); if ((p & BINDADDR_MASK) != BINDADDR_ARG) syserr("Binder not BINDADDR_ARG in argbindlist"); p = p & ~BINDADDR_MASK; p += bindmcrep_(b) & MCR_SIZE_MASK; bl = bl->bindlistcdr; } if (n != 0) { if (!IS_VARIADIC(m) && !(p > 16)) { mask |= regbit(R_A1+n) - regbit(R_A1); argwordsbelowfp = n; realargwordsbelowfp = n; stack_args_split = 1; } else { if (res_regs >= 4 || (procflags & BLK0EXIT)) { r_fr = R_FR; mask |= regbit(R_FR); } fpdesc_setinitoffset(-4-n*4); outop(F_PUSH, 0, 0, regbit(R_A1+n) - regbit(R_A1)); } } pushed_args = n; firstargoff = 0; } else argwordsbelowfp = n; pushed_lr = 0; procmask = mask; sp_offset = 4*bitcount(mask); fpdesc_enterproc(); if (0 && usrdbg(DBG_PROC)) { outop(F_SUBSP, 0, 0, 16 >> 2); outop(F_PUSH, 0, 0, mask); outop(F_MOVHL, 0, R_FR, R_PC-8); outop(F_ADDI8, R_FR, 0, 6); outop(F_STRSP, R_FR, 0, (sp_offset+3*4) >> 2); outop(F_MOVHL, 0, R_FR, R_LR-8); outop(F_STRSP, R_FR, 0, (sp_offset+2*4) >> 2); outop(F_ADDRSP, R_FR, 0, (sp_offset+4*4+pushed_args*4) >> 2); outop(F_STRSP, R_FR, 0, (sp_offset+1*4) >> 2); outop(F_MOVHL, 0, R_FR, R_FP-8); outop(F_STRSP, R_FR, 0, (sp_offset+0*4) >> 2); outop(F_ADDRSP, R_FR, 0, (sp_offset+3*4) >> 2); outop(F_MOVLH, 0, R_FP-8, R_FR); firstargoff += 4*4; } else { if ((regmask & (1<<R_LR)) || procflags & NONLEAF || ((config & CONFIG_OPTIMISE_SPACE) && mask && !(pcs_flags & PCS_INTERWORK))) { if ((procflags & BLK0EXIT) || ((pcs_flags & PCS_INTERWORK) && res_regs >= 4)) { r_fr = R_FR; mask |= regbit(R_FR); } procmask = mask; sp_offset = 4*bitcount(mask); pushed_lr = 1; outop(F_PUSH, 0, 0, 0x100 | mask); intsavewordsbelowfp = bitcount((0x100 | mask) & ~M_ARGREGS); firstargoff += 4; } else { if (mask) outop(F_PUSH, 0, 0, mask); intsavewordsbelowfp = bitcount(mask & ~M_ARGREGS); } } firstargoff += sp_offset;; if ((procflags & STACKCHECK) && !no_stack_checks && !(pcs_flags & PCS_NOSTACKCHECK)) { Symstr *name = stackoverflow; LabelNumber *ll; n = greatest_stackdepth; if (n <= 256) { outop(F_CMPHH, 0, R_SP-8, R_SL-8); } else { name = stack1overflow; outop(F_MOVHH, 0, ARM_R_IP-8, R_SP-8); load_integer(R_FR, -n); outop(F_ADDLH, 0, ARM_R_IP-8, R_FR); outop(F_CMPHH, 0, ARM_R_IP-8, R_SL-8); } ll = nextlabel(); AddLabelReference(codep, ll); addfref_(ll, codep | LABREF_BC); outop(F_BC, 0, C_of_Q(Q_GE), 0); call_k(name); setlabel(ll); } setlabel(entrylab); if (target_stack_moves_once) { add_integer(R_SP, R_SP, -greatest_stackdepth); fp_minus_sp += greatest_stackdepth; } } static void add_to_sp(int32 diff) { add_integer(R_SP, R_SP, diff * 4); } static void routine_exit(int to_pc) { int32 mask = procmask; int32 i, n; int32 sp_offset; int32 res_regs; res_regs = currentfunction.nresultregs; if (!res_regs) res_regs = 1; sp_offset = 4*bitcount(mask); if (0 && usrdbg(DBG_PROC)) { add_to_sp(fp_minus_sp/4); outop(F_LDRSP, R_IP, 0, (sp_offset+0*4) >> 2); outop(F_MOVLH, 0, R_FP-8, R_IP); if (to_pc && res_regs < 4) { if (mask) outop(F_POP, 0, 0, mask); outop(F_LDRSP, R_A1+3, 0, (2*4) >> 2); add_to_sp(4 + pushed_args); flush_pending(1 << R_SP); if (pcs_flags & PCS_INTERWORK) outop(F_BX_L, 0, R_A1+3, 0); else outop(F_MOVLH, 0, R_PC-8, R_A1+3); } else { /* Ugh */ outop(F_LDRSP, r_fr, 0, (sp_offset+2*4) >> 2); outop(F_MOVLH, 0, R_LR-8, r_fr); if (mask) outop(F_POP, 0, 0, mask); add_to_sp(4 + pushed_args); flush_pending(1 << R_SP); if (to_pc) { if (pcs_flags & PCS_INTERWORK) outop(F_BX_H, 0, R_LR-8, 0); else outop(F_MOVHH, 0, R_PC-8, R_LR-8); } } } else { if (pending_regs & (1 << R_SP)) { assert(reg_values[R_SP].typ == REGV_BASE); assert(reg_values[R_SP].reg == R_SP); fp_minus_sp += reg_values[R_SP].value; pending_regs &= ~(1 << R_SP); } fp_minus_sp /= 4; assert(fp_minus_sp >= 0); mask &= ~0x0f; if (procflags & ARGS2STACK && pushed_args != 0 && stack_args_split == 0) { if (fp_minus_sp <= 4 - res_regs && (config & CONFIG_OPTIMISE_SPACE)) { for (i = 0; i < fp_minus_sp; i++) mask |= 1L << (3-i); } else add_to_sp(fp_minus_sp); if (to_pc && res_regs < 4) { if (mask) outop(F_POP, 0, 0, mask); outop(F_POP, 0, 0, regbit(R_A1+3)); add_to_sp(pushed_args); flush_pending(1 << R_SP); if (pcs_flags & PCS_INTERWORK) outop(F_BX_L, 0, R_A1+3, 0); else outop(F_MOVLH, 0, R_PC-8, R_A1+3); } else { /* Ugh */ outop(F_LDRSP, r_fr, 0, sp_offset >> 2); outop(F_MOVLH, 0, R_LR-8, r_fr); if (mask) outop(F_POP, 0, 0, mask); add_to_sp(1 + pushed_args); flush_pending(1 << R_SP); if (to_pc) { if (pcs_flags & PCS_INTERWORK) outop(F_BX_H, 0, R_LR-8, 0); else outop(F_MOVHH, 0, R_PC-8, R_LR-8); } } } else { n = pushed_args + fp_minus_sp; /* This optimisation is really horrible. Consider removing? */ if (to_pc && n <= 4 - res_regs && (config & CONFIG_OPTIMISE_SPACE)) { for (i = 0; i < n; i++) mask |= 1L << (3-i); } else add_to_sp(n); if (pushed_lr) { if (!to_pc || (pcs_flags & PCS_INTERWORK)) { if (to_pc && res_regs < 4) { if (mask) outop(F_POP, 0, 0, mask); outop(F_POP, 0, 0, regbit(R_A1+3)); outop(F_BX_L, 0, R_A1+3, 0); } else { outop(F_LDRSP, r_fr, 0, sp_offset >> 2); outop(F_MOVLH, 0, R_LR-8, r_fr); if (mask) outop(F_POP, 0, 0, mask); add_to_sp(1); flush_pending(1 << R_SP); if (to_pc) outop(F_BX_H, 0, R_LR-8, 0); } } else { outop(F_POP, 0, 0, 0x100 | mask); } } else { if (mask) outop(F_POP, 0, 0, mask); if (to_pc) { if (pcs_flags & PCS_INTERWORK) outop(F_BX_H, 0, R_LR-8, 0); else outop(F_MOVHH, 0, R_PC-8, R_LR-8); } } } } } static int simple_routine_exit(void) { if (fp_minus_sp) return 0; return (!(procflags & ARGS2STACK) || pushed_args == 0) && !usrdbg(DBG_PROC); } static int32 pcref(int32 dest, int32 size) { int32 d; d = (dest - codep - PC_OFFSET) / 2; if (d < -size || d >= size) syserr(syserr_displacement, d); return d & (size - 1); } typedef struct Backwards_Branch { struct Backwards_Branch *cdr; LabelNumber *real_dest; LabelNumber *faked_dest; } Backwards_Branch; Backwards_Branch *backwards_branches; static void add_casebranch(LabelNumber *destination) { if (lab_isset_(destination)) { if (destination == returnlab && !(config & CONFIG_OPTIMISE_SPACE)) { destination = returnlab = nextlabel(); } else { Backwards_Branch *b = NewSyn(Backwards_Branch); cdr_(b) = backwards_branches; b->real_dest = destination; b->faked_dest = destination = nextlabel(); backwards_branches = b; } } { LabelNumber *ll = NULL; int32 max_dest = casebranch_codep + branch_range((use_dcw ? FREF_DCW : FREF_DCB) | Q_AL); FRef_Branch *new_fref, *fref; FRef_Branch **fref_p = &fref_branches; for (; (fref = *fref_p) != NULL; fref_p = &cdr_(fref)) { if (destination == fref->real_dest && FREF_CONDITION(fref->flags) == Q_AL) { if (max_dest < fref->pcref + branch_range(fref->flags)) { *fref_p = cdr_(fref); if (cdr_(fref) == NULL) fref_branches_head = fref_p; fref_p = &fref_branches; new_fref = fref; for (; (fref = *fref_p) != NULL; fref_p = &cdr_(fref)) { if (max_dest <= fref->pcref + branch_range(fref->flags)) break; } cdr_(new_fref) = fref; new_fref->pcref = casebranch_codep; new_fref->codep = codep; new_fref->flags = Q_AL | (use_dcw ? FREF_DCW : FREF_DCB); *fref_p = new_fref; if (fref == NULL) fref_branches_head = &cdr_(new_fref); fref = new_fref; } ll = fref->chained_dest; break; } } if (fref == NULL) { ll = nextlabel(); fref_p = &fref_branches; for (; (fref = *fref_p) != NULL; fref_p = &cdr_(fref)) if (max_dest <= fref->pcref + branch_range(fref->flags)) break; new_fref = NewSyn(FRef_Branch); cdr_(new_fref) = fref; new_fref->pcref = casebranch_codep; new_fref->codep = codep; new_fref->flags = Q_AL | (use_dcw ? FREF_DCW : FREF_DCB); new_fref->real_dest = destination; new_fref->chained_dest = ll; *fref_p = new_fref; if (fref == NULL) fref_branches_head = &cdr_(new_fref); branchpoolsize += 2; } if (use_dcw) { AddLabelReference(codep, ll); addfref_(ll, codep| LABREF_BXX_16); outDCW(codep - casebranch_codep); } else { AddLabelReference(codep, ll); addfref_(ll, codep | LABREF_BXX_8); outDCB((codep - casebranch_codep) >> 1); } } } static LabelNumber *add_fref_branch(LabelNumber *destination, int32 codep, uint32 condition) { LabelNumber *ll; FRef_Branch *new_fref, *fref, **fref_p; int32 max_dest; int32 span; #if 0 fprintf(stderr, "%.8x: (add_fref_branch) F%dL%d\n", codebase + codep, current_procnum, lab_name_(destination) & 0xfffff); #endif span = branch_range(FREF_BRANCH | condition); max_dest = codep + span; fref_p = &fref_branches; for (; (fref = *fref_p) != NULL; fref_p = &cdr_(fref)) { if (destination == fref->real_dest && (FREF_CONDITION(fref->flags) == Q_AL || FREF_CONDITION(fref->flags) == condition)) { if (condition == Q_AL && codep - fref->pcref > (FREF_TYPE(fref->flags) == FREF_BRANCH ? 1024 : 256)) { *fref_branches_head = fref; *fref_p = cdr_(fref); cdr_(fref) = NULL; fref_branches_head = &cdr_(fref); setlabel1(fref->chained_dest); fref->chained_dest = nextlabel(); fref->pcref = codep; fref->codep = codep; fref->flags = condition | FREF_BRANCH; } else { if (max_dest < fref->pcref + branch_range(fref->flags)) { *fref_p = cdr_(fref); if (cdr_(fref) == NULL) fref_branches_head = fref_p; fref_p = &fref_branches; new_fref = fref; for (; (fref = *fref_p) != NULL; fref_p = &cdr_(fref)) { if (max_dest <= fref->pcref + branch_range(fref->flags)) break; } cdr_(new_fref) = fref; new_fref->pcref = codep; new_fref->codep = codep; new_fref->flags = condition | FREF_BRANCH; *fref_p = new_fref; if (!fref) fref_branches_head = &cdr_(new_fref); fref = new_fref; } } AddLabelReference(codep, fref->chained_dest); recalc_mustbranchlitby(); return fref->chained_dest; } } ll = nextlabel(); fref_p = &fref_branches; for (; (fref = *fref_p) != NULL; fref_p = &cdr_(fref)) { if (max_dest <= fref->pcref + branch_range(fref->flags)) break; } new_fref = NewSyn(FRef_Branch); cdr_(new_fref) = fref; new_fref->pcref = codep; new_fref->codep = codep; new_fref->flags = condition | FREF_BRANCH; new_fref->real_dest = destination; new_fref->chained_dest = ll; *fref_p = new_fref; if (fref == NULL) fref_branches_head = &cdr_(new_fref); branchpoolsize += 2; AddLabelReference(codep, ll); recalc_mustbranchlitby(); return new_fref->chained_dest; } static void add_branch(LabelNumber *dest, int32 condition, int32 codep) { Branch *b = NewSyn(Branch); cdr_(b) = available_branches; available_branches = b; b->codep = codep; b->condition = condition; b->dest = dest; } static Branch *branch_available(LabelNumber *dest, int32 condition) { int32 span = condition == Q_AL ? 2036 : 244; int32 max_dest = codep - span; Branch *b = available_branches; Branch *use_b = NULL; for (; b != NULL && b->codep >= max_dest; b = cdr_(b)) { if (b->dest == dest && (b->condition == Q_AL || (b->condition == condition && (!use_b || use_b->condition != Q_AL)))) use_b = b; } return use_b; } static void conditional_branch_to(int32 condition, LabelNumber *destination, int use_bl) { LabelNumber *ll; Branch *b; int32 inst_codep; if (destination == RETLAB) { /* Only the result registers matter on function exit */ int32 i = 0; int32 regs = 0; do { regs |= 1L << i; i++; } while (i < currentfunction.nresultregs); if (condition == Q_AL) spareregs |= procmask & ~regs; ldm_flush(); /* Ensure final values of result registers + any V registers not * in procmask. These must be assignments to global registers so * need to be flushed here */ flush_pending(regs | (0xf0 & ~procmask)); destination = returnlab; if (condition == Q_AL) { /* if get an unconditional return expand it inline */ /* and save its address if it was the first */ pending_regs &= (1 << R_SP); return_pending = 0; if (simple_routine_exit() || !lab_isset_(destination)) { flush_pending(1 << R_SP); if (!lab_isset_(destination)) { setlabel(destination); } dbg_return(codebase+codep); routine_exit(1); return; } } else { if (flags_reg != NoRegister) flush_pending(1L << flags_reg); if (!lab_isset_(destination)) return_pending = 1; } } else { ldm_flush(); flush_pending(0xff); } flush_pending(1 << R_SP); if ((condition & ~Q_UBIT) == Q_NE && cmp_reg != NoRegister) { reg_values[cmp_reg].typ = REGV_CONSTANT; reg_values[cmp_reg].value = cmp_value; } /* * Unconditional branches can reach MUCH further than conditional ones... */ inst_codep = codep; if (condition == Q_AL) { if (lab_isset_(destination) || use_bl) { /* u.defn shares with u.frefs */ int32 dest = destination->u.defn & 0xffffff; int32 span = dest - (codep + PC_OFFSET); ll = destination; if (use_bl || span < -2048 || span >= 2048) { if (!pushed_lr) syserr(syserr_leaf_fn, symname_(currentfunction.symstr)); if (!use_bl && (b = branch_available(destination, condition)) != 0) { ll = nextlabel(); AddLabelReference(inst_codep, ll); outop(F_B, 0, 0, pcref(b->codep, 0x800)); setlabel2(ll, b->codep); } else { int32 d; AddLabelReference(inst_codep, ll); d = 0; if (!lab_isset_(destination)) addfref_(destination, codep | LABREF_BL); else d = pcref(dest, 0x400000); outop(F_CALL1, 0, 0, (d >> 11) & 0x7ff); outop(F_CALL, 0, 0, d & 0x7ff); } } else { AddLabelReference(inst_codep, ll); outop(F_B, 0, 0, pcref(dest, 0x800)); } add_branch(destination, condition, inst_codep); } else { ll = add_fref_branch(destination, codep, Q_AL); addfref_(ll, codep | LABREF_B); outop(F_B, 0, 0, 0); } } else { if (lab_isset_(destination)) { /* u.defn shares with u.frefs */ int32 span = (destination->u.defn & 0x00ffffff) - (codep+PC_OFFSET); if (span >= -256 && span < 256) { ll = destination; AddLabelReference(inst_codep, ll); outop(F_BC, 0, C_of_Q(condition), pcref(destination->u.defn & 0x00ffffff, 0x100)); add_branch(destination, condition, inst_codep); } else { ll = nextlabel(); if ((b = branch_available(destination, codep)) != 0) { AddLabelReference(inst_codep, ll); outop(F_BC, 0, C_of_Q(condition), pcref(b->codep, 0x100)); setlabel2(ll, b->codep); } else { AddLabelReference(inst_codep, ll); addfref_(ll, codep | LABREF_BC); outop(F_BC, 0, C_of_Q(Q_NEGATE(condition)), 0); conditional_branch_to(Q_AL, destination, 0); setlabel(ll); } } } else { ll = add_fref_branch(destination, codep, condition); addfref_(ll, codep | LABREF_BC); outop(F_BC, 0, C_of_Q(condition), 0); } } } static void dump_backwards_branches(void) { Backwards_Branch *b; for (b = backwards_branches; b != NULL; b = cdr_(b)) { setlabel(b->faked_dest); conditional_branch_to(Q_AL, b->real_dest, 0); } backwards_branches = NULL; } static int is_commutative(int32 op) { return op == F_AND || op == F_EOR || op == F_OR || op == F_MUL; } static void rk_op(int32 op, int32 r1, int32 r2, int32 m) { int32 r; int32 dead_r1 = nspareregs & (1 << r1); if (r2 == R_IP) syserr("op = %x: IP clash @ %.8lx", (int)op, codebase+codep); r = constant_available(m); if (r >= 0) { if (r == r1) { if (is_commutative(op)) { outop(op, 0, r1, r2); return; } } else { if (nspareregs & (1L << r2)) { outop(op, 0, r2, r); if (!dead_r1) move_register(r1, r2); } else { move_register(r1, r2); outop(op, 0, r1, r); } return; } } if (r1 == r2) { load_integer(R_IP, m); outop(op, 0, r1, R_IP); } else if (is_commutative(op)) { load_integer(r1, m); outop(op, 0, r1, r2); } else { load_integer(R_IP, m); if (nspareregs & (1L << r2)) { /* Better this way ... * MOV may be eliminated later */ outop(op, 0, r2, R_IP); if (!dead_r1) move_register(r1, r2); } else { move_register(r1, r2); outop(op, 0, r1, R_IP); } } } static void rr_op(int32 op, int32 r1, int32 r2, int32 m) { int32 r_ip; int32 dead_r1 = nspareregs & (1 << r1); if (r1 == r2) { outop(op, 0, r1, m); } else if (r1 == m) { switch (op) { case F_AND: case F_OR: case F_EOR: case F_MUL: #ifdef THUMB_INLINE_ASSEMBLER case F_ADC: #endif outop(op, 0, r1, r2); break; case F_BIC: outop(F_MVN, 0, r1, r1); outop(F_AND, 0, r1, r2); break; case F_LSL: case F_LSR: case F_ASR: case F_ROR: #ifdef THUMB_INLINE_ASSEMBLER case F_SBC: #endif if (r2 == R_IP) syserr("F_LSL/F_LSR/F_ASR/F_ROR: IP clash @ %.8lx", codebase+codep); r_ip = R_IP; if (nspareregs & (1L << r2)) r_ip = r2; move_register(r_ip, r2); outop(op, 0, r_ip, r1); if (!dead_r1) move_register(r1, r_ip); break; } } else { if ((nspareregs & (1L << r2)) && !(op == F_MUL && r2 == m)) { outop(op, 0, r2, m); if (!dead_r1) move_register(r1, r2); } else { move_register(r1, r2); outop(op, 0, r1, m); } } } static int32 pending_op = -1; static int32 pending_r1, pending_r2; static int32 saved_spareregs; static void debug_putc(char c) { cc_msg("%c", c); } #if 0 static char *nameof_cond(int32 condition) { switch (condition & ~Q_UBIT) { case Q_EQ & ~Q_UBIT: return "EQ"; case Q_NE & ~Q_UBIT: return "NE"; case Q_HS & ~Q_UBIT: return "CS"; case Q_LO & ~Q_UBIT: return "CC"; case Q_PL & ~Q_UBIT: return "PL"; case Q_MI & ~Q_UBIT: return "MI"; case Q_HI & ~Q_UBIT: return "HI"; case Q_LS & ~Q_UBIT: return "LS"; case Q_GE & ~Q_UBIT: return "GE"; case Q_LT & ~Q_UBIT: return "LT"; case Q_GT & ~Q_UBIT: return "GT"; case Q_LE & ~Q_UBIT: return "LE"; case Q_AL & ~Q_UBIT: return "AL"; default: syserr("unknown condition %x\n", condition); return "??"; } } #endif #define BaseIsWordAligned(op, base, peep) (((op) & J_BASEALIGN4) || (base) == R_SP || ((peep) & P_BASEALIGNED)) void show_inst_direct(PendingOp *p) { J_OPCODE op = p->ic.op; RealRegister r1 = p->ic.r1.rr, r2 = p->ic.r2.rr, m = p->ic.r3.i; int32 peep = p->peep, deadbits = p->dataflow; int32 illbits; int32 w; RealRegister r1r = NoRegister, r2r = NoRegister, mr = NoRegister; int len; J_OPCODE op1; int32 i, n; CheckJopcodeP(p, JCHK_MEM | JCHK_REGS | JCHK_SYSERR); #if 0 { FRef_Branch *fref; cc_msg("mustbranchlitby = %.8x (branchpoolsize = %.8x)\n", codebase + mustbranchlitby, branchpoolsize); for (fref = fref_branches; fref != NULL; fref = cdr_(fref)) { if (FREF_TYPE(fref->flags) == FREF_DCB) cc_msg("@%.8x, DCB F%dL%d (F%dL%d) (pcref = %.8x)\n", codebase + fref->codep, current_procnum, lab_name_(fref->chained_dest) & 0xfffff, current_procnum, lab_name_(fref->real_dest) & 0xfffff, fref->pcref); else cc_msg("@%.8x, B%s F%dL%d (F%dL%d) (pcref = %.8x)\n", codebase + fref->codep, nameof_cond(FREF_CONDITION(fref->flags)), current_procnum, lab_name_(fref->chained_dest) & 0xfffff, current_procnum, lab_name_(fref->real_dest) & 0xfffff, fref->pcref); } } #endif nspareregs = spareregs; op1 = op & J_TABLE_BITS; if (op1 == J_CALLK || op1 == J_OPSYSK || op1 == J_CALLR) { #if 0 /* /* ECN - Need to rethink this. This set is wrong if the usage of caller * save registers is precisely known. */ nspareregs |= 0x0f; #endif n = k_resultregs_(r2); for (i = 0; i < n; i++) nspareregs &= ~(1L << i); } if (debugging(DEBUG_LOCALCG)) { cc_msg("%.8lx ", codebase+codep); if (a_uses_r1(p) && (deadbits & J_DEAD_R1)) debug_putc('*'); else debug_putc('-'); if (a_uses_r2(p) && (deadbits & J_DEAD_R2)) debug_putc('*'); else debug_putc('-'); if (a_uses_r3(p) && (deadbits & J_DEAD_R3)) debug_putc('*'); else debug_putc('-'); if (a_loads_r1(p)) debug_putc('!'); else debug_putc('-'); if (a_loads_r2(p)) debug_putc('!'); else debug_putc('-'); if (peep & P_CMPZ) debug_putc('#'); else debug_putc(' '); if (peep & P_BASEALIGNED) debug_putc('%'); else debug_putc(' '); if (op & J_BASEALIGN4) debug_putc('^'); else debug_putc(' '); } if (peep & P_CMPZ) { ldm_flush(); flush_pending(0xff | (1 << R_SP)); } if (a_uses_r1(p)) { r1r = r1; /* Fails on inline assembler... if (r1r >= 8 && op1 != J_MOVR && op1 != J_ADDR && !(r1r == R_SP && op1 == J_ADDK) syserr("r1 = %d, op = %d", (int)r1, (int)op1); */ if (deadbits & J_DEAD_R1) nspareregs |= 1L << r1; } if (a_uses_r2(p)) { r2r = r2; if (r2r >= 8 && op1 != J_MOVR && op1 != J_ADDR && r2r != R_SP) syserr("r2 = %d, op = %d", (int)r2, (int)op1); if (deadbits & J_DEAD_R2) nspareregs |= 1L << r2; } if (a_uses_r3(p)) { mr = m; if (mr >= 8 && op1 != J_MOVR && op1 != J_ADDR && !(mr == R_SP && (op1 == J_SUBR || op1 == J_CMPR))) syserr("mr = %d, op = %d", (int)mr, (int)op1); if (deadbits & J_DEAD_R3) nspareregs |= 1L << m; } if (a_loads_r1(p) && !(deadbits & J_DEAD_R1)) nspareregs &= ~(1L << r1); if (a_loads_r2(p) && !(deadbits & J_DEAD_R2)) nspareregs &= ~(1L << r2); if (debugging(DEBUG_LOCALCG)) { for (i = 0; i < 8; i++) debug_putc((int)((nspareregs & (1L << i)) ? '0' + i : '-')); if ((op & J_TABLE_BITS) > J_LAST_JOPCODE) cc_msg(" %-3ld %ld, %ld, %ld\n", (op & J_TABLE_BITS), p->ic.r1.rr, p->ic.r2.rr, p->ic.r3.rr); else print_jopcode (&p->ic); } op &= ~J_DEADBITS; if (op1 != J_BXX) { casebranch_pending = -1; if (codep & 1) outDCB(0); if (casebranch_litpool) { char b[32]; sprintf(b, "x$litpool$%d", literal_pool_number); obj_symref(sym_insert_id(b), xr_code+xr_defloc+xr_dataincode, (casebranch_litpool+3) & ~3); sprintf(b, "x$litpool_e$%d", literal_pool_number++); obj_symref(sym_insert_id(b), xr_code+xr_defloc+xr_dataincode, codebase+codep-1); casebranch_litpool = 0; } if (backwards_branches) dump_backwards_branches(); } if (deadcode) { if (op1 != J_LABEL && op1 != J_ENDPROC) { goto windup; } else { if (!(op1 == J_LABEL && deadcode == (LabelNumber *)m)) { conditional_branch_to(Q_AL, deadcode, 0); dump_branch_lits(0, 0); } deadcode = 0; } } if (pending_op >= 0) { int32 tmp_spareregs; if (op1 == J_ADDK && !(peep & P_CMPZ) && m == 4 && r1r == r2r && r1r == pending_r2) { w = F_LDM; if (pending_op == F_STRI5) w = F_STM; spareregs = saved_spareregs; outop(w, pending_r2, 0, 1L << pending_r1); pending_op = -1; goto windup; } tmp_spareregs = spareregs; spareregs = saved_spareregs; outop(pending_op, pending_r2, pending_r1, 0); spareregs = tmp_spareregs; pending_op = -1; } /* Don't dump literals just before an ENDPROC as otherwise the * 'branch round literals' will never be resolved. */ if (op1 != J_ENDPROC) { if (codep >= mustlitby - branchpoolsize) { dumplits(1); } if (codep >= mustbranchlitby) dump_branch_lits(1, 0); } illbits = op & (Q_MASK | J_SIGNED | J_UNSIGNED); switch(op & ~(Q_MASK | J_SIGNED | J_UNSIGNED | J_BASEALIGN4)) { #define rkop(inst) rk_op(inst, r1r, r2r, m) #define rrop(inst) rr_op(inst, r1r, r2r, mr) #ifdef THUMB_CPLUSPLUS case J_WORD_ADCON: cnop(); obj_symref((Symstr *)m, xr_code, 0); AddCodeXref4(X_absreloc | codebase+codep, (Symstr *)m, 0); outcodeword(0, LIT_ADCON); break; case J_WORD_LABEL: cnop(); addfref_((LabelNumber *)m, codep | LABREF_WORD32); outcodeword(0, LIT_ADCON); break; #endif case J_WORD: flush_pending(0xff | (1 << R_SP)); ldm_flush(); outHW(m); break; case J_ADCONF: case J_ADCOND: load_fp_adcon(r1r, op, (FloatCon *)m); break; case J_ADCONLL: load_ll_adcon(r1r, op, (Int64Con *)m); break; case J_CMPR: if (r2r == R_SP) outop(F_CMPLH, 0, R_SP-8, mr); else if (mr == R_SP) outop(F_CMPHL, 0, r2r, R_SP-8); else outop(F_CMP, 0, r2r, mr); illbits &= ~Q_MASK; peep &= ~P_CMPZ; break; #ifdef THUMB_INLINE_ASSEMBLER case J_CMNR: outop(F_CMN, 0, r2r, mr); illbits &= ~Q_MASK; peep &= ~P_CMPZ; break; #endif case J_MOVR: move_register(r1r, mr); if (peep & P_CMPZ) { if (r1r >= 8 && mr >= 8) syserr("peep & P_CMPZ && r1 >= 8 && mr >= 8"); if (r1r >= 8) outop(F_CMP8, mr, 0, 0); if (mr >= 8) outop(F_CMP8, r1r, 0, 0); } peep &= ~P_CMPZ; break; case J_NEGR: outop(F_NEG, 0, r1r, mr); peep &= ~P_CMPZ; break; case J_NOTR: outop(F_MVN, 0, r1r, mr); peep &= ~P_CMPZ; break; case J_MOVK: load_integer(r1r, m); break; case J_CALLK: call_k((Symstr *)m); break; case J_TAILCALLK: { int32 d; int32 dest; int32 n; ldm_flush(); if ((Symstr *)m == currentfunction.symstr) { dest = entrylab->u.defn & 0xffffff; if ((n = pushed_args) != 0) { outop(F_ADDSP, 0, 0, n*4); outop(F_PUSH, 0, 0, regbit(R_A1+n) - regbit(R_A1)); } flush_pending(0xff | (1 << R_SP)); d = (dest - codep - PC_OFFSET) / 2; if (d >= -0x400) { AddLabelReference(codep, entrylab); outop(F_B, 0, 0, d & 0x7ff); } else { load_adcon(r_fr, (Symstr *)m, dest); outop(F_MOVLH, 0, R_PC-8, r_fr); } break; } #ifdef THUMB_CPLUSPLUS flush_pending(0xff | (1<<R_SP)); arm_tailcall_k((Symstr *)m); #else syserr("Non recursive tailcall to $r in $r", (Symstr *)m, currentfunction.symstr); #endif break; } case J_TAILCALLR: /* Pending rethink about J_TAILCALLR */ syserr("Thumb cannot handle J_TAILCALLR"); ldm_flush(); flush_pending(0xff); if ((procmask & M_VARREGS & regbit(mr)) || mr == R_IP) { outop(F_MOVLH, 0, ARM_R_IP-8, mr); routine_exit(0); outop(F_BX_H, 0, ARM_R_IP-8, 0); } else { routine_exit(0); outop(F_BX_L, 0, mr, 0); } break; case J_OPSYSK: { RealRegister i; if (p->ic.r2.i & K_SPECIAL_ARG) outop(F_MOVLH, 0, ARM_R_IP-8, TARGET_SPECIAL_ARG_REG); ldm_flush(); flush_pending(0xff | (1 << R_SP)); for (i = 0; i < 4; i++) reg_values[i].typ = REGV_UNKNOWN; outop(F_SWI, 0, 0, m); flags_reg = NoRegister; andk_flag = 0; cmp_reg = NoRegister; } break; case J_CALLR: #if 0 if (pcs_flags & PCS_INTERWORK) { call_k(call_via[mr]); } else { RealRegister i; ldm_flush(); flush_pending(0xff | (1 << R_SP)); for (i = 0; i < 4; i++) reg_values[i].typ = REGV_UNKNOWN; outop(F_MOVHH, 0, R_LR-8, R_PC-8); outop(F_MOVLH, 0, R_PC-8, mr); flags_reg = NoRegister; andk_flag = 0; cmp_reg = NoRegister; } #else call_k(call_via[mr]); #endif break; case J_ADCON: { Symstr *name = (Symstr *)m; int32 offset = (int32)r2; load_adcon(r1r, name, offset); } break; case J_INFOLINE: ldm_flush(); flush_pending(ALL_REGS); dbg_addcodep((VoidStar)r1, codebase+codep); break; case J_INFOSCOPE: ldm_flush(); flush_pending(ALL_REGS); dbg_addcodep(NULL, codebase+codep); break; case J_INFOBODY: dbg_bodyproc(); break; case J_STRING: { StringSegList *s; int32 disp; s = (StringSegList *)m; ldm_flush(); flush_pending(0xff | (1 << R_SP)); w = 0; if (r2 >= 0) w = r2 & ~3; disp = lit_findstringincurpool(s); if (disp >= 0) { addfref_(litlab, codep | LABREF_WORD8); AddLitPoolReference(codep, disp); outop(F_ADDRPC, r1r, 0, (disp + w) / 4); } else { disp = lit_findstringinprevpools(s, codebase+codep+PC_OFFSET-252+w); if (disp >= 0) { disp = codebase+codep+PC_OFFSET-disp+w; outop(F_MOVHL, 0, r1r, R_PC-8); outop(F_SUBI8, r1r, 0, disp); } else { if (stringlength(s) > 8 && (disp = lit_findstringinprevpools(s, 0)) >= 0) { load_adcon(r1r, bindsym_(codesegment), disp+r2); } else { addressability(1024 - r2); addfref_(litlab, codep | LABREF_WORD8); AddLitPoolReference(codep, litpoolp << 2); outop(F_ADDRPC, r1r, 0, litpoolp + w / 4); codeseg_stringsegs(s, 1); } } } if (w ^ r2) add_integer(r1r, r1r, w ^ r2); } break; case J_B: { int32 condition; condition = check_cmp(op & Q_MASK); if (condition == Q_AL && !disable_opt) deadcode = (LabelNumber *)m; else if (condition != Q_NOT) conditional_branch_to(condition, (LabelNumber *)m, 0); illbits &= ~Q_MASK; } break; case J_BXX: { /* Used with case tables */ LabelNumber *l, *ll; LabelNumber *table; l = (LabelNumber *)m; /* expand RETLAB so that we always generate a branch of 2 bytes */ if (l == RETLAB) l = returnlab; m = casebranch_pending_m; r1r = casebranch_pending; casebranch_pending = -1; uses_IP = YES; /* * The first BXX in any branch table is to the default label */ if (r1r >= 0) { if (m >= USE_DCB_FOR_CASEBRANCH && m < USE_DCW_FOR_CASEBRANCH) { /* If this is a big switch statement then a conditional */ /* branch might not reach from here to the default */ /* label so do it by a conditional branch to an */ /* unconditional branch at the head of the cases */ ll = nextlabel(); AddLabelReference(codep, ll); conditional_branch_to(Q_HS, ll, 0); outop(F_LSLK, R_IP, r1r, use_bl ? 2 : 1); outop(F_ADDLH, 0, R_PC-8, R_IP); setlabel(ll); conditional_branch_to(Q_AL, l, 0); } else { table = nextlabel(); if (use_dcw) { ll = nextlabel(); AddLabelReference(codep, ll); conditional_branch_to(Q_HS, ll, 0); addfref_(table, codep | LABREF_WORD8); AddLabelReference(codep, table); outop(F_ADDRPC, R_IP, 0, 0); outop(F_ADD3R, R_IP, R_IP, r1r); outop(F_LDRHADDR, R_IP, R_IP, r1r); casebranch_codep = codep; outop(F_ADDLH, 0, R_PC-8, R_IP); setlabel(ll); conditional_branch_to(Q_AL, l, 0); } else { conditional_branch_to(Q_HS, l, 0); addfref_(table, codep | LABREF_WORD8); AddLabelReference(codep, table); outop(F_ADDRPC, R_IP, 0, 0); outop(F_LDRBADDR, R_IP, R_IP, r1r); outop(F_LSLK, R_IP, R_IP, 1); casebranch_codep = codep; outop(F_ADDLH, 0, R_PC-8, R_IP); } cnop(); setlabel(table); casebranch_litpool = codebase+codep; } } else { if (m >= USE_DCB_FOR_CASEBRANCH && m < USE_DCW_FOR_CASEBRANCH) conditional_branch_to(Q_AL, l, use_bl); else add_casebranch(l); } break; } case J_CASEBRANCH: { int32 b_size; /* * I will not want any danger of the branch table being disrupted by * an attempt to dump out a literal pool, so if needbe I dump out the * pool right now... */ if (m >= USE_DCB_FOR_CASEBRANCH && m < USE_DCW_FOR_CASEBRANCH) { use_bl = 0; b_size = 2+2; /* 2 for B, 2 for branchpool */ } else { use_dcw = (m >= USE_DCW_FOR_CASEBRANCH); b_size = 1+2; /* 1 for DCB, 2 for branchpool */ if (use_dcw) b_size = 2+2; /* 2 for DCW, 2 for branchpool */ } b_size = b_size * m + 2 * 6; if (codep+b_size >= mustlitby - branchpoolsize) dumplits(1); if (codep+b_size >= mustbranchlitby) dump_branch_lits(1, b_size); r2r = r1r; /* So I can use rrop() */ casebranch_pending_m = m; if (m >= 0 && m <= 0xff) { outop(F_CMP8, r2r, 0, (m-1)); } else { m -= 1; rkop(F_CMP); } casebranch_pending = r1r; /* Let BXX finish this bit of code off */ break; } case J_SHRK: if (m == 0) syserr("Shift right of 0"); outop(op & J_UNSIGNED ? F_LSRK : F_ASRK, r1r, r2r, m & 0x1f); illbits &= ~(J_SIGNED|J_UNSIGNED); peep &= ~P_CMPZ; break; case J_SHLK: outop(F_LSLK, r1r, r2r, m & 0x1f); illbits &= ~(J_SIGNED|J_UNSIGNED); peep &= ~P_CMPZ; break; case J_SHLR: rrop(F_LSL); illbits &= ~(J_SIGNED|J_UNSIGNED); peep &= ~P_CMPZ; break; case J_SHRR: rrop(op & J_UNSIGNED ? F_LSR : F_ASR); illbits &= ~(J_SIGNED|J_UNSIGNED); peep &= ~P_CMPZ; break; case J_RORR: rrop(F_ROR); illbits &= ~(J_SIGNED|J_UNSIGNED); peep &= ~P_CMPZ; break; case J_RORK: rkop(F_ROR); illbits &= ~(J_SIGNED|J_UNSIGNED); peep &= ~P_CMPZ; break; #ifdef THUMB_CPLUSPLUS case J_THIS_ADJUST: { int32 v[4]; int32 *ve, *p; if (m & 3) syserr("Pointer adjustment %d not a multiple of 4", m); ve = arm_add_integer(R_A1, R_A1, m, 0, NULL, v); for (p = &v[0]; p != ve; p++) outcodeword(ARM_AL | *p, LIT_OPCODE_32); break; } #endif #ifdef THUMB_INLINE_ASSEMBLER case J_SBCK: rkop(F_SBC); peep &= ~P_CMPZ; break; case J_ADCK: rkop(F_ADC); peep &= ~P_CMPZ; break; #endif case J_ADDK: if ((peep & P_CMPZ) && (nspareregs & (1L << r1))) { if (r2r < 8 && -m >= 0 && -m <= 0xff) outop(F_CMP8, r2r, 0, -m); else { add_integer(r1r, r2r, m); flush_pending(1 << r1r); } } else add_integer(r1r, r2r, m); if (r2r >= 8 && (peep & P_CMPZ)) { if (r1r >= 8) syserr("P_CMPZ set with Rd >= 8 and Rn >=8 in J_ADDK"); outop(F_CMP8, r1r, 0, 0); } peep &= ~P_CMPZ; break; #ifdef THUMB_INLINE_ASSEMBLER case J_CMNK: if (m == 0) { outop(F_MOV8, R_IP, 0, 0); outop(F_CMN, 0, r2r, R_IP); illbits &= ~Q_MASK; peep &= ~P_CMPZ; break; } else m = -m; /* and fallthrough CMPK case */ #endif case J_CMPK: if (m >= 0 && m <= 0xff) outop(F_CMP8, r2r, 0, m); else { int r; if (r2r == R_IP) syserr("J_CMPK:IP clash @ %.8lx", codebase+codep); if ((r = constant_available(m)) >= 0) { outop(F_CMP, 0, r2r, r); } else if ((r = constant_available(-m)) >= 0) { outop(F_CMN, 0, r2r, r); } else { len = load_integer0(R_IP, m, 1); if (load_integer0(R_IP, -m, 1) < len) { load_integer(R_IP, -m); outop(F_CMN, 0, r2r, R_IP); } else { load_integer(R_IP, m); outop(F_CMP, 0, r2r, R_IP); } } } illbits &= ~Q_MASK; peep &= ~P_CMPZ; break; case J_LABEL: ldm_flush(); flush_pending(0xff | (1 << R_SP)); reg_flush(); nspareregs = 0; setlabel((LabelNumber *)m); break; case J_MULK: multiply_integer(r1r, r2r, m); peep &= ~P_CMPZ; break; case J_ANDK: and_integer(r1r, r2r, m, peep); peep &= ~P_CMPZ; break; case J_ORRK: rkop(F_OR); peep &= ~P_CMPZ; break; case J_EORK: rkop(F_EOR); peep &= ~P_CMPZ; break; #ifdef THUMB_INLINE_ASSEMBLER case J_TSTK: load_integer(R_IP, m); outop(F_TST, 0, r2r, R_IP); break; case J_TSTR: outop(F_TST, 0, r2r, mr); break; case J_ADCR: rrop(F_ADC); break; case J_SBCR: rrop(F_SBC); break; #endif case J_ADDR: if (r1r < 8 && r2r < 8 && mr < 8) { outop(F_ADD3R, r1r, r2r, mr); } else { if (r1r == mr) mr = r2r; else if (r1r != r2r) move_register(r1r, r2r); if (r1r >= 8) { if (mr >= 8) outop(F_ADDHH, 0, r1r-8, mr-8); else outop(F_ADDLH, 0, r1r-8, mr); } else { if (mr >= 8) outop(F_ADDHL, 0, r1r, mr-8); else outop(F_ADD3R, r1r, r1r, mr); } } peep &= ~P_CMPZ; break; case J_SUBR: if (r2r == R_SP) { outop(F_MOVHL, 0, R_IP, R_SP-8); r2r = R_IP; if (mr == R_IP) syserr("J_SUBR: IP clash @ %.8lx", codebase+codep); } else if (mr == R_SP) { outop(F_MOVHL, 0, R_IP, R_SP-8); mr = R_IP; } outop(F_SUB3R, r1r, r2r, mr); peep &= ~P_CMPZ; break; case J_ANDR: rrop(F_AND); peep &= ~P_CMPZ; break; case J_ORRR: rrop(F_OR); peep &= ~P_CMPZ; break; case J_EORR: rrop(F_EOR); peep &= ~P_CMPZ; break; case J_MULR: rrop(F_MUL); peep &= ~P_CMPZ; break; case J_BICR: rrop(F_BIC); peep &= ~P_CMPZ; break; /* load/store */ case J_LDRBK: if (r2r == R_SP) { /* r1r clashes with IP if signed - checked later */ if (m >= 0 && m <= (1020 + 31)) { n = (m > 1020) ? 1020 : (m & ~3); outop(F_ADDRSP, r1r, 0, n/4); } else { if (op & J_SIGNED) { n = 0; if (m >= 0) { n = m & (0xff << 2); if (m & 3) n = (m > 1020) ? 1020 : (m & ~3); } outop(F_ADDRSP, r1r, 0, n/4); } else { n = m & ~0x1f; load_integer(r1r, n); outop(F_ADDHL, 0, r1r, R_SP-8); } } m -= n; r2r = r1r; } if (op & J_SIGNED) { if (r2r == R_IP) syserr("J_LDRBK: IP clash @ %.8lx", codebase+codep); uses_IP = YES; load_integer(R_IP, m); outop(F_LDSBADDR, r2r, r1r, R_IP); } else { if ((n = bigindexbyte(r2r, m)) >= 0) { if (r2r == R_IP) syserr("J_LDRBK: IP clash @ %.8lx", codebase+codep); r2r = R_IP, m = n; } outop(F_LDRBI5, r2r, r1r, m); } illbits &= ~(J_SIGNED|J_UNSIGNED); break; case J_LDRBR: if (r2r == R_SP) { uses_IP = YES; if (mr == R_IP) syserr("J_LDRBR: IP clash @ %.8lx", codebase+codep); outop(F_MOVHL, 0, R_IP, R_SP-8); r2r = R_IP; } outop((op & J_SIGNED) ? F_LDSBADDR : F_LDRBADDR, r2r, r1r, mr); illbits &= ~(J_SIGNED|J_UNSIGNED); break; case J_LDRWK+J_ALIGN1: if (!BaseIsWordAligned(op, r2r, peep) || (m & 1) != 0) { int32 inc; int32 n; RealRegister r_ip = R_IP; if (r2r == R_SP) { if (m >= 0 && (m+3) <= (1020+31)) { n = (m > 1020) ? 1020 : (m & ~0x0f); outop(F_ADDRSP, R_IP, 0, n/4); m = m-n; } else { /* ECN: 0x0f here instead of 0x1f in case m & 3 */ load_integer(R_IP, m & ~0x0f); outop(F_ADDHL, 0, R_IP, R_SP-8); m = m & 0x0f; } r2r = R_IP; } else if (bigindexbyte(r2r, m+1) >= 0) { syserr("Unaligned LDRWK index too big (%ld) @ %.8lx", m, codebase+codep); m = 0; } if (r1r == R_IP) syserr("Unaligned LDRWK: IP clash @ %.8lx", codebase+codep); /* r2r may be IP */ inc = 1; if (!target_lsbytefirst) inc = -1, m += 1; if (r1r == r2r) { outop(F_LDRBI5, r2r, r_ip, m+inc); outop(F_LDRBI5, r2r, r1r, m); } else { outop(F_LDRBI5, r2r, r1r, m); outop(F_LDRBI5, r2r, r_ip, m+inc); } outop(F_LSLK, r_ip, r_ip, 8); outop(F_OR, 0, r1r, r_ip); if (op & J_SIGNED) { outop(F_LSLK, r1r, r1r, 16); outop(F_ASRK, r1r, r1r, 16); } illbits &= ~(J_SIGNED|J_UNSIGNED); break; } case J_LDRWK+J_ALIGN2: if (r2r == R_SP) { if (!(m & 1) && m >= 0 && m <= (1020 + 62)) { n = (m > 1020) ? 1020 : (m & ~3); outop(F_ADDRSP, r1r, 0, n/4); } else { if (op & J_SIGNED) { n = 0; if (m >= 0) { n = m & (0xff << 2); if (m & 3) n = (m > 1020) ? 1020 : (m & ~3); } outop(F_ADDRSP, r1r, 0, n/4); } else { n = m & ~(0x1f << 1); load_integer(r1r, n); outop(F_ADDHL, 0, r1r, R_SP-8); } } m -= n; r2r = r1r; } if (op & J_SIGNED) { if (r2r == R_IP) syserr("J_LDRWK: IP clash @ %.8lx", codebase+codep); uses_IP = YES; load_integer(R_IP, m); outop(F_LDSHADDR, r2r, r1r, R_IP); } else { if ((n = bigindexshort(r2r, m)) >= 0) { if (r2r == R_IP) syserr("J_LDRWK: IP clash @ %.8lx", codebase+codep); r2r = R_IP, m = n; } outop(F_LDRHI5, r2r, r1r, m >> 1); } illbits &= ~(J_SIGNED|J_UNSIGNED); break; case J_LDRWR+J_ALIGN2: if (r2r == R_SP) { uses_IP = YES; if (mr == R_IP) syserr("J_LDRWR: IP clash @ %.8lx", codebase+codep); outop(F_MOVHL, 0, R_IP, R_SP-8); r2r = R_IP; } outop((op & J_SIGNED) ? F_LDSHADDR : F_LDRHADDR, r2r, r1r, mr); illbits &= ~(J_SIGNED|J_UNSIGNED); break; case J_LDRK+J_ALIGN1: case J_STRK+J_ALIGN1: if (!BaseIsWordAligned(op, r2r, peep) || (m & 3) != 0) { int32 inc; int32 n; RealRegister r_ip = R_IP; if (r2r == R_SP) { if (m >= 0 && (m+3) <= (1020+31)) { n = (m > 1020) ? 1020 : (m & ~0x0f); outop(F_ADDRSP, R_IP, 0, n/4); m = m-n; } else { /* ECN: 0x0f here instead of 0x1f in case m & 3 */ load_integer(R_IP, m & ~0x0f); outop(F_ADDHL, 0, R_IP, R_SP-8); m = m & 0x0f; } r2r = R_IP; if (op1 == J_STRK) r_ip = R_A1+2; } else if (bigindexbyte(r2r, m+3) >= 0) { syserr("Unaligned LDRK/STRK index too big (%ld) @ %.8lx", m, codebase+codep); m = 0; } if (r1r == R_IP) syserr("Unaligned LDRK/STRK: IP clash @ %.8lx", codebase+codep); inc = 1; if (!target_lsbytefirst) inc = -1; if (op1 == J_STRK) { /* r1r and r2r clash with IP */ uint32 value = 0x01020304; /* unknown value - all bytes different */ uint32 lastval; uint32 storebits = 0x01010101; int32 shift; RealRegister valreg = r1r; if (inc < 0) m += 3; if (value_is_constant(r1r)) value = reg_values[r1r].value; lastval = value & 255; /* skip the first LSR */ while (storebits != 0) { for (shift = 0; shift < 32; shift += 8) if (storebits & (1 << shift) && lastval == ((value >> shift) & 255)) break; if (shift == 32) /* didn't find the same value */ { for (shift = 0; !(storebits & (1 << shift)); shift += 8) continue; lastval = (value >> shift) & 255; outop(F_LSRK, r_ip, r1r, shift); valreg = r_ip; } outop(F_STRBI5, r2r, valreg, m + inc * (shift >> 3)); storebits ^= 1 << shift; } } else { RealRegister lo, hi; lo = r_ip, hi = r1r; if (r2r == r_ip) lo = r1r, hi = r_ip; if (BaseIsWordAligned(op, r2r, peep)) { /* A3 not used. r2r may be IP, but r1r clashes with IP */ n = m & 3; switch (n) { case 1: outop(F_LDRI5, r2r, lo, m >> 2); outop(F_LDRBI5, r2r, hi, m + 3); if (inc > 0) outop(F_LSRK, lo, lo, 8); break; case 2: outop(F_LDRHI5, r2r, lo, m >> 1); outop(F_LDRHI5, r2r, hi, (m>>1)+1); break; case 3: outop(F_LDRBI5, r2r, lo, m); outop(F_LDRI5, r2r, hi, (m>>2)+1); if (inc < 0) outop(F_LSRK, hi, hi, 8); break; } if (inc > 0) outop(F_LSLK, hi, hi, (4-n)*8); else outop(F_LSLK, lo, lo, n * 8); outop(F_OR, 0, r1r, r_ip); } else { /* r1r clashes with IP and A3, r2r clashes with A3 (may be IP) */ if (inc < 0) m += 3; if (r1r == r2r) { /* now r2r <> IP! */ outop(F_LDRBI5, r2r, R_A3, m); outop(F_LDRBI5, r2r, r_ip, m+inc); outop(F_LSLK, r_ip, r_ip, 8); outop(F_OR, 0, R_A3, r_ip); outop(F_LDRBI5, r2r, r_ip, m+inc*2); outop(F_LSLK, r_ip, r_ip, 16); outop(F_OR, 0, R_A3, r_ip); outop(F_LDRBI5, r2r, r1r, m+inc*3); outop(F_LSLK, r1r, r1r, 24); outop(F_OR, 0, r1r, R_A3); } else { outop(F_LDRBI5, r2r, r1r, m); outop(F_LDRBI5, r2r, R_A3, m+inc); outop(F_LSLK, R_A3, R_A3, 8); outop(F_OR, 0, r1r, R_A3); outop(F_LDRBI5, r2r, R_A3, m+inc*2); outop(F_LSLK, R_A3, R_A3, 16); outop(F_OR, 0, r1r, R_A3); outop(F_LDRBI5, r2r, R_A3, m+inc*3); outop(F_LSLK, R_A3, R_A3, 24); outop(F_OR, 0, r1r, R_A3); } } } uses_IP = YES; illbits &= ~(J_SIGNED|J_UNSIGNED); break; } case J_LDRK+J_ALIGN4: case J_STRK+J_ALIGN4: w = loads_r1(op) ? F_LDRI5 : F_STRI5; if (r2r == R_SP) { if (m < 0 || m > 1020 || (m & 3)) { if (r1r == R_IP && w == F_STRI5) syserr("J_STRK: IP clash @ %.8lx", codebase+codep); uses_IP = YES; if (!(m & 3) && m >= 0 && m <= (1020 + 124)) { outop(F_ADDRSP, R_IP, 0, 1020/4); outop(w, R_IP, r1r, (m - 1020) >> 2); } else { load_integer(R_IP, m & ~(0x1f << 2)); outop(F_ADDHL, 0, R_IP, R_SP-8); outop(w, R_IP, r1r, (m >> 2) & 0x1f); } } else { w = loads_r1(op) ? F_LDRSP : F_STRSP; outop(w, r1r, 0, m >> 2); } } else { if (m == 0 && !(w == F_LDRI5 && r1r == r2r)) { pending_op = w; pending_r2 = r2r; pending_r1 = r1r; saved_spareregs = spareregs; spareregs = nspareregs; return; } else { if ((n = bigindex(r2r, m)) >= 0) { if (r2r == R_IP) syserr("J_LDRK/J_STRK: IP clash @ %.8lx", codebase+codep); if (r1r == R_IP && w == F_STRI5) syserr("J_STRK: IP clash @ %.8lx", codebase+codep); r2r = R_IP, m = n; } outop(w, r2r, r1r, m >> 2); } } illbits &= ~(J_SIGNED|J_UNSIGNED); break; case J_LDRR+J_ALIGN4: case J_STRR+J_ALIGN4: w = loads_r1(op) ? F_LDRADDR : F_STRADDR; if (r2r == R_SP) { uses_IP = YES; if (mr == R_IP || (w == F_STRADDR && r1r == R_IP)) syserr("J_LDRR/J_STRR: IP clash @ %.8lx", codebase+codep); outop(F_MOVHL, 0, R_IP, R_SP-8); r2r = R_IP; } outop(w, r2r, r1r, mr); illbits &= ~(J_SIGNED|J_UNSIGNED); break; case J_STRBK: if (r2r == R_SP) { uses_IP = YES; if (r1r == R_IP) syserr("J_STRBK: IP clash @ %.8lx", codebase+codep); if (m >= 0 && m <= (1020 + 31)) { n = (m > 1020) ? 1020 : (m & ~3); outop(F_ADDRSP, R_IP, 0, n/4); outop(F_STRBI5, R_IP, r1r, m - n); } else { load_integer(R_IP, m & ~0x1f); outop(F_ADDHL, 0, R_IP, R_SP-8); outop(F_STRBI5, R_IP, r1r, m & 0x1f); } } else { if ((n = bigindexbyte(r2r, m)) >= 0) { if (r2r == R_IP || r1r == R_IP) syserr("J_STRBK: IP clash @ %.8lx", codebase+codep); r2r = R_IP, m = n; } outop(F_STRBI5, r2r, r1r, m); } break; case J_STRBR: if (r2r == R_SP) { if (r1r == R_IP || mr == R_SP) syserr("J_STRBR: IP clash @ %.8lx", codebase+codep); uses_IP = YES; outop(F_MOVHL, 0, R_IP, R_SP-8); r2r = R_IP; } outop(F_STRBADDR, r2r, r1r, mr); break; case J_STRWK+J_ALIGN1: if (!BaseIsWordAligned(op, r2r, peep) || (m & 1) != 0) { int32 inc; int32 n; RealRegister r_ip = R_IP; bool bytesequal = NO; if (value_is_constant(r1r)) { int32 value = reg_values[r1r].value; int32 b0 = value & 0xff, b1 = (value >> 8) & 0xff; if (b0 == b1) bytesequal = YES; /* Expected to be useful really only for 0 / -1 */ } if (r2r == R_SP) { if (m >= 0 && (m+3) <= (1020+31)) { n = (m > 1020) ? 1020 : (m & ~0x0f); outop(F_ADDRSP, R_IP, 0, n/4); m = m-n; } else { /* ECN: 0x0f here instead of 0x1f in case m & 3 */ load_integer(R_IP, m & ~0x0f); outop(F_ADDHL, 0, R_IP, R_SP-8); m = m & 0x0f; } r2r = R_IP; r_ip = R_A1+2; } else if (bigindexbyte(r2r, m+1) >= 0) { syserr("Unaligned STRWK index too big (%ld) @ %.8lx", m, codebase+codep); m = 0; } if (r1r == r_ip || r2r == r_ip) syserr("Unaligned STRWK: IP clash @ %.8lx", codebase+codep); inc = 1; if (!target_lsbytefirst) inc = -1, m += 1; outop(F_STRBI5, r2r, r1r, m); if (bytesequal) r_ip = r1r; else outop(F_LSRK, r_ip, r1r, 8); outop(F_STRBI5, r2r, r_ip, m+inc); uses_IP = YES; break; } case J_STRWK+J_ALIGN2: if (r2r == R_SP) { uses_IP = YES; if (r1r == R_IP) syserr("J_STRWK: IP clash @ %.8lx", codebase+codep); if (!(m & 1) && m >= 0 && m <= (1020 + 62)) { n = (m > 1020) ? 1020 : (m & ~3); outop(F_ADDRSP, R_IP, 0, n/4); outop(F_STRHI5, R_IP, r1r, (m - n) >> 1); } else { load_integer(R_IP, m & ~(0x1f << 1)); outop(F_ADDHL, 0, R_IP, R_SP-8); outop(F_STRHI5, R_IP, r1r, (m >> 1) & 0x1f); } } else { if ((n = bigindexshort(r2r, m)) >= 0) { if (r2r == R_IP || r1r == R_IP) syserr("J_STRWK: IP clash @ %.8lx", codebase+codep); r2r = R_IP, m = n; } outop(F_STRHI5, r2r, r1r, m >> 1); } break; case J_STRWR+J_ALIGN2: if (r2r == R_SP) { uses_IP = YES; if (r1r == R_IP || mr == R_IP) syserr("J_STRWR: IP clash @ %.8lx", codebase+codep); outop(F_MOVHL, 0, R_IP, R_SP-8); r2r = R_IP; } outop(F_STRHADDR, r2r, r1r, mr); break; #ifdef THUMB_INLINE_ASSEMBLER case J_LDMW: if (r1r == R_SP) { if (m & 0x8000) m ^= 0x8100; outop(F_POP, 0, 0, m); } else outop(F_LDM, r1r, 0, m); break; case J_STMW: if (r1r == R_SP) { if (m & 0x4000) m ^= 0x4100; outop(F_PUSH, 0, 0, m); } else outop(F_STM, r1r, 0, m); break; case J_SWI: outop(F_SWI, 0, 0, r1); break; case J_BL: call_k(bindsym_((Binder *) r1)); break; case J_NULLOP: outop(F_MOVHH, 0, 0, 0); break; #endif case J_ENDPROC: { bool branches_left = fref_branches != 0; int32 old_codep = codep; int32 new_codep; if (branches_left || (!lab_isset_(returnlab) && return_pending)) conditional_branch_to(Q_AL, RETLAB, 0); new_codep = codep; codep = old_codep; while (fref_branches) setlabel(fref_branches->real_dest); codep = new_codep; available_branches = NULL; return_pending = 0; deadcode = 0; literal_pool_start = codebase+codep; dumplits2(0); #ifdef THUMB_CPLUSPLUS cnop(); #else if (codep & 1) outDCB(0); #endif fpdesc_endproc(); /* ECN: Many Thumb jopcodes will modify registers which cg does not know about * Therefore we must mark R0-R3 as being used. * HCM: this is a weak argument. Thumb/gen can augment regmask in a more exact * way. */ regmask |= 0x0f; } break; case J_ENTER: if (m < 0) syserr("emit(J_ENTER %ld)", m); returnlab = nextlabel(); entrylab = nextlabel(); routine_entry(m); break; case J_STACK: fpdesc_newsp(m); fp_minus_sp = m; break; case J_PUSHM: if (m != 0) outop(F_PUSH, 0, 0, m); break; case J_USE: case J_VSTORE: ldm_flush(); break; case J_CLRC+J_ALIGN4: case J_MOVC+J_ALIGN4: { int32 regs; bool useloop; bool ismove; int32 i, n; int32 count, rcount; LabelNumber *l; ismove = op1 == J_MOVC; regs = movc_workregs(p) | spareregs; if (ismove) regs &= ~regbit(r2); count = m; useloop = count > MOVC_LOOP_THRESHOLD; rcount = 4 * bitcount(regs); #if 0 printf("%s %d, %d, %d, @ %.8x\n", ismove ? "J_MOVC" : "J_CLRC", r1, r2, m, codebase+codep); #endif nspareregs |= regbit(r1); if (ismove) nspareregs |= regbit(r2); if (useloop) { if ((ismove && count <= 3*rcount) || (count <= 4*rcount)) useloop = NO; else rcount -= 4, regs &= ~regbit(R_IP); } { /* Remove unneeded registers if the register count either exeeds ldm_regs_max or rcount. */ int i, num_instr; if (count < 4 * ldm_regs_max) i = rcount - count; else i = rcount - 4 * ldm_regs_max; if (i > 0) { rcount -= i; for (; i > 0; i -= 4) regs ^= (regs & -regs); } regmask |= regs; /* Count the number of instructions required to be sure we dump the literal pool before it overflows. MOVC: 6 instructions for no loop max, loop max: 6 + load_integer. CLRC: 3 + rcount instructions for no loop, with loop max: 4 + load_integer + rcount. Assume 4 for load_integer max. But... we must also take any pending instructions into account, and any instructions in the ldm peepholer. Since there is a safety margin of 12 instructions, we don't care... */ num_instr = ismove ? 10 : rcount + 8; if (codep+2*num_instr >= mustlitby - branchpoolsize) dumplits(1); if (codep+2*num_instr >= mustbranchlitby) dump_branch_lits(1, num_instr*2); } if (!ismove) { for (i = 0; i <= 7; i++) if (regs & regbit(i)) load_integer(i, 0); } if (!useloop) { while (count > rcount) { if (ismove && count == rcount+4 && (deadbits & J_DEAD_R2) && !(peep & P_POST)) { rcount += 4; regs |= regbit(r2); } if (ismove) outop(F_LDM, r2, 0, regs); outop(F_STM, r1, 0, regs); count -= rcount; } } else { l = nextlabel(); n = count / rcount; count = count % rcount; load_integer(R_IP, n); ldm_flush(); flush_pending(0xff | (1 << R_SP)); reg_flush(); setlabel(l); if (ismove) outop(F_LDM, r2, 0, regs); outop(F_STM, r1, 0, regs); add_integer(R_IP, R_IP, -1); conditional_branch_to(Q_NE, l, 0); } if (count > 0) { for (i = rcount-count; i != 0; i -= 4) regs ^= (regs & -regs); if (ismove) outop(F_LDM, r2, 0, regs); outop(F_STM, r1, 0, regs); } if (reg_values[r1].typ == REGV_BASE) reg_values[r1].value += m; if (ismove && reg_values[r2].typ == REGV_BASE) reg_values[r2].value += m; } break; case J_TYPECASE: ldm_flush(); break; default: syserr("show_inst_direct(%#lx)", (long)op); outop(0, 0, 0, 0); /* placeholder */ } /* Check we've tidied up correctly */ if ((peep & ~P_BASEALIGNED) | illbits) syserr("show_inst_direct: peep = %lx illbits = %lx", (long)peep, (long)illbits); /* ECN: If P_CMPZ and the result is not used we must ensure the * opcode is actually emitted. */ if ((p->peep & P_CMPZ) && a_uses_r1(p) && (deadbits & J_DEAD_R1)) flush_pending(1 << r1); windup: spareregs = nspareregs; if (spareregs & pending_regs) pending_regs &= ~spareregs; } void show_instruction(const Icode *const ic) { J_OPCODE op = ic->op; VRegInt r1 = ic->r1; VRegInt r2 = ic->r2; VRegInt m = ic->r3; int32 dataflow = op & J_DEADBITS; static int32 cond = Q_AL; int32 newcond = 1; op &= ~J_DEADBITS; /* remove dataflow bits */ /* While code is still in flux, we assume all STRW's coming here have */ /* J_ALIGN4&J_ALIGNWR set... */ /* apparently, they don't have ALIGNWR... */ { int32 op1 = op & (J_TABLE_BITS | J_ALIGNMENT); if (op1 == J_STRWK+J_ALIGN4 || op1 == J_STRWR+J_ALIGN4) op = op - J_STRWK + J_STRK; } switch (op) { case J_SETSP: { int32 oldstack = r2.i, newstack = m.i; int32 diff = newstack - oldstack; if (fp_minus_sp != oldstack) syserr(syserr_setsp_confused, (long)fp_minus_sp, (long)oldstack, (long)newstack); fp_minus_sp = newstack; op = J_ADDK; r1.rr = R_SP; r2.rr = R_SP; m.i = -diff; dataflow = J_DEAD_R2; } break; case J_PUSHM: fp_minus_sp += (4 * bitcount(m.i)); break; case J_SUBK: if (m.i != 0) { op = J_ADDK; m.i = -m.i; } break; #ifdef THUMB_INLINE_ASSEMBLER case J_CMNK: if (m.i != 0) { op = J_CMPK; m.i = -m.i; } break; case J_BICK: op = J_ANDK; m.i = ~m.i; break; #endif case J_SHLK+J_SIGNED: case J_SHLK+J_UNSIGNED: m.i &= 255; if (m.i >= 32) { op = J_MOVK; dataflow &= ~J_DEAD_R2; m.i = 0; } break; case J_SHRK+J_UNSIGNED: m.i &= 255; if (m.i > 32) { /* LSR #32 allowed */ op = J_MOVK; dataflow &= ~J_DEAD_R2; m.i = 0; } else if (m.i == 0) { op = J_MOVR; m = r2; r2.rr = GAP; if (dataflow & J_DEAD_R2) dataflow ^= J_DEAD_R2+J_DEAD_R3; } break; case J_SHRK+J_SIGNED: m.i &= 255; if (m.i >= 32) m.i = 32; /* ASR #32 allowed */ else if (m.i == 0) { op = J_MOVR; m = r2; r2.rr = GAP; if (dataflow & J_DEAD_R2) dataflow ^= J_DEAD_R2+J_DEAD_R3; } break; } { bool flush = NO; switch (op & ~Q_MASK) { case J_ENTER: case J_ENDPROC: case J_LABEL: newcond = Q_AL; flush = YES; break; case J_STACK: case J_INFOLINE: case J_INFOBODY: case J_INFOSCOPE: case J_OPSYSK: case J_CALLK: case J_CALLR: case J_CASEBRANCH: case J_BXX: case J_B: case J_WORD: case J_USE: case J_VOLATILE: flush = YES; break; case J_PUSHD: case J_PUSHF: case J_ORG: case J_CONDEXEC: /* Things the ARM peepholer handles but we don't */ syserr("show_instruction(%#lx)", (long)op); break; } { PendingOp cur; if ((op & J_BASEALIGN4) && !j_is_adcon(op)) { cur.ic.op = op & ~J_BASEALIGN4; cur.peep = (op & J_ALIGNMENT) < J_ALIGN4 ? P_BASEALIGNED : 0; } else { cur.ic.op = op & ~J_BASEALIGN4; cur.peep = 0; } cur.ic.r1 = r1; cur.ic.r2 = r2; cur.ic.r3 = m; cur.ic.r4.rr = 0; cur.dataflow = dataflow; cur.cond = cond; peephole_op(&cur, flush); if (flush) ldm_flush(); if (newcond != 1) cond = newcond; } } } void branch_round_literals(LabelNumber *m) { conditional_branch_to(Q_AL, (LabelNumber *)m, 0); } void mcdep_init() { char cv_name[16]; int i; codebuf_reinit2(); /* this should be in driver.c? */ avoidallocating(R_LR); /* not directly accessible on this machine */ casebranch_pending = -1; mustlitby = 0x10000000; mustbranchlitby = 0x10000000; backwards_branches = 0; current_procnum = 0; adconpool_init(); peephole_init(); for (i = 0; i < 8; i++) { sprintf(cv_name, "__call_via_r%d", i); call_via[i] = sym_insert_id(cv_name); } fpdesc_init(); t_sym = sym_insert_id("$T"); label_values = NULL; label_references = NULL; } /* AM: the following two interface routines are temporarily needed. */ void localcg_reinit() { casebranch_pending = -1; deadcode = 0; mustlitby = 0x10000000; mustbranchlitby = 0x10000000; backwards_branches = 0; peephole_reinit(); fpdesc_init(); } void localcg_tidy() { dbg_finalise(); peephole_tidy(); } void localcg_newliteralpool(void) { if (in_code) { literal_pool_start = codebase+codep; in_code = 0; } mustlitby = 0x10000000; mustbranchlitby = 0x10000000; } void localcg_endcode(void) { describe_literal_pool(); } /* End of section thumb/gen.c */
stardot/ncc
tests/mathtest.c
<filename>tests/mathtest.c<gh_stars>0 /* Library routines for testing math functions with odd values */ /* Copyright (C) Advanced RISC Machines, 1997. All Rights Reserved */ /* SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <stdlib.h> #include <errno.h> #include <stdio.h> #include "mathtest.h" #define SIGN_BIT 0x80000000ul #define DINFNAN_INT_SE_HI 0x7FF00000ul #define DINFNAN_INT_LO 0x00000000ul #define DQNAN_BIT 0x00080000ul unsigned long dnan_low = 1, dnan_high = 0, fnan = 1; void dset_to_qnan(double_ints *x) { if ((dnan_low == 0ul && dnan_high == 0ul) || (dnan_high & (DINFNAN_INT_SE_HI+DQNAN_BIT)) != 0ul || (dnan_low & DINFNAN_INT_LO) != 0ul) { fprintf(stderr, "Test error - dset_to_qnan [%08lx/%08lx]\n", dnan_high, dnan_low); exit(1); } x->i.se_hi = DINFNAN_INT_SE_HI + DQNAN_BIT + dnan_high; x->i.lo = DINFNAN_INT_LO + dnan_low; return; } void dset_to_snan(double_ints *x) { if ((dnan_low == 0ul && dnan_high == 0ul) || (dnan_high & (DINFNAN_INT_SE_HI+DQNAN_BIT)) != 0ul || (dnan_low & DINFNAN_INT_LO) != 0ul) { fprintf(stderr, "Test error - dset_to_snan [%08lx/%08lx]\n", dnan_high, dnan_low); exit(1); } x->i.se_hi = DINFNAN_INT_SE_HI + dnan_high; x->i.lo = DINFNAN_INT_LO + dnan_low; return; } unsigned int disnan(double_ints *x) { return ( ((x->i.se_hi & DINFNAN_INT_SE_HI) == DINFNAN_INT_SE_HI) && ( (x->i.se_hi & ~(SIGN_BIT+DINFNAN_INT_SE_HI)) != 0 || x->i.lo != 0) ); } void dset_to_inf(double_ints *x) { x->i.se_hi = DINFNAN_INT_SE_HI; x->i.lo = DINFNAN_INT_LO; return; } unsigned int disinf(double_ints *x) { return ( ((x->i.se_hi & DINFNAN_INT_SE_HI) == DINFNAN_INT_SE_HI) && (x->i.se_hi & ~(SIGN_BIT+DINFNAN_INT_SE_HI)) == 0 && x->i.lo == 0 ); } void dset_to_one(double_ints *x) { x->f = 1.0; return; } void dset_to_mone(double_ints *x) { x->f = -1.0; } void dsucc(double_ints *a) { /* return a number at least 1 bigger than the argument */ double x = a->f; a->f += 1.0; if (a->f == x) { unsigned lo = a->i.lo; if (a->i.se_hi & SIGN_BIT) { a->i.lo--; if (lo < a->i.lo) a->i.se_hi--; } else { a->i.lo++; if (lo > a->i.lo) a->i.se_hi++; } } } void dpred(double_ints *a) { double x = a->f; a->f -= 1.0; if (a->f == x) { unsigned lo = a->i.lo; if (a->i.se_hi & SIGN_BIT) { a->i.lo++; if (lo > a->i.lo) a->i.se_hi++; } else { a->i.lo--; if (lo < a->i.lo) a->i.se_hi--; } } } void dneg(double_ints *a) { a->i.se_hi |= SIGN_BIT; } #define FINFNAN_INT_SEM 0x7f800000ul #define FQNAN_BIT 0x00400000ul void fset_to_qnan(float_int *x) { if (fnan == 0ul || (fnan & (FINFNAN_INT_SEM+FQNAN_BIT)) != 0ul) { fprintf(stderr, "Test error - fset_to_qnan [%08lx]\n", fnan); exit(1); } x->sem = FINFNAN_INT_SEM + FQNAN_BIT + fnan; return; } void fset_to_snan(float_int *x) { if (fnan == 0ul || (fnan & (FINFNAN_INT_SEM+FQNAN_BIT)) != 0ul) { fprintf(stderr, "Test error - fset_to_qnan [%08lx]\n", fnan); exit(1); } x->sem = FINFNAN_INT_SEM + fnan; return; } unsigned int fisnan(float_int *x) { return ( (x->sem & FINFNAN_INT_SEM) == FINFNAN_INT_SEM && (x->sem &~(SIGN_BIT+FINFNAN_INT_SEM)) != 0); } void fset_to_inf(float_int *x) { x->sem = FINFNAN_INT_SEM; return; } unsigned int fisinf(float_int *x) { return ( (x->sem & FINFNAN_INT_SEM) == FINFNAN_INT_SEM && (x->sem &~(SIGN_BIT+FINFNAN_INT_SEM)) == 0); } void fset_to_one(float_int *x) { x->f = 1.0; return; } void fset_to_mone(float_int *x) { x->f = -1.0; } void fsucc(float_int *a) { /* return a number bigger than the argument */ float x = a->f; a->f += 1.0; if (a->f == x) { if (a->sem & SIGN_BIT) a->sem--; else a->sem++; } } void fpred(float_int *a) { float x = a->f; a->f -= 1.0; if (a->f == x) { if (a->sem & SIGN_BIT) a->sem++; else a->sem--; } } void fneg(float_int *a) { a->sem |= SIGN_BIT; } /* return TRUE if there's been an IVO, and clear the flag */ unsigned int ivo(void) { unsigned long flags = __fp_status(__fpsr_IOC, 0); return (flags & __fpsr_IOC) != 0; } int get_errno(void) { int e = errno; errno = 0; return e; } #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif
stardot/ncc
arm/target.h
/* * C compiler file arm/target.h, version 13a * Copyright (C) Codemist Ltd., 1988. * Copyright (C) Acorn Computers Ltd., 1988 * Copyright (C) Advanced Risc Machines Ltd., 1991 * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _target_LOADED #define _target_LOADED 1 #include "toolenv.h" #define TARGET_IS_ARM 1 #ifndef TARGET_MACHINE /* Allow for definition of deviant ARMs, such as the APRM, in "options.h" */ # define TARGET_MACHINE "ARM" #endif #define TARGET_PREDEFINES { "__arm", \ "__CLK_TCK=100", \ "__JMP_BUF_SIZE=22" } #define EXTENSION_SYSV 1 #ifndef SOFTWARE_FLOATING_POINT # define TARGET_HAS_IEEE #endif #ifndef TARGET_IS_BIG_ENDIAN # ifndef TARGET_ENDIANNESS_CONFIGURABLE # define TARGET_IS_LITTLE_ENDIAN 1 # endif #endif #define TARGET_HAS_DATA_VTABLES 1 #define target_has_data_vtables (!pcrel_vtables) /* should this be in PCS? */ #ifndef NO_DEBUGGER # define TARGET_HAS_DEBUGGER 1 #endif #define TARGET_HAS_COND_EXEC 1 #define TARGET_HAS_SCALED_ADDRESSING 1 #define TARGET_HAS_NEGATIVE_INDEXING 1 #define target_shiftop_allowed(a,b,c,d) arm_shiftop_allowed(a, b, c, d) extern bool arm_shiftop_allowed(int32 n, int32 m, int32 signedness, int32 op); /* whether we can scale by n bits for an object of size m */ #define TARGET_HAS_SCALED_OPS 1 #define TARGET_HAS_SWITCH_BRANCHTABLE 1 #define TARGET_HAS_TAILCALL 1 #define TARGET_HAS_TAILCALLR 1 #define TARGET_HAS_FP_LITERALS 1 /* TARGET_HAS_FP_LITERALS invites fpliteral() which is a fn for the ARM */ #define TARGET_HAS_MULTIPLY 1 #define TARGET_HAS_ROTATE 1 #define TARGET_HAS_BLOCKMOVE 1 #define TARGET_ALLOWS_COMPARE_CSES 1 #define TARGET_FP_ARGS_IN_FP_REGS 1 #define TARGET_GEN_NEEDS_VOLATILE_INFO 1 #define TARGET_INLINES_MONADS 1 #define TARGET_HAS_PROFILE 1 /*#define TARGET_COUNT_IS_PROC 1*/ /* count is not a normal function (no frame required in its caller, */ /* destroys only r14 and ip). */ /* ECN: In this multi-target world things like TARGET_LACKS_HALFWORD_STORE & co. * really mean TARGET_MAY_LACK_HALFWORD_STORE. */ #define TARGET_LACKS_HALFWORD_STORE 1 #define TARGET_LACKS_RR_HALFWORD_STORE 1 #define target_has_halfword_support (config & CONFIG_HALFWORD_SPT) #define target_lacks_halfword_store \ ((config & (CONFIG_NO_HALFWORD_STORES|CONFIG_HALFWORD_SPT)) != CONFIG_HALFWORD_SPT) #define target_lacks_rr_halfword_store \ ((config & (CONFIG_NO_HALFWORD_STORES|CONFIG_HALFWORD_SPT)) != CONFIG_HALFWORD_SPT) #define TARGET_LACKS_RR_FP_ACCESSES 1 #define TARGET_LACKS_RR_UNALIGNED_ACCESSES 1 #define TARGET_LACKS_UNSIGNED_FIX 1 #define TARGET_ADDRESSES_UNSIGNED 1 #define TARGET_LDRK_MIN (-0xfffL) #define TARGET_LDRK_MAX 0xfffL #define TARGET_LDRWK_MIN ((target_has_halfword_support) ? -0xffL : -0xfffL) #define TARGET_LDRWK_MAX ((target_has_halfword_support) ? 0xffL : 0xfffL) #define TARGET_LDRFK_MIN (-0x3fcL) #define TARGET_LDRFK_MAX 0x3fcL #define TARGET_MAX_FRAMESIZE (4*12 + 12*4) /* help please on the 0-1 controversy */ #define R_A1 0L #define R_F0 16L #define R_V1 4L #define NARGREGS 4L #define NVARREGS 8L /* Includes R_SL & R_FP (only sometimes varregs) */ #define MAXGLOBINTREG 6L #define TARGET_HAS_BSS 1 #ifndef TARGET_HAS_AOUT # define CONST_DATA_IN_CODE 1 #endif #define NINTREGS 16L /* same as smallest fp reg, usually R_F0 */ #define NFLTARGREGS 4L #define NFLTVARREGS 4L #define R_FV1 (R_F0+NFLTARGREGS) #define MAXGLOBFLTREG 4L #define R_P1 R_A1 /* * ALLOCATION_ORDER is pretty suspect - it defines an order for looking at * registers and is intended to interact well with the copy-avoidance code. * When the copy-avoidance code is better this may not be needed any more. * The following lines are a temporary admission of defeat */ /* We choose to use SL = 10, FP = 11, IP = 12, SP = 13 here (= APCS_R) so that SL and FP (sometimes var regs) are contiguous with the var regs. */ #define ALLOCATION_ORDER {0,1,2,3, 12,14, 4,5,6,7,8,9,10,11, \ 16,17,18,19, 20,21,22,23, \ 255} #define R_IP 0xcL /* temp + used in call (nb not necessarily a real register number) */ #define R_SP 0xdL /* main stack pointer */ #define R_LR 0xeL /* link addr in fn calls or work reg */ #define R_PSR 0xfL #define TARGET_SPECIAL_ARG_REG R_IP /* emphasise non-obvious defaults in mip/defaults.h */ #ifndef alignof_double # define alignof_double 4 #endif #define MIN_ALIGNMENT_CONFIGURABLE #ifndef COMPILING_ON_ARM extern char const *target_lib_name(ToolEnv *t, char const *name); # define target_lib_name_(x,e) target_lib_name(x,e) #endif extern char *target_asm_options(ToolEnv *); #define target_asm_options_(x) target_asm_options(x) #ifndef TARGET_HAS_COFF # ifndef TARGET_HAS_AOUT # define TARGET_HAS_AOF 1 # endif #endif #ifdef TARGET_HAS_AOF # define TARGET_HAS_ADCON_AREA 1 # define TARGET_HAS_MULTIPLE_CODE_AREAS 1 # define TARGET_DEBUGGER_WANTS_MACROS 1 #endif #ifndef INTEGER_LOAD_MAX_DEFAULT # define INTEGER_LOAD_MAX_DEFAULT 2 #endif #ifndef LDM_REGCOUNT_MAX_DEFAULT # define LDM_REGCOUNT_MAX_DEFAULT 16 #endif #ifndef LDM_REGCOUNT_MIN_DEFAULT # define LDM_REGCOUNT_MIN_DEFAULT 3 #endif #ifndef STRUCT_PTR_ALIGN_DEFAULT # define STRUCT_PTR_ALIGN_DEFAULT 1 #endif #define SOFTWARE_FLOATING_POINT 1 #define SOFTWARE_FLOATING_POINT_RETURNS_DOUBLES_IN_REGISTERS 1 #define software_floating_point_enabled (config & CONFIG_SOFTWARE_FP) #define software_floats_enabled (config & CONFIG_SOFTWARE_FLOATS) #define software_doubles_enabled (config & CONFIG_SOFTWARE_DOUBLES) #define TARGET_SOFTFP_SUPPORT_INCLUDES_REVERSE_OPS 1 #define localcg_newliteralpool_exists 1 extern bool ImmediateOperand(int32 n, uint32 op); #define immed_cmp(n) ImmediateOperand(n, J_CMPK) #define immed_op(n, op) ImmediateOperand(n, op) #define TARGET_HAS_SAVE #ifdef TARGET_HAS_DEBUGGER # ifdef TARGET_HAS_AOF # ifndef HOST_DOESNT_WANT_FP_OFFSET_TABLES # define TARGET_HAS_FP_OFFSET_TABLES # endif # ifndef TARGET_HAS_DWARF # define TARGET_HAS_ASD # endif # endif # ifdef TARGET_HAS_ASD # ifdef TARGET_HAS_DWARF # define TARGET_HAS_MULTIPLE_DEBUG_FORMATS # endif # endif # define DEBUGGER_NEEDS_NO_FRAMEPOINTER # define NEW_DBG_PROC_INTERFACE #endif #define TARGET_SUPPORTS_TOOLENVS #define TOOLNAME armcc /* So there's just one entrypoint name, viz armccinit */ #ifdef CPLUSPLUS # define TOOLFILENAME "armcpp" #else # define TOOLFILENAME "armcc" #endif #endif /* end of arm/target.h */
stardot/ncc
mip/regsets.c
/* * regsets.c - space-efficient set representations, version 1a. * Copyright (C) Acorn Computers Ltd., 1988. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ /* Memo: @@@ someone misunderstands either the use of unsigned32 or */ /* the binding power of cases in (unsigned)regno / RANGESIZE. */ /* [ACN has made RANGESIZE an unsigned value and has put extra parens */ /* near where it is used: Happy now, Alan?] */ /* AM thinks that regno should really be unsigned32 (or VRegnum?) */ #include <stddef.h> /* for size_t */ #ifdef __STDC__ # include <string.h> #else # include <strings.h> #endif #include "globals.h" #include "regsets.h" #include "store.h" /* Some generic list operations which should be elsewhere (e.g. with */ /* nconc. */ bool generic_member(IPtr a, List const *l) { for (; l != NULL; l = l->cdr) if (a == l->car) return YES; return NO; } List *generic_ndelete(IPtr a, List *l) { List *r = l, *s; if (l == NULL) return l; else if (l->car == a) return (List *)discard2(l); do { s = l; l = l->cdr; if (l == NULL) return r; } while (l->car != a); s->cdr = (List *)discard2(l); return r; } /* * Macros for bit-vector access. Not sure quite how portable these are, * but having BitmapChunk as unsigned char probably makes it quite safe. */ #define bitmapchunk(bitmap, bitno) ((bitmap)[(bitno) >> 3]) #define bitmapbit(bitno) (1 << ((bitno) & (BITSPERCHUNK-1))) /* * **************** Sets of registers ***************** * This implementation works best if the sets are locally dense, but * globally sparse, without being too awful in the two extremes. * (Implementation is by a segmented bitmap) * The segments are now stored ordered by element size (rather than most * recently referenced first), since that makes the set operations (union * intersection, difference, compare) much faster. */ /* Beware: the number RANGESIZE on the next line is not freely */ /* changeable. See the union for VRegset and calls to discard3(). */ /* Moreover magic number 0x80 below must correspond to BITSPERCHUNK. */ #define RANGESIZE ((unsigned32)32) #define BITSPERCHUNK 8 typedef unsigned char BitmapChunk; typedef struct VRegSet { struct VRegSet *next; UPtr rangeid; /* for 'newchunk' allocator, else unsigned32. */ union { UPtr bitword; BitmapChunk bits[RANGESIZE/BITSPERCHUNK]; } bits; } VRegSet; static VRegSet *newchunk(VRegSetAllocRec *allocrec, VRegSet *next, int32 id, unsigned32 n) { AllocType type = allocrec->alloctype; (*allocrec->statsloc)++; return (VRegSet*) ( (type == AT_Syn) ? syn_list3(next, id, n) : (type == AT_Bind) ? binder_list3(next, id, n) : global_list3(SU_Other, next, id, n)); } extern VRegSet *vregset_insert(int32 regno, VRegSet *set, bool *oldp, VRegSetAllocRec *allocrec) { VRegSet *p, *prev; unsigned32 range = ((unsigned32)regno) / RANGESIZE; regno &= (RANGESIZE-1); for (prev = NULL, p = set; p != NULL; prev = p, p = p->next) { if (p->rangeid <= range) break; } if (p == NULL || p->rangeid < range) { VRegSet *q = newchunk(allocrec, p, range, 0); if (prev == NULL) set = q; else prev->next = q; p = q; } if (oldp) *oldp = (bitmapchunk(p->bits.bits, regno) & bitmapbit(regno)) != 0; bitmapchunk(p->bits.bits, regno) |= bitmapbit(regno); return set; } extern bool vregset_member(int32 regno, VRegSet *set) { VRegSet *p; unsigned32 range = ((unsigned32)regno) / RANGESIZE; regno &= (RANGESIZE-1); for (p = set; p != NULL; p = p->next) { if (p->rangeid <= range) { /* may have it */ if (p->rangeid < range) return NO; return (bitmapchunk(p->bits.bits, regno) & bitmapbit(regno)) != 0; } } return NO; } extern VRegSet *vregset_delete(int32 regno, VRegSet *set, bool *oldp) { VRegSet *p, *prev = NULL; unsigned32 range = ((unsigned32)regno) / RANGESIZE; regno &= (RANGESIZE-1); if (oldp) *oldp = NO; for (p = set; p != NULL; prev = p, p = p->next) if (p->rangeid <= range) { /* may have it */ if (p->rangeid < range) return set; if (oldp) *oldp = (bitmapchunk(p->bits.bits, regno) & bitmapbit(regno)) != 0; bitmapchunk(p->bits.bits, regno) &= ~bitmapbit(regno); if (p->bits.bitword == 0) { VRegSet *next = (VRegSet *) discard3((VoidStar) p); if (prev == NULL) set = next; else prev->next = next; return set; } } return set; } typedef union { RProc2 *p2; RProc1 *p1; } RProcx; typedef enum { Proc2, Proc1 } RProcType; static void vregset_map_i(VRegSet *set, RProcx dothis, RProcType type, VoidStar arg) { VRegSet *p; for (p = set; p != NULL; p = p->next) { unsigned32 base = p->rangeid * RANGESIZE; int32 j; for (j = RANGESIZE/BITSPERCHUNK-1 ; j >= 0 ; j--) { BitmapChunk chunk = p->bits.bits[j]; if (chunk != 0) { int32 reg = base + j*BITSPERCHUNK + BITSPERCHUNK-1; do { /* AM: funny order to map regs in... */ if (chunk & 0x80) { if (type == Proc2) dothis.p2(reg, arg); else dothis.p1(reg); } reg--; chunk = chunk<<1; } while (chunk!=0); } } } } extern void vregset_map(VRegSet *set, RProc2 *dothis, VoidStar arg) { RProcx p; p.p2 = dothis; vregset_map_i(set, p, Proc2, arg); } extern void vregset_map1(VRegSet *set, RProc1 *dothis) { RProcx p; p.p1 = dothis; vregset_map_i(set, p, Proc1, (VoidStar)NULL); } extern void vregset_discard(VRegSet *set) { while (set != NULL) set = (VRegSet *) discard3((VoidStar) set); } extern int vregset_compare(VRegSetP s1, VRegSetP s2) { int res = VR_EQUAL; while (s1 != NULL && s2 != NULL) { int32 r1 = s1->rangeid, r2 = s2->rangeid; if (r1 == r2) { int32 w1 = s1->bits.bitword, w2 = s2->bits.bitword; if (w1 == w2); else if ((w1 & w2) == w1) { if (res == VR_SUPERSET) return VR_UNORDERED; if (res == VR_EQUAL) res = VR_SUBSET; } else if ((w1 & w2) == w2) { if (res == VR_SUBSET) return VR_UNORDERED; if (res == VR_EQUAL) res = VR_SUPERSET; } else return VR_UNORDERED; s1 = s1->next; s2 = s2->next; } else if (r1 > r2) { if (res == VR_SUBSET) return VR_UNORDERED; if (res == VR_EQUAL) res = VR_SUPERSET; s1 = s1->next; } else { if (res == VR_SUPERSET) return VR_UNORDERED; if (res == VR_EQUAL) res = VR_SUBSET; s2 = s2->next; } } if (s1 != NULL) return (res == VR_SUBSET) ? VR_UNORDERED : VR_SUPERSET; else if (s2 != NULL) return (res == VR_SUPERSET) ? VR_UNORDERED : VR_SUBSET; return res; } extern VRegSetP vregset_difference(VRegSetP s1, VRegSetP s2) { VRegSet *p1 = s1, *p2 = s2, *prev1 = NULL; while (p1 != NULL && p2 != NULL) { if (p1->rangeid < p2->rangeid) p2 = p2->next; else if (p1->rangeid == p2->rangeid) { VRegSet *next1 = p1->next; p1->bits.bitword &= ~p2->bits.bitword; if (p1->bits.bitword == 0) { if (prev1 == NULL) s1 = next1; else prev1->next = next1; discard3((VoidStar) p1); } else prev1 = p1; p1 = next1; } else { prev1 = p1; p1 = p1->next; } } return s1; } extern VRegSetP vregset_union(VRegSetP s1, VRegSetP s2, VRegSetAllocRec *allocrec) { VRegSet *p1 = s1, *p2 = s2, *prev1 = NULL; while (p1 != NULL && p2 != NULL) { if (p1->rangeid == p2->rangeid) { p1->bits.bitword |= p2->bits.bitword; p2 = p2->next; } else if (p1->rangeid < p2->rangeid) { VRegSet *q = newchunk(allocrec, p1, p2->rangeid, p2->bits.bitword); if (prev1 == NULL) s1 = q; else prev1->next = q; p1 = q; p2 = p2->next; } prev1 = p1; p1 = p1->next; } while (p2 != NULL) { VRegSet *q = newchunk(allocrec, NULL, p2->rangeid, p2->bits.bitword); if (prev1 == NULL) s1 = q; else prev1->next = q; prev1 = q; p2 = p2->next; } return s1; } extern VRegSetP vregset_intersection(VRegSetP s1, VRegSetP s2) { VRegSet *p1 = s1, *p2 = s2, *prev1 = NULL; while (p1 != NULL && p2 != NULL) { if (p1->rangeid < p2->rangeid) p2 = p2->next; else { VRegSet *next1 = p1->next; if (p1->rangeid == p2->rangeid) { p1->bits.bitword &= p2->bits.bitword; if (p1->bits.bitword != 0) { prev1 = p1; p1 = next1; continue; } } if (prev1 == NULL) s1 = next1; else prev1->next = next1; discard3((VoidStar) p1); p1 = next1; } } if (p1 != NULL) { if (prev1 == NULL) s1 = NULL; else prev1->next = NULL; vregset_discard(p1); } return s1; } extern VRegSetP vregset_copy(VRegSetP set, VRegSetAllocRec *allocrec) { VRegSet *copy = NULL; for ( ; set != NULL ; set = set->next) { copy = newchunk(allocrec, copy, set->rangeid, set->bits.bitword); } return (VRegSetP) dreverse((List *) copy); } extern void vregset_init(void) { } /* * Start of (fairly) abstract type for reg clash matrix. RCC 19/02/88. * The matrix representation exploits the sparseness, symmetry, and * locality of the clash matrix. Essentially we split it up into * 16x16 bit squares, and store only those squares which are not entirely * zero. * * To exploit symmetry we do not store the transpose of each square, * but just link it off the other idx. We choose to access things * from the larger idx whenever possible (choose larger as local vars * tend to have low VReg numbers, and clash with lots of things: want * the resulting squares to be spread over many lists). * * The sparse matrix and the clash2 lists are allocated with SynAlloc, * as I believe they are now no bigger than the syntax tree (for a * big proc, 6000 lines and 12400 vregs, had about 1.1MB in front-end * and 560K here). * * Things rest of the file can use from here are: * add_clash(), vregset_member(), remove_clashes(), * clashkillbits(), printvregclash(), printvregclash2(). */ #define BLOCKBITS 3 /* 3 or 4 are probably the only sensible values */ #define BLOCKSIZE (1<<BLOCKBITS) #define BITSPERSQUARE (BLOCKSIZE*BLOCKSIZE) #define BITMAPSIZE ((BLOCKSIZE*BLOCKSIZE)/BITSPERCHUNK) #define blockno(reg) ((BlockNo)((reg) >> BLOCKBITS)) #define lowbits(reg) ((reg)&(BLOCKSIZE-1)) #define bitidx(a, b) (((a)<<BLOCKBITS) | (b)) typedef unsigned32 BlockNo; typedef struct Square { struct Square *next; /* list of squares owned by masteridx */ unsigned32 blockid; /* masteridx + otheridx<<16 */ struct Square *weaknext; /* list of squares involving otheridx */ BitmapChunk bitmap[BITMAPSIZE]; /* contents of this square */ } Square; #define masteridx(blockid) ((BlockNo)((blockid) & 0xffff)) #define otheridx(blockid) ((BlockNo)((blockid) >> 16)) typedef struct SquareLists { Square *list; /* list of squares owned by this idx */ Square *weaklist; /* list of other squares involving this idx */ } SquareLists; static VoidStar allocate(AllocType type, int32 size) { return (type == AT_Syn) ? SynAlloc(size) : (type == AT_Bind) ? BindAlloc(size) : GlobAlloc(SU_Other, size); } extern bool relation_member(int32 a, int32 b, Relation matrix) { SquareLists *master; Square *p, *prev; BlockNo other; if (a < b) { int32 t = a; a = b; b = t; } master = &(matrix[blockno(a)]); other = blockno(b); for (prev = NULL, p = master->list; p != NULL; prev = p, p = p->next) { if ((p->blockid >> 16) == other) { /* eureka! */ if (prev != NULL) { /* move to front */ prev->next = p->next; p->next = master->list; master->list = p; } { unsigned32 bitno = (unsigned32)bitidx(lowbits(a), lowbits(b)); return ((bitmapchunk(p->bitmap, bitno) & bitmapbit(bitno)) != 0); } } } return NO; } extern bool relation_add(int32 a, int32 b, Relation matrix, RelationAllocRec *allocrec) { SquareLists *master; Square *p, *prev; BlockNo other; if (a < b) { int32 t = a; a = b; b = t; } master = &(matrix[blockno(a)]); other = blockno(b); for (prev = NULL, p = master->list; p != NULL; prev = p, p = p->next) { if ((p->blockid >> 16) == other) { /* eureka! */ if (prev != NULL) { /* move to front */ prev->next = p->next; p->next = master->list; master->list = p; } break; } } if (p == NULL) { /* need a new square */ (*allocrec->statsloc)++; *allocrec->statsbytes += sizeof(Square); p = (Square *) allocate(allocrec->alloctype, sizeof(Square)); p->next = master->list; p->blockid = ((int32)blockno(a)) | (((int32)other) << 16); p->weaknext = matrix[other].weaklist; memclr(p->bitmap, sizeof(p->bitmap)); master->list = p; matrix[other].weaklist = p; } { unsigned32 bitno = (unsigned32)bitidx(lowbits(a), lowbits(b)); BitmapChunk chunk = bitmapchunk(p->bitmap, bitno); BitmapChunk bit = bitmapbit(bitno); if ((chunk & bit) == 0) { /* a new clash! */ bitmapchunk(p->bitmap, bitno) = (chunk | bit); return 1; } } return 0; } extern bool relation_delete(int32 a, int32 b, Relation matrix) { SquareLists *master; Square *p, *prev; BlockNo other; if (a < b) { int32 t = a; a = b; b = t; } master = &(matrix[blockno(a)]); other = blockno(b); for (prev = NULL, p = master->list; p != NULL; prev = p, p = p->next) { if ((p->blockid >> 16) == other) { /* eureka! */ if (prev != NULL) { /* move to front */ prev->next = p->next; p->next = master->list; master->list = p; } break; } } if (p == NULL) { unsigned32 bitno = (unsigned32)bitidx(lowbits(a), lowbits(b)); BitmapChunk chunk = bitmapchunk(p->bitmap, bitno); BitmapChunk bit = bitmapbit(bitno); if ((chunk & bit) != 0) { bitmapchunk(p->bitmap, bitno) = chunk & ~bit; return 1; } } return 0; } static void relation_map_i(int32 a, Relation matrix, RProcx dothis, RProcType type, VoidStar arg) { BlockNo block; Square *p; int32 j; for (p = matrix[blockno(a)].list; p != NULL; p = p->next) { block = otheridx(p->blockid) << BLOCKBITS; for (j = 0; j < BLOCKSIZE; ++j) { int32 bitno = bitidx(lowbits(a), j); BitmapChunk chunk = bitmapchunk(p->bitmap, bitno); if (chunk != 0) { if (chunk & bitmapbit(bitno)) { int32 n = block | j; if (type == Proc2) dothis.p2(n, arg); else dothis.p1(n); } } } } for (p = matrix[blockno(a)].weaklist; p != NULL; p = p->weaknext) { block = masteridx(p->blockid) << BLOCKBITS; for (j = 0; j < BLOCKSIZE; ++j) { int32 bitno = bitidx(j, lowbits(a)); BitmapChunk chunk = bitmapchunk(p->bitmap, bitno); if (chunk != 0) { if (chunk & bitmapbit(bitno)) { int32 n = block | j; if (type == Proc2) dothis.p2(n, arg); else dothis.p1(n); } } } } } extern void relation_map(int32 a, Relation matrix, RProc2 *dothis, VoidStar arg) { RProcx p; p.p2 = dothis; relation_map_i(a, matrix, p, Proc2, arg); } extern void relation_map1(int32 a, Relation matrix, RProc1 *dothis) { RProcx p; p.p1 = dothis; relation_map_i(a, matrix, p, Proc1, (VoidStar)NULL); } extern void relation_mapanddelete(int32 a, Relation matrix, RProc2 *dothis, VoidStar arg) { BlockNo block; Square *p; int32 j; for (p = matrix[blockno(a)].list; p != NULL; p = p->next) { block = otheridx(p->blockid) << BLOCKBITS; for (j = 0; j < BLOCKSIZE; ++j) { int32 bitno = bitidx(lowbits(a), j); BitmapChunk chunk = bitmapchunk(p->bitmap, bitno); if (chunk != 0) { if (chunk & bitmapbit(bitno)) { int32 n = block | j; bitmapchunk(p->bitmap, bitno) &= ~bitmapbit(bitno); dothis(n, arg); } } } } for (p = matrix[blockno(a)].weaklist; p != NULL; p = p->weaknext) { block = masteridx(p->blockid) << BLOCKBITS; for (j = 0; j < BLOCKSIZE; ++j) { int32 bitno = bitidx(j, lowbits(a)); BitmapChunk chunk = bitmapchunk(p->bitmap, bitno); if (chunk != 0) { if (chunk & bitmapbit(bitno)) { int32 n = block | j; bitmapchunk(p->bitmap, bitno) &= ~bitmapbit(bitno); dothis(n, arg); } } } } } extern Relation relation_init(RelationAllocRec *allocrec, int32 size, unsigned32 *statsloc) { SquareLists *p; int32 vecsize = ((size + BLOCKSIZE-1) / BLOCKSIZE) * sizeof(p[0]); p = (SquareLists *)allocate(allocrec->alloctype, vecsize); ClearToNull((void **)p, (size_t)vecsize/sizeof(void **)); *statsloc += vecsize; return p; } /* end of mip/regsets.c */
stardot/ncc
interp/interp.c
/* * interp/interp.c: main C interpreter routines * Copyright (C) Codemist Ltd., 1988-1993 * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Advanced RISC Machines Limited, 1992. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 188 * Checkin $Date$ * Revising $Author$ */ #include <setjmp.h> #include "globals.h" #include "lex.h" #include "syn.h" #include "sem.h" #include "bind.h" #include "builtin.h" #include "aetree.h" #include "codebuf.h" #include "aeops.h" #include "pp.h" #include "store.h" #include "simplify.h" #include "util.h" #ifdef USE_PP #include "pp.h" #endif #include "asdfmt.h" #include "dbg_hdr.h" #include "dbg_tbl.h" #ifndef USE_PP /* Dummy definitions for stuff in cfe/pp.c */ int32 pp_pragmavec['z'-'a'+1]; bool list_this_file; int pp_inhashif; #else FILE *asmstream, *objstream; #endif bool target_lsbitfirst; int32 config; char *expr_string; extern int curchar; extern Expr *rd_expr(); static Dbg_MCState *cc_dbg_state; static Dbg_Environment *cc_dbg_env; #define b_dbgaddr 0x80000000 #define STACKSIZE 1024 typedef char *SP; SP sp; char stack[STACKSIZE]; /* /* a tiny stack for the moment */ static int32 max_spoffset; static void inst_decls(Cmd *x, int32 spoffset); static void inst_exprdecls(Expr *e, int32 spoffset); static Expr *do_cmd(Cmd *x); static void eval_error(char *s, ...); static SP adjust_sp(int32 n) { return sp -= n; } static Dbg_Error readword(Dbg_MCState *state, ARMword *word, ARMaddress addr) { if (addr & b_dbgaddr) { *word = *(ARMword *)(addr & ~b_dbgaddr); return 0; } else { return dbg_ReadWord(state, word, addr); } } static Dbg_Error writeword(Dbg_MCState *state, ARMaddress addr, ARMword word) { if (addr & b_dbgaddr) { *(ARMword *)(addr & ~b_dbgaddr) = word; return 0; } else { return dbg_WriteWord(state, addr, word); } } static Dbg_Error readhalf(Dbg_MCState *state, ARMhword *hword, ARMaddress addr) { if (addr & b_dbgaddr) { *hword = *(ARMhword *)(addr & ~b_dbgaddr); return 0; } else { return Dbg_ReadHalf(state, hword, addr); } } static Dbg_Error writehalf(Dbg_MCState *state, ARMaddress addr, ARMhword hword) { if (addr & b_dbgaddr) { *(ARMhword *)(addr & ~b_dbgaddr) = hword; return 0; } else { return Dbg_WriteHalf(state, addr, hword); } } static Dbg_Error readbyte(Dbg_MCState *state, Dbg_Byte *byte, ARMaddress addr) { if (addr & b_dbgaddr) { *byte = *(Dbg_Byte *)(addr & ~b_dbgaddr); return 0; } else { return dbg_ReadByte(state, byte, addr); } } static Dbg_Error writebyte(Dbg_MCState *state, ARMaddress addr, Dbg_Byte byte) { if (addr & b_dbgaddr) { *(Dbg_Byte *)(addr & ~b_dbgaddr) = byte; return 0; } else { return dbg_WriteByte(state, addr, byte); } } static void define(Binder *b) { Dbg_LLSymType junk; unsigned32 val; void *llsym; llsym = dbg_LLSymVal(cc_dbg_state, cc_dbg_env->st, symname_(bindsym_(b)), &junk, &val); if (llsym) bindaddr_(b) = val; else eval_error("$b not defined\n", b); } static int32 mk_string(String *str) { char *s, *t; int len; StringSegList *strseg; /* /* At the moment this just reallocates the string every time it is used ! */ len = 0; for (strseg = str->strseg; strseg; strseg = strseg->strsegcdr) len += strseg->strseglen; s = t = SynAlloc(len + 1); for (strseg = str->strseg; strseg; strseg = strseg->strsegcdr) { memcpy(t, strseg->strsegbase, strseg->strseglen); t += strseg->strseglen; } s[len] = 0; return (int32)s + b_dbgaddr; } static jmp_buf eval_recover; static void eval_error(char *s, ...) { va_list a; va_start(a, s); sstart_string_char(s); ssuperrprintf(a); va_end(a); cc_msg("\n"); longjmp(eval_recover, 0); } extern Expr *eval_expr(Expr *e); static int32 read_with_mcrep(ARMaddress a, int32 m) { ARMword w; ARMhword h; Dbg_Byte b; int32 i; switch (m & MCR_SIZE_MASK) { case sizeof(ARMword): readword(cc_dbg_state, &w, a); i = w; break; case sizeof(ARMhword): readhalf(cc_dbg_state, &h, a); i = (int32)(unsigned32)h; if ((m & MCR_SORT_MASK) == MCR_SORT_SIGNED) i = (int32)(h << 16) / (1 << 16); break; case sizeof(Dbg_Byte): readbyte(cc_dbg_state, &b, a); i = (int32)(unsigned32)b; if ((m & MCR_SORT_MASK) == MCR_SORT_SIGNED) i = (int32)(h << 24) / (1 << 24); break; default: eval_error("read_with_mcrep 0x%8x", m); } return i; } static void write_with_mcrep(ARMaddress addr, int32 m, int32 i) { switch (m & MCR_SIZE_MASK) { case sizeof(ARMword): writeword(cc_dbg_state, addr, i); break; case sizeof(ARMhword): writehalf(cc_dbg_state, addr, i); break; case sizeof(Dbg_Byte): writebyte(cc_dbg_state, addr, i); break; default: eval_error("write_with_mcrep 0x%8x", m); } } static void assign_expr(int32 addr, Expr *e, TypeExpr *container) { int32 size; ARMaddress source; int32 i; Dbg_Error err; ARMword w; Expr *x; int32 mc, me; mc = mcrepoftype(container); me = mcrepofexpr(e); if ((me & MCR_SORT_MASK) == MCR_SORT_UNSIGNED || (me & MCR_SORT_MASK) == MCR_SORT_SIGNED) { if (h0_(e) != s_integer) eval_error("Cannot evaluate $e", e); i = intval_(e); write_with_mcrep(addr, mc, i); } else { switch (h0_(e)) { case s_binder: source = bindaddr_((Binder *)e); if (bindstg_((Binder *)e) & bitofstg_(s_auto)) { if (source & b_dbgaddr) source += (int32)sp; } break; case s_content: x = eval_expr(arg1_(e)); if (h0_(x) != s_integer) eval_error("Cannot evaluate $e", e); source = intval_(x); break; default: eval_error("Cannot evaluate $e", e); } size = me & MCR_SIZE_MASK; for (i = 0; i < size/4; i++) { err = readword(cc_dbg_state, &w, source); if (err) eval_error("Error reading 0x%08x", source); err = writeword(cc_dbg_state, addr, w); if (err) eval_error("Error writing 0x%08x", addr); addr += 4; source += 4; } } } Expr *eval_expr(Expr *e) { AEop op; Expr *e1; Expr *e2; Expr *x; int32 i1, i2; Binder *b; Dbg_Error err; ARMword w; int32 m; TypeExpr *t; if (!e) return 0; op = h0_(e); e1 = arg1_(e); e2 = arg2_(e); switch (op) { case s_let: case s_invisible: return eval_expr(e2); case s_comma: return eval_expr(e1), eval_expr(e2); case s_fnap: { ARMaddress addr; int argw; ExprList *el; static ARMword args[32]; int i = 0; char *structresult = 0; el = exprfnargs_(e); t = typeofexpr(e); m = mcrepoftype(t); x = eval_expr(e1); if (h0_(x) != s_integer) eval_error("Attempt to call non function $e", e1); addr = intval_(x); if (!(addr & b_dbgaddr)) { if ((m & MCR_SORT_MASK) == MCR_SORT_STRUCT) { structresult = SynAlloc(m & MCR_SIZE_MASK); args[i++] = (ARMword)structresult | b_dbgaddr; } } while (el) { x = eval_expr(exprcar_(el)); assign_expr((int32)&args[i] | b_dbgaddr, x, te_int); i += pad_to_word(sizeoftype(typeofexpr(x)))/4; el = cdr_(el); } argw = i; if (!(addr & b_dbgaddr)) { if (Dbg_CallNaturalSize(cc_dbg_state, addr, argw, args) != ps_callreturned) eval_error("Call to function $e did not return normally", e1); if (structresult) { b = mk_binder(gensymval(0), bitofstg_(s_static), t); bindaddr_(b) = (IPtr)structresult; return (Expr *)b; } else return mkintconst(t, cc_dbg_state->call.res.intres, 0); } else { TopDecl *t; int32 spoffset; SynBindList *bl; t = (TopDecl *)(addr & ~b_dbgaddr); max_spoffset = 0; inst_decls(t->v_f.fn.body, 0); spoffset = max_spoffset; i = 0; bl = t->v_f.fn.formals; while (bl) { bindaddr_(bl->bindlistcar) = spoffset + i * sizeof(ARMword) | b_dbgaddr; i += pad_to_word(sizeoftype(bindtype_(bl->bindlistcar)))/4; bl = bl->bindlistcdr; } sp = adjust_sp(spoffset + i * sizeof(ARMword)); memcpy(sp+spoffset, args, argw * sizeof(ARMword)); x = do_cmd(t->v_f.fn.body); adjust_sp(-(spoffset + i * sizeof(ARMword))); return x; } } case s_plusplus: case s_minusminus: x = eval_expr(e1); if (h0_(x) != s_integer) eval_error("Cannot evaluate $e", e1); i2 = intval_(x); e2 = mkintconst(typeofexpr(e1), s_plusplus ? i2++ : i2--, 0); case s_displace: case s_init: case s_assign: t = typeofexpr(e1); x = mk_expr1(s_addrof, ptrtotype_(t), e1); x = eval_expr(x); if (h0_(x) != s_integer) eval_error("Unable to take address of $e", e1); i1 = intval_(x); x = eval_expr(e2); assign_expr(i1, x, t); return x; case s_cond: x = eval_expr(e1); if (h0_(x) != s_integer) eval_error("Cannot evaluate $e", e1); return eval_expr(intval_(x) ? arg2_(e):arg3_(e)); case s_addrof: { switch (h0_(e1)) { case s_binder: b = (Binder *)e1; if (bindstg_(b) & b_undef) define(b); i1 = bindaddr_(b); if (bindstg_(b) & bitofstg_(s_auto)) { if (i1 & b_dbgaddr) i1 += (int32)sp; } return mkintconst(ptrtotype_(bindtype_(b)), i1, 0); case s_content: return eval_expr(arg1_(e1)); case s_dot: x = mk_expr1(s_addrof, ptrtotype_(typeofexpr(arg1_(e1))), arg1_(e1)); x = eval_expr(x); if (h0_(x) != s_integer) eval_error("Cannot evaluate $e", e1); return mkintconst(typeofexpr(e), intval_(x)+exprdotoff_(e1), 0); case s_string: return mkintconst(te_charptr, mk_string((String *)e1), 0); default: cc_msg("Unknown op(%d) in $e (s_addrof)\n", h0_(e1), e1); return 0; } break; } case s_content: m = mcrepofexpr(e); if ((m & MCR_SORT_MASK) == MCR_SORT_SIGNED || (m & MCR_SORT_MASK) == MCR_SORT_UNSIGNED) { x = eval_expr(e1); w = read_with_mcrep(intval_(x), m); return mkintconst(typeofexpr(e), w, 0); } return e; case s_dot: e1 = mk_expr1(s_addrof, te_int, e1); x = eval_expr(e1); if (h0_(x) != s_integer) eval_error("Cannot evaluate $e", e1); i1 = intval_(x); w = read_with_mcrep(i1+exprdotoff_(e), mcrepofexpr(e)); return mkintconst(typeofexpr(e), w, 0); case s_binder: b = (Binder *)e; if (bindstg_(b) & b_undef) define(b); m = mcrepofexpr((Expr *)b); if ((m & MCR_SORT_MASK) == MCR_SORT_SIGNED || (m & MCR_SORT_MASK) == MCR_SORT_UNSIGNED) { i1 = bindaddr_(b); if (bindstg_(b) & bitofstg_(s_auto)) { if (i1 & b_dbgaddr) i1 += (int32)sp; } w = read_with_mcrep(i1, mcrepoftype(bindtype_(b))); return mkintconst(bindtype_(b), w, 0); } return (Expr *)b; case s_cast: return eval_expr(e1); case s_string: return mkintconst(te_charptr, mk_string((String *)e), 0); case s_integer: case s_boolean: return e; case s_plus: case s_minus: case s_times: case s_div: case s_rem: case s_and: case s_or: case s_xor: case s_andand: case s_oror: case s_leftshift: case s_rightshift: case s_equalequal: case s_notequal: case s_less: case s_lessequal: case s_greater: case s_greaterequal: x = eval_expr(e2); if (h0_(x) != s_integer) eval_error("Cannot evaluate $e", e2); i2 = intval_(x); case s_monplus: case s_neg: case s_bitnot: case s_boolnot: x = eval_expr(e1); if (h0_(x) != s_integer) eval_error("Cannot evaluate $e", e1); i1 = intval_(x); switch (op) { case s_plus: i1 = i1+i2; break; case s_minus: i1 = i1-i2; break; case s_times: i1 = i1*i2; break; case s_div: i1 = i1/i2; break; case s_rem: i1 = i1%i2; break; case s_and: i1 = i1&i2; break; case s_or: i1 = i1|i2; break; case s_xor: i1 = i1^i2; break; case s_andand: i1 = i1&&i2; break; case s_oror: i1 = i1||i2; break; case s_leftshift: i1 = i1<<i2; break; case s_rightshift: i1 = i1>>i2; break; case s_equalequal: i1 = i1==i2; break; case s_notequal: i1 = i1!=i2; break; case s_less: i1 = i1<i2; break; case s_lessequal: i1 = i1<=i2; break; case s_greater: i1 = i1>i2; break; case s_greaterequal: i1 = i1>=i2; break; case s_monplus: i1 = i1; break; case s_neg: i1 = -i1; break; case s_bitnot: i1 = ~i1; break; case s_boolnot: i1 = !i1; break; } return mkintconst(typeofexpr(e), i1, 0); default: cc_msg("Unknown op(%d) in $e\n", op, e); } } static void spaces(int i) { while (i--) cc_msg(" "); } static void display_expr_i(int32 i, TypeExpr *t, char *format, int indent) { switch (h0_(t)) { case s_typespec: cc_msg("%d", i); break; case t_content: cc_msg("%p", i); break; default: eval_error("Cannot handle h0_(t) = %d in display_expr_i", h0_(t)); } } static void display_expr_a(int32 a, TypeExpr *t, char *format, int indent) { SET_BITMAP m; TagBinder *tb; ClassMember *members; StructPos sp; SET_BITMAP sort; int32 i, n; int32 size; ARMword w; switch (h0_(t)) { case t_content: readword(cc_dbg_state, &w, a); display_expr_i(w, t, format, indent); break; case s_typespec: m = typespecmap_(t); switch (sort = (m & -m)) { case bitoftype_(s_class): case bitoftype_(s_struct): case bitoftype_(s_union): tb = typespectagbind_(t); indent += 4; cc_msg("{"); for (members = tagbindmems_(tb); members; members = memcdr_(members)) { if (!structfield(members, sort, &sp)) continue; if (!memsv_(members)) continue; cc_msg("\n"); spaces(indent); cc_msg("%s = ", symname_(memsv_(members))); display_expr_a(a+sp.boffset, memtype_(members), format, indent); } cc_msg("\n"); indent -= 4; spaces(indent); cc_msg("}"); break; case bitoftype_(s_char): case bitoftype_(s_int): case bitoftype_(s_enum): i = read_with_mcrep(a, mcrepoftype(t)); display_expr_i(i, t, format, indent); break; } break; case t_subscript: n = intval_(typesubsize_(t)); indent += 4; t = typearg_(t); size = sizeoftype(t); cc_msg("{"); structpos_init(&sp, tb); for (i = 0; i < n; i++) { cc_msg("\n"); spaces(indent); display_expr_a(a, t, format, indent); a += size; } cc_msg("\n"); indent -= 4; spaces(indent); cc_msg("}"); break; default: eval_error("Cannot handle h0_(t) = %d in display_expr_a", h0_(t)); } } static void display_expr(Expr *e, TypeExpr *t, char *format, int indent) { Expr *x; if (h0_(e) == s_integer) { display_expr_i(intval_(e), t, format, indent); return; } x = mk_expr1(s_addrof, ptrtotype_(t), e); /* Side effect free ? */ x = eval_expr(x); if (h0_(x) != s_integer) eval_error("Cannot take address of $e", e); display_expr_a(intval_(x), t, format, indent); } void cc_rd_expr(Dbg_MCState *state, Dbg_Environment *env, char *s, char *format) { Expr *e, *x; int32 i; TypeExpr *t; int32 spoffset; Expr *edtor; cc_dbg_state = state; cc_dbg_env = env; expr_string = s; curchar = 0; #ifdef USE_PP pp_notesource("<expr>", 0); #endif nextsym(); if (setjmp(eval_recover) == 0) { push_exprtemp_scope(); e = rd_expr(10/*PASTCOMMA*/); if (e && h0_(e) != s_error) { e = optimise0(e); sp = stack + STACKSIZE; max_spoffset = 0; inst_exprdecls(e, 0); spoffset = max_spoffset; sp = adjust_sp(spoffset); x = eval_expr(e); pr_expr(e); if (x) { t = typeofexpr(x); cc_msg(" = ["); pr_typeexpr(t, 0); cc_msg("] "); display_expr(x, t, format, 0); } else cc_msg("void"); sp = adjust_sp(-spoffset); cc_msg("\n"); } } return; } static void inst_exprdecls(Expr *e, int32 spoffset) { Expr *e1, *e2; SynBindList *bl; ExprList *el; if (!e) return; e1 = arg1_(e); e2 = arg2_(e); switch (h0_(e)) { case s_let: bl = (SynBindList *)e1; while (bl) { bindaddr_(bl->bindlistcar) = spoffset | b_dbgaddr; spoffset += pad_to_word(sizeoftype(bindtype_(bl->bindlistcar))); bl = bl->bindlistcdr; } if (spoffset > max_spoffset) max_spoffset = spoffset; inst_exprdecls(e2, spoffset); break; case s_fnapstructvoid: case s_fnapstruct: case s_fnap: inst_exprdecls(e1, spoffset); el = exprfnargs_(e); while (el) { inst_exprdecls(exprcar_(el), spoffset); el = cdr_(el); } break; case s_dot: inst_exprdecls(e1, spoffset); if (h0_(typeofexpr(e)) == t_ovld || h0_(typeofexpr(e)) == t_fnap) inst_exprdecls(e2, spoffset); break; case s_invisible: inst_exprdecls(e2, spoffset); break; case s_cond: inst_exprdecls(arg3_(e), spoffset); inst_exprdecls(e2, spoffset); case s_cast: inst_exprdecls(e1, spoffset); case s_floatcon: case s_string: case s_integer: case s_boolean: case s_binder: case s_member: case s_identifier: case s_error: break; default: if (ismonad_(h0_(e)) || h0_(e) == s_return || h0_(e) == s_throw) inst_exprdecls(e1, spoffset); else if (isdiad_(h0_(e))) inst_exprdecls(e1, spoffset), inst_exprdecls(e2, spoffset); else eval_error("Unhandled op in inst_exprdecls %d", h0_(e)); break; } } static void inst_decls(Cmd *x, int32 spoffset) { SynBindList *bl; CmdList *cl; if (!x) return; switch (h0_(x)) { case s_return: case s_semicolon: inst_exprdecls(cmd1e_(x), spoffset); return; case s_block: bl = cmdblk_bl_(x); while (bl) { bindaddr_(bl->bindlistcar) = spoffset | b_dbgaddr; spoffset += pad_to_word(sizeoftype(bindtype_(bl->bindlistcar))); bl = bl->bindlistcdr; } if (spoffset > max_spoffset) max_spoffset = spoffset; cl = cmdblk_cl_(x); while (cl) { inst_decls(cmdcar_(cl), spoffset); cl = (CmdList *)cdr_((List *)cl); } return; case s_do: inst_decls(cmd1c_(x), spoffset); inst_exprdecls(cmd2e_(x), spoffset); return; case s_for: inst_exprdecls(cmd1e_(x), spoffset); inst_exprdecls(cmd2e_(x), spoffset); inst_exprdecls(cmd3e_(x), spoffset); inst_decls(cmd4c_(x), spoffset); return; case s_if: inst_exprdecls(cmd1e_(x), spoffset); inst_decls(cmd2c_(x), spoffset); inst_decls(cmd3c_(x), spoffset); return; } } #define DO_EXEC 0 #define DO_GOTO 1 #define DO_SWITCH 2 #define DO_DEFAULT 3 static int do_flags; static LabBind *goto_dest; static int32 switch_dest; static Expr *fn_res; static AEop do_cmd_1(Cmd *x) { Expr *e; CmdList *cl; AEop op; if (!x) return 0; switch (h0_(x)) { case s_semicolon: if (do_flags != DO_EXEC) return 0; eval_expr(cmd1e_(x)); return 0; case s_block: cl = cmdblk_cl_(x); while (cl) { op = do_cmd_1(cmdcar_(cl)); if (op) return op; cl = (CmdList *)cdr_((List *)cl); } return 0; case s_colon: if (do_flags == DO_GOTO && goto_dest == cmd1lab_(x)) do_flags = DO_EXEC; return do_cmd_1(cmd2c_(x)); case s_case: if (do_flags == DO_SWITCH && switch_dest == intval_(cmd1e_(x))) do_flags = DO_EXEC; return do_cmd_1(cmd2c_(x)); case s_default: if (do_flags == DO_DEFAULT) do_flags = DO_EXEC; return do_cmd_1(cmd1c_(x)); case s_switch: if (do_flags == DO_GOTO) return do_cmd_1(cmd2c_(x)); if (do_flags != DO_EXEC) return 0; do_flags = DO_SWITCH; switch_dest = intval_(eval_expr(cmd1e_(x))); op = do_cmd_1(cmd2c_(x)); if (do_flags == DO_SWITCH) { do_flags = DO_DEFAULT; op = do_cmd_1(cmd2c_(x)); do_flags = 0; } if (op == s_break) op = 0; return op; case s_goto: if (do_flags != DO_EXEC) return 0; do_flags = DO_GOTO; goto_dest = cmd1lab_(x); return s_goto; case s_return: { int32 m; TypeExpr *t; Binder *b; char *structresult; if (do_flags != DO_EXEC) return 0; e = eval_expr(cmd1e_(x)); if (e) { t = typeofexpr(e); m = mcrepoftype(t); if ((m & MCR_SORT_MASK) == MCR_SORT_STRUCT) { structresult = SynAlloc(m & MCR_SIZE_MASK); b = mk_binder(gensymval(0), bitofstg_(s_static), t); bindaddr_(b) = (IPtr)structresult | b_dbgaddr; assign_expr(bindaddr_(b), e, t); e = (Expr *)b; } } fn_res = e; return s_return; } case s_break: if (do_flags != DO_EXEC) return 0; return s_break; case s_continue: if (do_flags != DO_EXEC) return 0; return s_continue; case s_do: do { op = do_cmd_1(cmd1c_(x)); if (op == s_continue) continue; if (op == s_break) break; if (op) return op; if (do_flags != DO_EXEC) return 0; } while (intval_(eval_expr(cmd2e_(x)))); return 0; case s_for: if (do_flags != DO_EXEC) goto go_into; for (eval_expr(cmd1e_(x)); intval_(eval_expr(cmd2e_(x))); eval_expr(cmd3e_(x))) { go_into: op = do_cmd_1(cmd4c_(x)); if (op == s_continue) continue; if (op == s_break) break; if (op) return op; if (do_flags != DO_EXEC) return 0; } return 0; case s_if: if (do_flags != DO_EXEC) { op = do_cmd_1(cmd2c_(x)); if (do_flags != DO_EXEC) op = do_cmd_1(cmd3c_(x)); return op; } else { if (intval_(eval_expr(cmd1e_(x)))) return do_cmd_1(cmd2c_(x)); else return do_cmd_1(cmd3c_(x)); } } } static Expr *do_cmd(Cmd *x) { int32 res; AEop op; goto_dest = 0; fn_res = 0; do { op = do_cmd_1(x); } while (op == s_goto); return fn_res; } Expr *genstaticparts(DeclRhsList *const d, bool topflag, bool dummy_call, Expr *dyninit) { char *p; const SET_BITMAP stg = d->declstg; if ((stg & bitofstg_(s_typedef)) || (stg & b_fnconst)) return 0; #if 0 if (!(stg & bitofstg_(s_static)) && !(stg & bitofstg_(s_extern))) return 0; #endif if (stg & b_undef) return 0; if (topflag) { p = (char *)SynAlloc(sizeoftype(d->decltype)); bindaddr_(d->declbind) = (int32)p | b_dbgaddr; } if (!dummy_call) { /* This putrid code comes from vargen */ if (dyninit == 0 && syn_canrdinit()) { dyninit = syn_rdinit(d->decltype, 0, 0); if (dyninit && h0_(dyninit) != s_error) dyninit = mkbinary(s_assign, d->declbind, dyninit); } } if (topflag) { if (dyninit && h0_(dyninit) != s_error) eval_expr(dyninit); else memset(p, 0, sizeoftype(d->decltype)); } return dyninit; } Dbg_Error cc_rd_topdecl(Dbg_MCState *state, Dbg_Environment *env, char *s) { TopDecl *t; FILE *f; cc_dbg_state = state; cc_dbg_env = env; expr_string = 0; curchar = 0; #ifdef USE_PP while (isspace(*s)) s++; if (*s) { f = fopen(s, "r"); if (!f) { cc_msg("Error opening '%s'\n", s); return 0; } } else { f = stdin; s = "<stdin>"; } pp_notesource(s, f); #endif nextsym(); while (1) { t = rd_topdecl(); pr_topdecl(t); sp = stack + STACKSIZE; if (h0_(t) == s_eof) break; else if (h0_(t) == s_fndef) { cc_msg("Defined function $b\n", t->v_f.fn.name); bindaddr_(t->v_f.fn.name) = (IPtr)t | b_dbgaddr; t->v_f.fn.structresult = currentfunction.structresult; } } #ifdef USE_PP if (f != stdin) fclose(f); #endif return 0; } static int gensymno; typedef struct Faked_TypeExpr { struct Faked_TypeExpr *next; ItemSection *section; asd_Type type; TypeExpr *t; } Faked_TypeExpr; Faked_TypeExpr *faked_typeexprs; static TypeExpr *fake_typeexpr_1(ItemSection *section, asd_Type type); static void add_faked_typeexpr(ItemSection *section, asd_Type type, TypeExpr *t) { Faked_TypeExpr *ft; ft = SynAlloc(sizeof(Faked_TypeExpr)); ft->section = section; ft->type = type; ft->t = t; ft->next = faked_typeexprs; faked_typeexprs = ft; } TypeExpr *fake_typeexpr(ItemSection *section, asd_Type type) { Faked_TypeExpr *ft; TypeExpr *t; for (ft = faked_typeexprs; ft; ft=ft->next) { if (ft->section == section && ft->type == type) return ft->t; } t = fake_typeexpr_1(section, type); add_faked_typeexpr(section, type, t); return t; } static TypeExpr *fake_typeexpr_1(ItemSection *section, asd_Type type) { TypeExpr *t; int32 tcode; Item *item; tcode = TYPE_TYPECODE(type); if (TYPE_PTRCOUNT(type)) { type = TYPE_TYPEWORD(tcode, TYPE_PTRCOUNT(type)-1); return ptrtotype_(fake_typeexpr(section, type)); } if (tcode >= 0) { switch (tcode) { case TYPEVOID: return te_void; case TYPESBYTE: return mk_typeexpr1(s_typespec, (TypeExpr *)(bitoftype_(s_char)|bitoftype_(s_signed)), 0); case TYPESHALF: return mk_typeexpr1(s_typespec, (TypeExpr *)(bitoftype_(s_int)|bitoftype_(s_short)), 0); case TYPESWORD: return te_int; case TYPEUBYTE: return mk_typeexpr1(s_typespec, (TypeExpr *)(bitoftype_(s_char)|bitoftype_(s_unsigned)), 0); case TYPEUHALF: return mk_typeexpr1(s_typespec, (TypeExpr *)(bitoftype_(s_int)|bitoftype_(s_short)|bitoftype_(s_unsigned)), 0); case TYPEUWORD: return te_uint; case TYPEFLOAT: return te_float; case TYPEDOUBLE: return te_double; case TYPESTRING: return ptrtotype_(te_char); case TYPEFUNCTION: { TypeExprFnAux s; return mkTypeExprfn(t_fnap, te_int, 0, 0, packTypeExprFnAux(s, 0, 1999, 0, 0, 0)); } default: cc_msg("Unrecognised type code %d\n", tcode); return te_int; } } else { item = (Item *)((char *)section - tcode); switch (asd_code_(item->c)) { case ITEMARRAY: { ItemArray *item_a = &item->a; return mk_typeexpr1(t_subscript, fake_typeexpr(section, item_a->basetype), mkintconst(te_int, item_a->upperbound.i+1, 0)); } case ITEMTYPE: return fake_typeexpr(section, item->t.type); case ITEMSTRUCT: case ITEMUNION: case ITEMCLASS: { TagBinder *tb; char name[12]; Symstr *s; ClassMember **pm, *m; SUC *item_s = &item->s; unsigned32 i; StructField *sf; TypeExpr *t; Binder *b; tb = (TagBinder *)SynAlloc(sizeof(TagBinder)); t = mk_typeexpr1(s_typespec, (TypeExpr *)(asd_code_(item->c) == ITEMSTRUCT ? bitoftype_(s_struct) : (asd_code_(item->c) == ITEMUNION ? bitoftype_(s_union) : bitoftype_(s_class))), (Expr *)tb); add_faked_typeexpr(section, type, t); memset(tb, 0, sizeof(TagBinder)); h0_(tb) = s_tagbind; gensymno++; sprintf(name, "<Anon%d>", gensymno); tagbindsym_(tb) = s = (sym_lookup)(name, 0); tagbindbits_(tb) = TB_DEFD; pm = &tagbindmems_(tb); for (i = 0; i < item_s->fields; i++) { /* /* Note!! We assume the offsets are in ascending order here */ sf = &item_s->fieldtable[i]; m = (ClassMember *)SynAlloc(sizeof(ClassMember)); memset(m, 0, sizeof(ClassMember)); h0_(m) = s_member; memsv_(m) = (sym_lookup)(sf->n.namep, 0); memtype_(m) = fake_typeexpr(section, sf->type); attributes_(m) = A_INTERN; *pm = m; pm = &memcdr_(m); } tagbindtype_(tb) = t; return t; } default: cc_msg("Unhandled item code %d\n", asd_code_(item->c)); return te_int; } return te_int; } } Symstr *int_sym_lookup(char const *name, int glo) { char *varname; VarDef *var; Dbg_Environment env; Dbg_Error err; Symstr *sym; Binder *b; TypeExpr *t; ItemSection *section; ItemVar *item; StgClass stgclass; sym = (sym_lookup)(name, glo); if (symtype_(sym) != s_identifier) return sym; if (bind_global_(sym)) return sym; err = dbg_StringToVarDef(cc_dbg_state, name, cc_dbg_env, &varname, &var, &env); /* fake a Symstr */ symchain_(sym) = 0; bind_global_(sym) = 0; /* Return 0 for binder if err occurs */ symext_(sym) = 0; if (err) { ItemProc *p; Item *ip; TypeExpr *fntype; FormTypeList *ftlist; int i; TypeExprFnAux aux; Symstr *s; size_t size; err = dbg_StringToPath(cc_dbg_state, name, name+strlen(name), &env, 0, cc_dbg_env->st, cc_dbg_env->proc); if (err) return sym; b = SynAlloc(sizeof(Binder)); memset(b, 0, sizeof(Binder)); h0_(b) = s_binder; bindsym_(b) = sym; p = env.proc->item; section = env.proc->n.section; fntype = fake_typeexpr(section, p->type); ftlist = 0; ip = (Item *)p; for (i = 0; i < p->args; i++) { ip = (Item *)(&ip->b + asd_len_(ip->c)); if (asd_code_(ip->v.id) != ITEMVAR) { cc_msg("Missing arguments in debug table\n"); break; } item = (ItemVar *)ip; if (strcmp(item->n.namep, "__struct_result") != 0) { size = offsetof(Symstr, symname) + strlen(item->n.namep) + 1; s = (Symstr *)SynAlloc(size); memclr(s, size); symtype_(s) = s_identifier; strcpy(symname_(s), item->n.namep); ftlist = mkFormTypeList(ftlist, s, fake_typeexpr(section, item->type), 0); i++; } } ftlist = (FormTypeList *)dreverse((List *)ftlist); t = mkTypeExprfn(t_fnap, fntype, 0, ftlist, packTypeExprFnAux(aux, p->args, p->args, 0, 0, 0)); bindtype_(b) = t; bindstg_(b) = bitofstg_(s_extern); bind_global_(sym) = b; bindaddr_(b) = p->startaddr; return sym; } section = var->n.section; item = &var->item->v; if (asd_code_(item->id) != ITEMVAR && asd_code_(item->id) != ITEMTYPE) return sym; stgclass = (StgClass)item->storageclass; /* Fake a binder */ b = SynAlloc(sizeof(Binder)); memset(b, 0, sizeof(Binder)); h0_(b) = s_binder; bindsym_(b) = sym; bindtype_(b) = fake_typeexpr(section, item->type); if (asd_code_(item->id) == ITEMTYPE) bindstg_(b) = bitofstg_(s_typedef); else switch (stgclass) { case C_EXTERN: bindstg_(b) = bitofstg_(s_extern); bindaddr_(b) = (IPtr)item->location.address; break; case C_STATIC: bindstg_(b) = bitofstg_(s_static); bindaddr_(b) = (IPtr)item->location.address; break; case C_AUTO: case C_VAR: bindstg_(b) = bitofstg_(s_auto); if (dbg_FindActivation(cc_dbg_state, cc_dbg_env) != Error_OK) return sym; bindaddr_(b) = FPOffset(item->location.offset, cc_dbg_env); break; case C_REG: bindstg_(b) = bitofstg_(s_register); bindaddr_(b) = (IPtr)0; bindxx_(b) = (VRegnum)item->location.offset; bindxxp_(b) = (void *)cc_dbg_env->frame.fp; break; default: return sym; } bind_global_(sym) = b; return sym; } /* Dummy definitions for stuff in cfe/vargen.c */ void initstaticvar(Binder *b, bool topflag) { } void compile_abort(int sig_no) { /* May be a bit unfriendly for an interactive program */ exit(1); } #ifndef USE_PP int pp_nextchar(void) { if (!expr_string) { int c = getchar(); if (c == EOF) c = PP_EOF; return c; } if (!*expr_string) return PP_EOF; return *expr_string++; } #endif extern void cc_init(void) { int i; #if 0 feature |= FEATURE_CPP; #else feature |= FEATURE_ANSI; feature &= ~(FEATURE_PCC|FEATURE_CPP|FEATURE_CFRONT); #endif expr_string = ""; errstate_init(); aetree_init(); alloc_init(); #ifndef USE_PP for (i = 0; i <= 'z'-'a'; i++) pp_pragmavec[i] = -1; #else compiler_init(); pp_init(&curlex.fl); #endif var_cc_private_flags = 0; bind_init(); lex_init(); builtin_init(); sem_init(); syn_init(); }
stardot/ncc
thumb/tasm.c
/* thumb/asm.c: Copyright (C) Codemist Ltd., 1994. */ /* SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ /* Assembler output is routed to asmstream, annotated if FEATURE_ANNOTATE. */ /* exports: asmstream, display_assembly_code, asm_header, asm_trailer */ #include <errno.h> #ifdef __STDC__ # include <string.h> #else # include <strings.h> #endif #include <ctype.h> #include <assert.h> #include "globals.h" #include "mcdep.h" #include "xrefs.h" #include "store.h" #include "codebuf.h" #include "ops.h" #include "mcdpriv.h" #include "builtin.h" #include "version.h" #include "errors.h" #include "disass.h" #include "bind.h" #ifdef CPLUSPLUS #include "unmangle.h" #endif FILE *asmstream; static bool headerdone; static bool first_area; static bool new_area; #ifndef NO_ASSEMBLER_OUTPUT #define annotations (feature & FEATURE_ANNOTATE) #define toevensex(x,y) (x) /* for cross compilation one day */ static bool asm_error; static Symstr const *out_codeseg; static void asm_blank(int32 n) { while (n-- > 0) fprintf(asmstream, "\n"); } static int32 asm_padcol9(int32 n) { while (n<9) fputc(' ',asmstream), n++; return n; } static void pr_string(int32 w) { int i; union fudge { int32 i; unsigned char c[4]; } ff; ff.i = w; for (i = 0; i < 4; i++) { if (i) fputc(',', asmstream); fprintf(asmstream, "0x%02x", ff.c[i]); } } static void pr_chars(int32 w) /* works on both sex machines */ { int i, c; union fudge { int32 i; unsigned char c[4]; } ff; ff.i = w; fputc('\'', asmstream); for (i=0; i<sizeof(int32); i++) { switch(c = ff.c[i]) { case '\\': case '\'': case '\"': break; case '\a': c = 'a'; break; case '\b': c = 'b'; break; case CHAR_FF: c = 'f'; break; case '\n': c = 'n'; break; case CHAR_CR: c = 'r'; break; case '\t': c = 't'; break; case CHAR_VT: c = 'v'; break; default: if (c < ' ' || c >= 127) fprintf(asmstream, "\\%o", (int)c); else putc(c, asmstream); continue; } putc('\\', asmstream); putc(c, asmstream); } fputc('\'', asmstream); } static void *aux; static void spr_asmname(char *buf, char const *s) { const char *s1 = s; char c; bool oddchars = NO; if (!isalpha(*s) && *s != '_') oddchars = YES; else while ((c = *s1++) != 0) if (!isalnum(c) && c != '_') { oddchars=YES; break; } if (oddchars) sprintf(buf, "|%s|", s); else strcpy(buf, s); } static void pr_asmname(Symstr const *sym) { char const *s = sym == 0 ? (asm_error = 1, "?") : symname_(sym); char buf[256]; spr_asmname(buf, s); fputs(buf, asmstream); } #ifdef CPLUSPLUS static void pr_unmangled_name(const Symstr *sym) { char buf[256]; if (LanguageIsCPlusPlus && annotations) { char const *name = unmangle2(symname_(sym), buf, sizeof buf); if (name != symname_(sym)) fprintf(asmstream, " ; %s", buf); } } #else #define pr_unmangled_name(sym) ((void)0) #endif /* decode_external checks if (and by what) a location is to be relocated. */ static Symstr *decode_external(int32 p) { CodeXref *x; for (x = codexrefs; x!=NULL; x = x->codexrcdr) /* SLOW loop !!! */ if (p == (x->codexroff & 0x00ffffff)) return x->codexrsym; return 0; /* not an external reference */ } /* Disassembler routines */ static int32 destination_label; static char *disass_cb(dis_cb_type type, int32 offset, unsigned32 address, int w, void *cb_arg, char *buf) { switch (type) { case D_LOAD: case D_STORE: case D_SWI: return buf; } if (destination_label != -1) { if ((destination_label & 0xfff00000) == 0) sprintf(buf, "F%ldL%ld", (long)current_procnum, (long)destination_label & 0xfffff); else sprintf(buf, "F%ldL%ld+%ld", (long)current_procnum, (long)destination_label & 0xfffff, (long)((destination_label >> 20) & 0xfff)); buf += strlen(buf); } else { if (aux == 0 && (type == D_LOADPCREL || type == D_STOREPCREL)) sprintf(buf, "[pc, #%ld]", offset); else if (aux != 0) spr_asmname(buf, symname_((Symstr *) aux)); else asm_error = YES; buf += strlen(buf); *buf = 0; } return buf; } static void decode_DC(int32 w) { int32 col = fprintf(asmstream, "DCD"); col = asm_padcol9(col); fprintf(asmstream, "0x%.8lx", (long)w); } static void decode_DCA(Symstr *s, int32 w) { int32 col = fprintf(asmstream, "DCD"); col = asm_padcol9(col); pr_asmname(s); if (w!=0) fprintf(asmstream, "%+ld", (long)w); } /* exported functions ...*/ void display_assembly_code(Symstr const *name) { int32 q, ilen; LabList *asm_lablist2 = 0; List3 *w1, *w2; char buf[256]; if (codep == 0) { new_area = YES; return; } if (new_area) { Symstr *sym = bindsym_(codesegment); asm_blank(1); if (!first_area) fprintf(asmstream, " AREA |C$$%s| %sCODE, READONLY\n", symname_(sym) + 2, (obj_iscommoncode() ? "COMDEF, " : "")); asm_blank(1); pr_asmname(sym); fprintf(asmstream, " DATA"); pr_unmangled_name(sym); asm_blank(1); first_area = NO; new_area = NO; } asm_blank(1); if (name != NULL) { /* may be NULL for string literals from static inits */ asm_lablist2 = asm_lablist; if (StrEq(symname_(name), "main")) obj_symref(libentrypoint, xr_code, 0); if (annotations) fprintf(asmstream, "%.6lx %20s", (long)codebase, ""); pr_asmname(name); pr_unmangled_name(name); asm_blank(1); } /* * The following crude quadratic loop identifies all the labels that are * actually referenced, so that any other ones do not get printed out to * make the assembly code look ugly. */ label_values = (List3 *)dreverse((List *)label_values); label_references = (List3 *)dreverse((List *)label_references); for (w1=label_references; w1!=NULL; w1=(List3 *)cdr_(w1)) { for (w2=label_values; w2!=NULL; w2=(List3 *)cdr_(w2)) { int32 nn = w2->csr; if (nn < 0) continue; if (nn == w1->csr & 0xfffff) { w2->csr = nn | 0x80000000; break; } } } for (q=0; q < codep; q+=ilen) /* q is now a BYTE offset */ { const int32 f = code_flag_(q); int32 w; aux = code_aux_(q & (-2)); while (label_values != NULL && car_(label_values) < q) label_values = (List3 *)label_values->cdr; while (label_values != NULL && car_(label_values) == q) { if (label_values->csr < 0) { if (annotations) fprintf(asmstream, "%28s", ""); fprintf(asmstream, "F%ldL%ld\n", (long)current_procnum, (long)label_values->csr & 0x7fffffff); } label_values = (List3 *)label_values->cdr; } destination_label = -1; while (label_references != NULL && car_(label_references) < q) label_references = (List3 *)label_references->cdr; if (label_references != NULL && car_(label_references) == q) destination_label = label_references->csr; /* * Yeah well - I call disass here so I can decide how long the instruction * is pretending to be. */ if (f == LIT_OPCODE) ilen = disass_16(code_hword_(q), code_hword_(q+2), q, buf, (void *)0, disass_cb); else if (f == LIT_BB || f == LIT_H) { w = code_hword_(q); ilen = 2; } else { w = code_inst_(q); ilen = 4; } if (annotations) { int32 i; fprintf(asmstream, "%.6lx ", (long)(codebase+q)); switch (f) { case LIT_OPCODE: for (i = 0; i < 8; i += 2) if (i < ilen) fprintf(asmstream, "%.4lx ", (long)code_hword_(q+i)); else fprintf(asmstream, " "); break; case LIT_STRING: fprintf(asmstream, "%.8lx ", (long)toevensex(w,LIT_BBBB)); break; default: if (ilen == 2) fprintf(asmstream, "%.4lx ", (long)toevensex(w, LIT_BB)); else fprintf(asmstream, "%.8lx ", (long)toevensex(w, LIT_H)); break; } } fputs(" ", asmstream); switch (f) { #ifdef THUMB_CPLUSPLUS case LIT_OPCODE_32: disass(w, q, buf, (void *)0, disass_cb); fputs(buf, asmstream); break; #endif case LIT_OPCODE: /* * (in fact this has been done already) * disass_16(code_hword_(q), code_hword_(q+2), q, * buf, (void *)0, disass_cb); */ fputs(buf, asmstream); break; case LIT_STRING: { int32 col = fprintf(asmstream, "DCB"); col = asm_padcol9(col); pr_string(w); if (annotations) fprintf(asmstream, " ; "), pr_chars(w); break; } case LIT_BB: { unsigned char b[2]; *(unsigned16 *)b = (unsigned16)w; fprintf(asmstream, "DCB %#.2x,%#.2x", b[0], b[1]); break; } case LIT_H: fprintf(asmstream, "DCW %#.4lx", (long)w); break; case LIT_NUMBER: decode_DC(w); break; case LIT_ADCON: decode_DCA(decode_external(codebase+q), w); break; case LIT_FPNUM: decode_DC(w); if (annotations) fprintf(asmstream, " ; E'%s'", (char *)aux); break; case LIT_FPNUM1: decode_DC(w); if (annotations) fprintf(asmstream, " ; D'%s'",(char *)aux); break; case LIT_FPNUM2: /* all printed by the FPNUM1 */ decode_DC(w); break; case LIT_INT64_1: fprintf(asmstream, "DCD 0x%.8lx, 0x%.8lx", w, code_inst_(q+4)); break; case LIT_INT64_2: /* all printed by the LIT_INT64_2 */ if (annotations) break; else continue; case LIT_RELADDR: default: syserr("syserr_display_asm %ld", (long)f); fprintf(asmstream, "?"); } fprintf(asmstream, "\n"); } if (asm_lablist2) syserr("syserr_asmlab"); asm_lablist = 0; /* stop confusion when called from vargen.c */ } static char const *regnames[] = { "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "ip", "sp", "lr", "pc" }; static char const *annotate_regnames[] = { "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "ip", "sp", "lr", "pc" }; char const **regnamev = regnames; void asm_setregname(int regno, char const *name) { if (headerdone) fprintf(asmstream, "%s RN %d\n", name, regno); regnamev[regno] = name; } void asm_header() { char b[64]; asm_error = 0; first_area = YES; new_area = NO; regnamev = annotations ? annotate_regnames : regnames; disass_sethexprefix("&"); disass_setregnames(regnamev, NULL); headerdone = YES; strcpy(b, "Lib$$Request$$armlib$$"); target_lib_variant(&b[22]); obj_symref(sym_insert_id(b), xr_code+xr_weak, 0); fprintf(asmstream, "; generated by %s\n", CC_BANNER); if (annotations) return; /* do not bore interactive user */ asm_blank(1); fprintf(asmstream, " CODE16\n"); asm_blank(1); fprintf(asmstream, " AREA |C$$code|, CODE, READONLY"); } /* (not exported) */ static void asm_outextern() { ExtRef *x; for (x = obj_symlist; x != 0; x = x->extcdr) { int32 flags = x->extflags; if (!(flags & xr_objflg) && !(flags & xr_defloc) && (flags & xr_defext)) { fprintf(asmstream, " EXPORT "); pr_asmname(x->extsym); fprintf(asmstream, "\n"); } } asm_blank(1); for (x = obj_symlist; x != 0; x = x->extcdr) { int32 flags = x->extflags; if (!(flags & xr_objflg) && !(flags & xr_defloc) && !(flags & xr_defext) && x->extsym != bindsym_(constdatasegment)) { /* COMMON data dealt with earlier */ if (!(flags & xr_code) && (x->extoffset > 0)) continue; fprintf(asmstream, " IMPORT "); pr_asmname(x->extsym); if (x->extflags & xr_weak) fprintf(asmstream, ", WEAK"); fprintf(asmstream, "\n"); } } } typedef struct ExtRefList { struct ExtRefList *cdr; ExtRef *car; } ExtRefList; static void asm_pad(int32 len) { asm_padcol9(1); fprintf(asmstream, "%% %ld\n", (long)len); } static void asm_data(DataInit *p, int constdata) { int32 offset = 0; for (; p != 0; p = p->datacdr) { int32 rpt = p->rpt, sort = p->sort, len = p->len; union { unsigned32 l; unsigned16 w[2]; unsigned8 b[4]; FloatCon *f; } val; val.l = p->val; if (sort != LIT_LABEL) asm_padcol9(1); switch (sort) { case LIT_LABEL: pr_asmname((Symstr *)rpt); /* Below it used to say constdata ... */ if (constdata) fprintf(asmstream, " DATA"); break; default: syserr(syserr_asm_trailer, (long)sort); case LIT_BBBB: if (rpt == 1) { fprintf(asmstream, "DCB %#.2x,%#.2x,%#.2x,%#.2x", val.b[0], val.b[1], val.b[2], val.b[3]); break; } case LIT_BBBX: if (rpt == 1) { fprintf(asmstream, "DCB %#.2x,%#.2x,%#.2x", val.b[0], val.b[1], val.b[2]); break; } case LIT_BBX: if (rpt == 1) { fprintf(asmstream, "DCB %#.2x,%#.2x", val.b[0], val.b[1]); break; } case LIT_BXXX: if (rpt == 1) { fprintf(asmstream, "DCB %#.2x", val.b[0]); break; } case LIT_HH: if (rpt == 1) { fprintf(asmstream, "DCW %#.4x,%#.4x", val.w[0], val.w[1]); break; } case LIT_HX: if (rpt == 1) { fprintf(asmstream, "DCW%c %#.4x", offset & 1 ? 'U' : ' ', val.w[0]); break; } case LIT_BBH: if (rpt == 1) { fprintf(asmstream, "DCB %#.2x,%#.2x\n", val.b[0], val.b[1]); asm_padcol9(1); fprintf(asmstream, "DCW %#.4x", val.w[1]); break; } case LIT_HBX: if (rpt == 1) { fprintf(asmstream, "DCW%c %#.4x\n", offset & 1 ? 'U' : ' ', val.w[0]); asm_padcol9(1); fprintf(asmstream, "DCB %#.2x", val.b[2]); break; } case LIT_HBB: if (rpt == 1) { fprintf(asmstream, "DCW %#.4x\n", val.w[0]); asm_padcol9(1); fprintf(asmstream, "DCB %#.2x,%#.2x", val.b[2], val.b[3]); break; } case LIT_NUMBER: if (len != 4) syserr(syserr_asm_data, (long)len); if (rpt == 1) { fprintf(asmstream, "DCD%c %#.8lx", offset & 3 ? 'U' : ' ', (long)val.l); } else if (val.l == 0) { fprintf(asmstream, "%% %ld", (long)rpt*len); } else syserr(syserr_asm_trailer1, (long)rpt, (long)val.l); break; case LIT_FPNUM: { int32 *p = ((FloatCon *)val.l) -> floatbin.irep; decode_DC(p[0]); if (annotations) fprintf(asmstream, " ; %s", ((FloatCon *)val.l) -> floatstr); if (len == 8) fprintf(asmstream, "\n"), asm_padcol9(1), decode_DC(p[1]); break; } case LIT_ADCON: /* (possibly external) name + offset */ if (rpt != 1) syserr("syserr_asm_trailer2"); decode_DCA((Symstr *)len, val.l); break; } offset = (offset + len) & 3; fprintf(asmstream, "\n"); } } void asm_trailer() { if (constdata_size() != 0) { asm_blank(1); fprintf(asmstream, " AREA |C$$constdata|, DATA, READONLY\n"); asm_blank(1); pr_asmname(bindsym_(constdatasegment)); asm_blank(1); asm_data(constdata_head(), 0); } if (data_size() != 0) { asm_blank(1); fprintf(asmstream, " AREA |C$$data|, DATA\n"); asm_blank(1); asm_data(data_head(), 0); } if (bss_size != 0) { int32 n = 0; ExtRef *x = obj_symlist; ExtRefList *zisyms = NULL; asm_blank(1); fprintf(asmstream, " AREA |C$$zinit|, NOINIT\n"); asm_blank(1); for (; x != NULL; x = x->extcdr) if (x->extflags & xr_bss) { ExtRefList **prev = &zisyms; ExtRefList *p; for (; (p = *prev) != 0; prev = &cdr_(p)) if (x->extoffset < car_(p)->extoffset) break; *prev = (ExtRefList *) syn_cons2(*prev, x); } for (; zisyms != NULL; zisyms = cdr_(zisyms)) { x = car_(zisyms); if (x->extoffset != n) asm_pad(x->extoffset-n); n = x->extoffset; #if 0 maybe_export(x->extsym); indent_18_if_annotating(); #endif pr_asmname(x->extsym); fprintf(asmstream, "\n"); } if (n != bss_size) asm_pad(bss_size-n); } { ExtRef *x; for (x = obj_symlist; x != NULL; x = x->extcdr) { int32 flags = x->extflags; if ((flags & (xr_defloc + xr_defext)) == 0) { /* not defined... */ Symstr *s = x->extsym; int32 len = x->extoffset; if (!(flags & xr_code) && (len > 0)) { /* common data... */ fputs(" EXPORT ", asmstream); pr_asmname(s); asm_blank(1); fprintf(asmstream, " AREA "); pr_asmname(s); fprintf(asmstream, ",COMMON, NOINIT\n"); asm_pad(len); } } } } asm_blank(1); if (!annotations) asm_outextern(); asm_blank(1); fprintf(asmstream, " END\n"); headerdone = NO; if (asm_error) syserr("syserr_asm_confused"); } #endif /* end of thumb/asm.c */
stardot/ncc
cppfe/xbuiltin.c
/* * xbuiltin.c: constants/global symbols for C++ compiler. * Copyright (C) Codemist Ltd., 1988-1993 * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Advanced RISC Machines Limited, 1992, 1994 * SPDX-Licence-Identifier: Apache-2.0 * All rights reserved. */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <time.h> #include <string.h> #include "globals.h" #include "defs.h" #include "builtin.h" #include "bind.h" #include "store.h" #include "aeops.h" #include "aetree.h" #include "sem.h" /* for ovld_instance_name_1 */ #include "dump.h" #include "cg.h" #include "jopcode.h" #define _BUILTIN_H static void builtin_init_cpp(void); #ifndef NO_DUMP_STATE static void Builtin_DumpState_cpp(FILE *f); static void Builtin_LoadState_cpp(FILE *f); #endif #include "builtin.c" Symstr *thissym = DUFF_SYMSTR, *ctorsym = DUFF_SYMSTR, *dtorsym = DUFF_SYMSTR, *assignsym = DUFF_SYMSTR, *vtabsym = DUFF_SYMSTR, *deletesym = DUFF_SYMSTR, *dtorgenlabsym = DUFF_SYMSTR; #define DUFF_EXPR ((Expr*)DUFF_ADDR) #define DUFF_BINDER ((Binder*)DUFF_ADDR) cpp_op_simulation cppsim = { DUFF_SYMSTR, DUFF_SYMSTR, DUFF_BINDER, DUFF_EXPR, DUFF_EXPR, DUFF_EXPR, DUFF_EXPR, DUFF_EXPR, DUFF_EXPR, DUFF_EXPR }; static Binder *library_function_binder_cpp(char *name, TypeExpr* fntype) { Symstr *sv = ovld_instance_name_1(name, fntype); return library_function_binder(sv, fntype); } static Expr *library_function_cpp(char *name, TypeExpr* fntype) { Symstr *sv = ovld_instance_name_1(name, fntype); return library_function_1(sv, fntype); } static void Builtin_DumpState_cpp(FILE *f) { WriteSymRef(thissym, f); WriteSymRef(ctorsym, f); WriteSymRef(dtorsym, f); WriteSymRef(assignsym, f); WriteSymRef(vtabsym, f); WriteSymRef(deletesym, f); WriteSymRef(dtorgenlabsym, f); WriteSymRef(cppsim.xnew, f); WriteSymRef(cppsim.xdel, f); WriteBinderRef(cppsim.xpvfn, f); Dump_Expr(cppsim.xpush_ddtor, f); Dump_Expr(cppsim.xnewvec, f); Dump_Expr(cppsim.xdelvec, f); Dump_Expr(cppsim.xmapvec1, f); Dump_Expr(cppsim.xmapvec1c, f); Dump_Expr(cppsim.xmapvec1ci, f); Dump_Expr(cppsim.xmapvec2, f); } static void Builtin_LoadState_cpp(FILE *f) { thissym = ReadSymRef(f); ctorsym = ReadSymRef(f); dtorsym = ReadSymRef(f); assignsym = ReadSymRef(f); vtabsym = ReadSymRef(f); deletesym = ReadSymRef(f); dtorgenlabsym = ReadSymRef(f); cppsim.xnew = ReadSymRef(f); cppsim.xdel = ReadSymRef(f); cppsim.xpvfn = ReadBinderRef(f); cppsim.xpush_ddtor = Dump_LoadExpr(f); cppsim.xnewvec = Dump_LoadExpr(f); cppsim.xdelvec = Dump_LoadExpr(f); cppsim.xmapvec1 = Dump_LoadExpr(f); cppsim.xmapvec1c = Dump_LoadExpr(f); cppsim.xmapvec1ci = Dump_LoadExpr(f); cppsim.xmapvec2 = Dump_LoadExpr(f); } static void builtin_init_cpp(void) { te_boolean = initprimtype_(bitoftype_(s_bool)); thissym = sym_insert_id("___this"); /* The next 2 lines have these exact names to match [ES] and overload.c */ ctorsym = sym_insert_id("__ct"); dtorsym = sym_insert_id("__dt"); assignsym = sym_insert_id("__as"); vtabsym = sym_insert_id("__VTABLE"); /* Maybe we need __vtp (pointer member) and __vt (static table?) */ deletesym = sym_insert_id("__is_delete"); dtorgenlabsym = sym_insert_id("__generated_dtor_part"); cppsim.xnew = bindsym_(toplevel_function("__nw", te_fntype(te_voidptr, te_size_t, 0, 0, 0, 0))); cppsim.xdel = bindsym_(toplevel_function("__dl", te_fntype(te_void, te_voidptr, 0, 0, 0, 0))); /* Arguable we should just parse appropriate strings instead of this. */ { TypeExpr *PFv_v = g_ptrtotype_(g_te_fntype(te_void, 0, 0, 0, 0, 0)); TypeExpr *PFPv_v = g_ptrtotype_(g_te_fntype(te_void, te_voidptr, 0, 0, 0, 0)); TypeExpr *PFPvi_v = g_ptrtotype_(g_te_fntype(te_void, te_voidptr, te_int, 0, 0, 0)); TypeExpr *PFPvT1_v = g_ptrtotype_(g_te_fntype(te_void, te_voidptr, te_voidptr, 0, 0, 0)); cppsim.xpvfn = library_function_binder_cpp("__pvfn", g_te_fntype(te_void, 0, 0, 0, 0, 0)); cppsim.x__throw = library_function_cpp("__throw", g_te_fntype(te_void, 0, 0, 0, 0, 0)); cppsim.x__ex_pop = library_function_cpp("__ex_pop", g_te_fntype(te_void, 0, 0, 0, 0, 0)); cppsim.x__ex_top = library_function_cpp("__ex_top", g_te_fntype(te_charptr, 0, 0, 0, 0, 0)); cppsim.x__ex_push = library_function_cpp("__ex_push", g_te_fntype(te_charptr, te_int, te_int, 0, 0, 0)); cppsim.xpush_ddtor = library_function_cpp("__push_ddtor", g_te_fntype(te_void, PFv_v, 0, 0, 0, 0)); cppsim.xnewvec = library_function_cpp("__nw_v", g_te_fntype(te_voidptr, te_voidptr, te_size_t, te_size_t, PFPv_v, 0)); cppsim.xdelvec = library_function_cpp("__dl_v", g_te_fntype(te_void, te_voidptr, te_size_t, PFPvi_v, 0, 0)); cppsim.xmapvec1 = library_function_cpp("__vc", g_te_fntype(te_void, te_voidptr, te_size_t, te_int, PFPv_v, 0)); cppsim.xmapvec1c = library_function_cpp("__vc", g_te_fntype(te_void, te_voidptr, te_voidptr, te_int, PFPv_v, 0)); cppsim.xmapvec1ci = library_function_cpp("__vc", g_te_fntype(te_void, te_voidptr, te_voidptr, te_int, PFPvi_v, 0)); cppsim.xmapvec2 = library_function_cpp("__vc", g_te_fntype(te_void, te_voidptr, te_voidptr, te_voidptr, te_size_t, PFPvT1_v)); } te_wchar = initprimtype_(wchar_typespec); te_stringchar = initprimtype_(bitoftype_(s_const)|bitoftype_(s_char)); te_wstringchar = initprimtype_(bitoftype_(s_const)|wchar_typespec); #ifdef EXTENSION_UNSIGNED_STRINGS te_ustringchar = initprimtype_(bitoftype_(s_const)|bitoftype_(s_unsigned)|bitoftype_(s_char)); #endif } /* End of xbuiltin.c */
stardot/ncc
mip/builtin.c
<filename>mip/builtin.c /* * builtin.c: constants/global symbols for C compiler. * Copyright (C) Codemist Ltd., 1987-1992. * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Advanced RISC Machines Limited, 1990-1992. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 23 * Checkin $Date$ * Revising $Author$ */ /* AM memo: names in here are really getting out of control. */ /* Rework soon, but remember that all names should be distinct in the */ /* the first 8 chars for linkers like the os370 ones.... */ /* AM memo: more thought is required in this file to account for */ /* natural (and unnatural) machine parameterisations. In particular */ /* getting the bsd vax/bsd sun/sysV names right is a pain. */ #ifndef _BUILTIN_H #include <time.h> #include <string.h> #include "globals.h" #include "defs.h" #include "builtin.h" #include "bind.h" #include "store.h" #include "aeops.h" #include "aetree.h" #include "dump.h" #include "cg.h" #include "jopcode.h" #define builtin_init_cpp() ((void)0) #define Builtin_DumpState_cpp(f) ((void)0) #define Builtin_LoadState_cpp(f) ((void)0) #endif /* The following line indicates more thought is required re naming. */ #ifdef TARGET_LINKER_OMITS_DOLLAR # define SYSPFX "__" #else # define SYSPFX "x$" #endif FloatCon *fc_two_31; /* floating point constant 2^31 */ FPConst fc_zero; /* floating point constants 0.0 */ #ifdef PASCAL /*ECN*/ FPConst fc_half; /* 0.5 */ FPConst fc_big; /* FLT or DBL MAX */ #endif FPConst fc_one; /* 1.0 */ FPConst fc_two; /* 2.0 */ FPConst fc_minusone; /* -1.0 */ TypeExpr *te_boolean; Expr *lit_false; Expr *lit_true; Expr *lit_zero; Expr *lit_one; TypeExpr *te_char; /* = (global)primtype_(bitoftype_(s_char)) */ TypeExpr *te_int; /* = (global)primtype_(bitoftype_(s_int)) */ TypeExpr *te_ushort, *te_uint, *te_lint, *te_ulint; /* and friends */ TypeExpr *te_llint, *te_ullint; TypeExpr *te_stringchar, *te_wstringchar, *te_wchar; #ifdef EXTENSION_UNSIGNED_STRINGS TypeExpr *te_ustringchar; #endif TypeExpr *te_double; /* = (global)primtype_(bitoftype_(s_double)) */ TypeExpr *te_float; /* its short friend */ TypeExpr *te_ldble; /* and its long one */ TypeExpr *te_void; /* = (global)primtype_(bitoftype_(s_void)) */ TypeExpr *te_charptr; /* = (global)ptrtotype_(te_char))) */ TypeExpr *te_intptr; /* = (global)ptrtotype_(te_int))) */ TypeExpr *te_voidptr; /* = (global)ptrtotype_(te_void))) */ /* since no-one looks inside datasegment and code segment perhaps they should be Symstr's */ Binder *datasegment, *codesegment, *constdatasegment, *ddtorsegment; #ifdef TARGET_HAS_BSS Binder *bsssegment; #endif Binder *extablesegment, *exhandlersegment; Symstr *mainsym, *setjmpsym, *assertsym, *first_arg_sym, *last_arg_sym; Symstr *libentrypoint, *stackoverflow, *stack1overflow, *countroutine, *count1routine; Symstr *traproutine; Symstr *targeterrno; #define PUREBIT bitoffnaux_(s_pure) #define COMMBIT bitoffnaux_(s_commutative) op_simulation sim; static Symstr *mallocsym, *callocsym, *reallocsym; bool returnsheapptr(Symstr *fn) { return (fn == mallocsym || fn == callocsym || fn == reallocsym || strncmp("__nw__", fn->symname, 6) == 0); } static Binder *library_function_binder(Symstr* sym, TypeExpr* fntype) { return global_mk_binder(0, sym, bitofstg_(s_extern) | b_undef | b_fnconst, fntype); } static Expr *library_function_1(Symstr* sym, TypeExpr* fntype) { return (Expr*) global_list4(SU_Other, s_addrof, global_list4(SU_Type, t_content, fntype, 0, 0), (FileLine *)0, library_function_binder(sym, fntype)); } static Expr *library_function(char *name, int minf, int maxf, int32 flags) { Symstr *sv = sym_insert_id(name); TypeExprFnAux s; TypeExpr *fntype = g_mkTypeExprfn(t_fnap, te_int, 0, 0, packTypeExprFnAux(s, minf, maxf, 0, 0, flags)); return library_function_1(sv, fntype); } TypeExpr *te_fntype(TypeExpr *res, TypeExpr *a1, TypeExpr *a2, TypeExpr *a3, TypeExpr *a4, TypeExpr *a5) { TypeExprFnAux s; int n = 0; FormTypeList *f = 0; if (a5) f = mkFormTypeList(f, 0, a5, 0), n++; if (a4) f = mkFormTypeList(f, 0, a4, 0), n++; if (a3) f = mkFormTypeList(f, 0, a3, 0), n++; if (a2) f = mkFormTypeList(f, 0, a2, 0), n++; if (a1) f = mkFormTypeList(f, 0, a1, 0), n++; return mkTypeExprfn(t_fnap, res, 0, f, packTypeExprFnAux(s, n,n,0,0,0)); } TypeExpr *g_te_fntype(TypeExpr *res, TypeExpr *a1, TypeExpr *a2, TypeExpr *a3, TypeExpr *a4, TypeExpr *a5) { TypeExprFnAux s; int n = 0; FormTypeList *f = 0; if (a5) f = g_mkFormTypeList(f, 0, a5, 0), n++; if (a4) f = g_mkFormTypeList(f, 0, a4, 0), n++; if (a3) f = g_mkFormTypeList(f, 0, a3, 0), n++; if (a2) f = g_mkFormTypeList(f, 0, a2, 0), n++; if (a1) f = g_mkFormTypeList(f, 0, a1, 0), n++; return g_mkTypeExprfn(t_fnap, res, 0, f, packTypeExprFnAux(s, n,n,0,0,0)); } #ifdef CPLUSPLUS /* We could use this more for C things too, but beware top-level names */ /* starting with a single '_' which could upset conforming C progs. */ static Binder *toplevel_function(char *name, TypeExpr *t) { Symstr *sv = sym_insert_id(name); DeclRhsList *d = mkDeclRhsList( /* declname = */ sv, /* decltype = */ t, /* declstg = */ bitofstg_(s_extern) | b_fnconst | b_undef); (void)instate_declaration(d, TOPLEVEL); /* instate_declaration() returns the unwanted INSTANCE Binder. */ return bind_global_(sv); } #endif static Expr *floating_function(int nargs, TypeExpr *result, TypeExpr *a1, TypeExpr *a2, char *name, int32 fl) { Symstr *w = sym_insert_id(name), *a_name = sym_insert_id("a"), *b_name = sym_insert_id("b"); Binder *b; FormTypeList *a = g_mkFormTypeList(0, a_name, a1, 0); TypeExprFnAux s; fl |= #ifdef SOFTWARE_FLOATING_POINT_RETURNS_DOUBLES_IN_REGISTERS (result == te_double) ? bitoffnaux_(s_structreg)|bitoffnaux_(s_pure) : #else (result == te_double) ? 0 : #endif bitoffnaux_(s_pure); if (fl & f_resultinflags) fl &= ~bitoffnaux_(s_pure); if (nargs != 1) a->ftcdr = g_mkFormTypeList(0, b_name, a2, 0); b = global_mk_binder(0, w, bitofstg_(s_extern) | b_undef | b_fnconst, g_mkTypeExprfn(t_fnap, result, 0, a, packTypeExprFnAux(s, nargs, nargs, 0, 0, fl))); return (Expr *)b; } static Expr *ll_function(int nargs, TypeExpr *result, TypeExpr *a1, TypeExpr *a2, char *name, int32 fl) { Symstr *w = sym_insert_id(name), *a_name = sym_insert_id("a"), *b_name = sym_insert_id("b"); Binder *b; FormTypeList *a = g_mkFormTypeList(0, a_name, a1, 0); TypeExprFnAux s; fl |= (result == te_llint || result == te_ullint) ? bitoffnaux_(s_structreg)|bitoffnaux_(s_pure) : bitoffnaux_(s_pure); if (fl & f_resultinflags) fl &= ~bitoffnaux_(s_pure); if (nargs != 1) a->ftcdr = g_mkFormTypeList(0, b_name, a2, 0); b = global_mk_binder(0, w, bitofstg_(s_extern) | b_undef | b_fnconst, g_mkTypeExprfn(t_fnap, result, 0, a, packTypeExprFnAux(s, nargs, nargs, 0, 0, fl))); return (Expr *)b; } #ifdef UNIQUE_DATASEG_NAMES /* The following routine hacks round a bug in Acorn's linker (June 87) */ /* w.r.t. local symbols in different files being confused. */ /* Something like it is probably needed for 370 CSECT names. */ /* Acorn linker bug corrected July 87, so this code disabled. */ /* ... but the code is still useful for Helios! */ static int main_compilation_count = 0; static char *probably_unique_name(int ch) { static char name[32]; #ifdef TARGET_LINKER_OMITS_DOLLAR sprintf(name, "__%c%lx", ch, (long)(20L*time(NULL)+main_compilation_count)); #else sprintf(name, "x$%c%lx", ch, (long)(20L*time(NULL)+main_compilation_count)); #endif return name; } #endif static void initfpconst(FPConst *fc, const char val[]) { fc->s = real_of_string(val, ts_float); fc->d = real_of_string(val, ts_double); } static Expr *globalize_integer(TypeExpr *t, int n) { return (Expr *)global_list5(SU_Const, s_integer, t, (FileLine *)NULL, (Expr *)n, (Expr *)NULL); } #ifndef NO_DUMP_STATE static Binder *ReadBinderRef(FILE *f) { uint32 w; fread(&w, sizeof(uint32), 1, f); return Dump_LoadedBinder(w); } static Symstr *ReadSymRef(FILE *f) { uint32 w; fread(&w, sizeof(uint32), 1, f); return Dump_LoadedSym(w); } void Builtin_LoadState(FILE *f) { sim.mulfn = Dump_LoadExpr(f); sim.divfn = Dump_LoadExpr(f); sim.udivfn = Dump_LoadExpr(f); sim.divtestfn = Dump_LoadExpr(f); sim.remfn = Dump_LoadExpr(f); sim.uremfn = Dump_LoadExpr(f); sim.fdivfn = Dump_LoadExpr(f); sim.ddivfn = Dump_LoadExpr(f); #ifdef TARGET_HAS_DIV_10_FUNCTION sim.div10fn = Dump_LoadExpr(f); sim.udiv10fn = Dump_LoadExpr(f); sim.rem10fn = Dump_LoadExpr(f); sim.urem10fn = Dump_LoadExpr(f); #endif sim.xprintf = Dump_LoadExpr(f); sim.xfprintf = Dump_LoadExpr(f); sim.xsprintf = Dump_LoadExpr(f); sim.yprintf = ReadSymRef(f); sim.yfprintf = ReadSymRef(f); sim.ysprintf = ReadSymRef(f); sim.dadd = (Expr *)ReadBinderRef(f); sim.dsubtract = (Expr *)ReadBinderRef(f); sim.dmultiply = (Expr *)ReadBinderRef(f); sim.ddivide = (Expr *)ReadBinderRef(f); sim.dnegate = (Expr *)ReadBinderRef(f); sim.dgreater = (Expr *)ReadBinderRef(f); sim.dgeq = (Expr *)ReadBinderRef(f); sim.dless = (Expr *)ReadBinderRef(f); sim.dleq = (Expr *)ReadBinderRef(f); sim.dequal = (Expr *)ReadBinderRef(f); sim.dneq = (Expr *)ReadBinderRef(f); sim.dfloat = (Expr *)ReadBinderRef(f); sim.dfloatu = (Expr *)ReadBinderRef(f); sim.dfix = (Expr *)ReadBinderRef(f); sim.dfixu = (Expr *)ReadBinderRef(f); sim.fadd = (Expr *)ReadBinderRef(f); sim.fsubtract = (Expr *)ReadBinderRef(f); sim.fmultiply = (Expr *)ReadBinderRef(f); sim.fdivide = (Expr *)ReadBinderRef(f); sim.fnegate = (Expr *)ReadBinderRef(f); sim.fgreater = (Expr *)ReadBinderRef(f); sim.fgeq = (Expr *)ReadBinderRef(f); sim.fless = (Expr *)ReadBinderRef(f); sim.fleq = (Expr *)ReadBinderRef(f); sim.fequal = (Expr *)ReadBinderRef(f); sim.fneq = (Expr *)ReadBinderRef(f); sim.ffloat = (Expr *)ReadBinderRef(f); sim.ffloatu = (Expr *)ReadBinderRef(f); sim.ffix = (Expr *)ReadBinderRef(f); sim.ffixu = (Expr *)ReadBinderRef(f); sim.fnarrow = (Expr *)ReadBinderRef(f); sim.dwiden = (Expr *)ReadBinderRef(f); #ifdef TARGET_SOFTFP_SUPPORT_INCLUDES_REVERSE_OPS sim.drsb = (Expr *)ReadBinderRef(f); sim.drdiv = (Expr *)ReadBinderRef(f); sim.frsb = (Expr *)ReadBinderRef(f); sim.frdiv = (Expr *)ReadBinderRef(f); #endif sim.llnot = (Expr *)ReadBinderRef(f); sim.llneg = (Expr *)ReadBinderRef(f); sim.lladd = (Expr *)ReadBinderRef(f); sim.llrsb = (Expr *)ReadBinderRef(f); sim.llsub = (Expr *)ReadBinderRef(f); sim.llmul = (Expr *)ReadBinderRef(f); sim.llurdv = (Expr *)ReadBinderRef(f); sim.lludiv = (Expr *)ReadBinderRef(f); sim.llsrdv = (Expr *)ReadBinderRef(f); sim.llsdiv = (Expr *)ReadBinderRef(f); sim.llurrem = (Expr *)ReadBinderRef(f); sim.llurem = (Expr *)ReadBinderRef(f); sim.llsrrem = (Expr *)ReadBinderRef(f); sim.llsrem = (Expr *)ReadBinderRef(f); sim.lland = (Expr *)ReadBinderRef(f); sim.llor = (Expr *)ReadBinderRef(f); sim.lleor = (Expr *)ReadBinderRef(f); sim.llshiftl = (Expr *)ReadBinderRef(f); sim.llushiftr = (Expr *)ReadBinderRef(f); sim.llsshiftr = (Expr *)ReadBinderRef(f); sim.llcmpeq = (Expr *)ReadBinderRef(f); sim.llcmpne = (Expr *)ReadBinderRef(f); sim.llucmpgt = (Expr *)ReadBinderRef(f); sim.llucmpge = (Expr *)ReadBinderRef(f); sim.llucmplt = (Expr *)ReadBinderRef(f); sim.llucmple = (Expr *)ReadBinderRef(f); sim.llscmpgt = (Expr *)ReadBinderRef(f); sim.llscmpge = (Expr *)ReadBinderRef(f); sim.llscmplt = (Expr *)ReadBinderRef(f); sim.llscmple = (Expr *)ReadBinderRef(f); sim.llfroml = (Expr *)ReadBinderRef(f); sim.llfromu = (Expr *)ReadBinderRef(f); sim.llsfromd = (Expr *)ReadBinderRef(f); sim.llsfromf = (Expr *)ReadBinderRef(f); sim.llufromd = (Expr *)ReadBinderRef(f); sim.llufromf = (Expr *)ReadBinderRef(f); sim.lltol = (Expr *)ReadBinderRef(f); sim.llstod = (Expr *)ReadBinderRef(f); sim.llstof = (Expr *)ReadBinderRef(f); sim.llutod = (Expr *)ReadBinderRef(f); sim.llutof = (Expr *)ReadBinderRef(f); sim.readcheck1 = Dump_LoadExpr(f); sim.readcheck2 = Dump_LoadExpr(f); sim.readcheck4 = Dump_LoadExpr(f); sim.writecheck1 = Dump_LoadExpr(f); sim.writecheck2 = Dump_LoadExpr(f); sim.writecheck4 = Dump_LoadExpr(f); sim.proc_entry = Dump_LoadExpr(f); sim.proc_exit = Dump_LoadExpr(f); sim.memcpyfn = Dump_LoadExpr(f); sim.memsetfn = Dump_LoadExpr(f); sim.realmemcpyfn = Dump_LoadExpr(f); sim.realmemsetfn = Dump_LoadExpr(f); sim.strcpysym = ReadSymRef(f); sim.strlensym = ReadSymRef(f); mallocsym = ReadSymRef(f); callocsym = ReadSymRef(f); reallocsym = ReadSymRef(f); sim.dpow = ReadSymRef(f); sim.dceil = ReadSymRef(f); sim.dfloor = ReadSymRef(f); sim.dmod = ReadSymRef(f); sim.dabs = ReadSymRef(f); sim.inserted_word = Dump_LoadExpr(f); datasegment = ReadBinderRef(f); codesegment = ReadBinderRef(f); #ifdef TARGET_HAS_BSS bsssegment = ReadBinderRef(f); #endif ddtorsegment = ReadBinderRef(f); constdatasegment = ReadBinderRef(f); extablesegment = ReadBinderRef(f); exhandlersegment = ReadBinderRef(f); mainsym = ReadSymRef(f); setjmpsym = ReadSymRef(f); first_arg_sym = ReadSymRef(f); last_arg_sym = ReadSymRef(f); lit_false = Dump_LoadExpr(f); lit_true = Dump_LoadExpr(f); lit_zero = Dump_LoadExpr(f); lit_one = Dump_LoadExpr(f); if (LanguageIsCPlusPlus) Builtin_LoadState_cpp(f); } static void WriteBinderRef(Binder *b, FILE *f) { uint32 w = Dump_BinderRef(b); fwrite(&w, sizeof(uint32), 1, f); } static void WriteSymRef(Symstr *sym, FILE *f) { uint32 w = Dump_SymRef(sym); fwrite(&w, sizeof(uint32), 1, f); } void Builtin_DumpState(FILE *f) { Dump_Expr(sim.mulfn, f); Dump_Expr(sim.divfn, f); Dump_Expr(sim.udivfn, f); Dump_Expr(sim.divtestfn, f); Dump_Expr(sim.remfn, f); Dump_Expr(sim.uremfn, f); Dump_Expr(sim.fdivfn, f); Dump_Expr(sim.ddivfn, f); #ifdef TARGET_HAS_DIV_10_FUNCTION Dump_Expr(sim.div10fn, f); Dump_Expr(sim.udiv10fn, f); Dump_Expr(sim.rem10fn, f); /* obsolete */ Dump_Expr(sim.urem10fn, f); /* obsolete */ #endif Dump_Expr(sim.xprintf, f); Dump_Expr(sim.xfprintf, f); Dump_Expr(sim.xsprintf, f); WriteSymRef(sim.yprintf, f); WriteSymRef(sim.yfprintf, f); WriteSymRef(sim.ysprintf, f); WriteBinderRef(exb_(sim.dadd), f); WriteBinderRef(exb_(sim.dsubtract), f); WriteBinderRef(exb_(sim.dmultiply), f); WriteBinderRef(exb_(sim.ddivide), f); WriteBinderRef(exb_(sim.dnegate), f); WriteBinderRef(exb_(sim.dgreater), f); WriteBinderRef(exb_(sim.dgeq), f); WriteBinderRef(exb_(sim.dless), f); WriteBinderRef(exb_(sim.dleq), f); WriteBinderRef(exb_(sim.dequal), f); WriteBinderRef(exb_(sim.dneq), f); WriteBinderRef(exb_(sim.dfloat), f); WriteBinderRef(exb_(sim.dfloatu), f); WriteBinderRef(exb_(sim.dfix), f); WriteBinderRef(exb_(sim.dfixu), f); WriteBinderRef(exb_(sim.fadd), f); WriteBinderRef(exb_(sim.fsubtract), f); WriteBinderRef(exb_(sim.fmultiply), f); WriteBinderRef(exb_(sim.fdivide), f); WriteBinderRef(exb_(sim.fnegate), f); WriteBinderRef(exb_(sim.fgreater), f); WriteBinderRef(exb_(sim.fgeq), f); WriteBinderRef(exb_(sim.fless), f); WriteBinderRef(exb_(sim.fleq), f); WriteBinderRef(exb_(sim.fequal), f); WriteBinderRef(exb_(sim.fneq), f); WriteBinderRef(exb_(sim.ffloat), f); WriteBinderRef(exb_(sim.ffloatu), f); WriteBinderRef(exb_(sim.ffix), f); WriteBinderRef(exb_(sim.ffixu), f); WriteBinderRef(exb_(sim.fnarrow), f); WriteBinderRef(exb_(sim.dwiden), f); #ifdef TARGET_SOFTFP_SUPPORT_INCLUDES_REVERSE_OPS WriteBinderRef(exb_(sim.drsb), f); WriteBinderRef(exb_(sim.drdiv), f); WriteBinderRef(exb_(sim.frsb), f); WriteBinderRef(exb_(sim.frdiv), f); #endif WriteBinderRef(exb_(sim.llnot), f); WriteBinderRef(exb_(sim.llneg), f); WriteBinderRef(exb_(sim.lladd), f); WriteBinderRef(exb_(sim.llrsb), f); WriteBinderRef(exb_(sim.llsub), f); WriteBinderRef(exb_(sim.llmul), f); WriteBinderRef(exb_(sim.llurdv), f); WriteBinderRef(exb_(sim.lludiv), f); WriteBinderRef(exb_(sim.llsrdv), f); WriteBinderRef(exb_(sim.llsdiv), f); WriteBinderRef(exb_(sim.llurrem), f); WriteBinderRef(exb_(sim.llurem), f); WriteBinderRef(exb_(sim.llsrrem), f); WriteBinderRef(exb_(sim.llsrem), f); WriteBinderRef(exb_(sim.lland), f); WriteBinderRef(exb_(sim.llor), f); WriteBinderRef(exb_(sim.lleor), f); WriteBinderRef(exb_(sim.llshiftl), f); WriteBinderRef(exb_(sim.llushiftr), f); WriteBinderRef(exb_(sim.llsshiftr), f); WriteBinderRef(exb_(sim.llcmpeq), f); WriteBinderRef(exb_(sim.llcmpne), f); WriteBinderRef(exb_(sim.llucmpgt), f); WriteBinderRef(exb_(sim.llucmpge), f); WriteBinderRef(exb_(sim.llucmplt), f); WriteBinderRef(exb_(sim.llucmple), f); WriteBinderRef(exb_(sim.llscmpgt), f); WriteBinderRef(exb_(sim.llscmpge), f); WriteBinderRef(exb_(sim.llscmplt), f); WriteBinderRef(exb_(sim.llscmple), f); WriteBinderRef(exb_(sim.llfroml), f); WriteBinderRef(exb_(sim.llfromu), f); WriteBinderRef(exb_(sim.llsfromf), f); WriteBinderRef(exb_(sim.llsfromd), f); WriteBinderRef(exb_(sim.llufromf), f); WriteBinderRef(exb_(sim.llufromd), f); WriteBinderRef(exb_(sim.lltol), f); WriteBinderRef(exb_(sim.llstod), f); WriteBinderRef(exb_(sim.llstof), f); WriteBinderRef(exb_(sim.llutod), f); WriteBinderRef(exb_(sim.llutof), f); Dump_Expr(sim.readcheck1, f); Dump_Expr(sim.readcheck2, f); Dump_Expr(sim.readcheck4, f); Dump_Expr(sim.writecheck1, f); Dump_Expr(sim.writecheck2, f); Dump_Expr(sim.writecheck4, f); Dump_Expr(sim.proc_entry, f); Dump_Expr(sim.proc_exit , f); /* _memcpyfn and _memsetfn are internals for (aligned) struct copy/clr */ Dump_Expr(sim.memcpyfn, f); Dump_Expr(sim.memsetfn, f); Dump_Expr(sim.realmemcpyfn, f); Dump_Expr(sim.realmemsetfn, f); WriteSymRef(sim.strcpysym, f); WriteSymRef(sim.strlensym, f); WriteSymRef(mallocsym, f); WriteSymRef(callocsym, f); WriteSymRef(reallocsym, f); WriteSymRef(sim.dpow, f); WriteSymRef(sim.dceil, f); WriteSymRef(sim.dfloor, f); WriteSymRef(sim.dmod, f); WriteSymRef(sim.dabs, f); Dump_Expr(sim.inserted_word, f); WriteBinderRef(datasegment, f); WriteBinderRef(codesegment, f); #ifdef TARGET_HAS_BSS WriteBinderRef(bsssegment, f); #endif WriteBinderRef(ddtorsegment, f); WriteBinderRef(constdatasegment, f); WriteBinderRef(extablesegment, f); WriteBinderRef(exhandlersegment, f); WriteSymRef(mainsym, f); WriteSymRef(setjmpsym, f); WriteSymRef(first_arg_sym, f); WriteSymRef(last_arg_sym, f); Dump_Expr(lit_false, f); Dump_Expr(lit_true, f); Dump_Expr(lit_zero, f); Dump_Expr(lit_one, f); if (LanguageIsCPlusPlus) Builtin_DumpState_cpp(f); } #endif void builtin_init(void) { initfpconst(&fc_zero, "0.0"); #ifdef PASCAL /*ECN*/ initfpconst(&fc_half, "0.5"); fc_big.s = real_of_string("3.40282347e+38", ts_float); fc_big.d = real_of_string("1.79769313486231571e+308", ts_double); #endif initfpconst(&fc_one, "1.0"); initfpconst(&fc_two, "2.0"); initfpconst(&fc_minusone, "-1.0"); fc_two_31 = real_of_string("2147483648.0", ts_double); #define initprimtype_(t) (TypeExpr*)global_list4(SU_Other, s_typespec, (t),0,0); te_char = initprimtype_(bitoftype_(s_char)); te_int = initprimtype_(ts_int); te_ushort = initprimtype_(ts_short|bitoftype_(s_unsigned)); te_uint = initprimtype_(ts_int|bitoftype_(s_unsigned)); te_lint = initprimtype_(ts_long); te_ulint = initprimtype_(ts_long|bitoftype_(s_unsigned)); te_llint = initprimtype_(ts_longlong); te_ullint = initprimtype_(ts_longlong|bitoftype_(s_unsigned)); te_double = initprimtype_(ts_double); te_float = initprimtype_(ts_float); te_ldble = initprimtype_(ts_longdouble); te_void = initprimtype_(bitoftype_(s_void)); #define g_ptrtotype_(t) (TypeExpr*)global_list4(SU_Other, t_content, (t), 0, 0) te_charptr = g_ptrtotype_(te_char); te_intptr = g_ptrtotype_(te_int); te_voidptr = g_ptrtotype_(te_void); #if defined(TARGET_IS_UNIX) && !defined(TARGET_IS_SPARC) && !defined(TARGET_IS_ALPHA) sim.mulfn = library_function("x$mul", 2, 2, PUREBIT); sim.divfn = library_function("x$div", 2, 2, PUREBIT); sim.udivfn = library_function("x$udiv", 2, 2, PUREBIT); sim.divtestfn = library_function("x$divtest", 1, 1, PUREBIT); sim.remfn = library_function("x$mod", 2, 2, PUREBIT); sim.uremfn = library_function("x$umod", 2, 2, PUREBIT); sim.fdivfn = library_function("x$fdiv", 2, 2, PUREBIT); sim.ddivfn = library_function("x$ddiv", 2, 2, PUREBIT); #else #ifdef TARGET_LINKER_OMITS_DOLLAR sim.mulfn = library_function("__multiply", 2, 2, PUREBIT); sim.divfn = library_function("__divide", 2, 2, PUREBIT); sim.udivfn = library_function("__udivide", 2, 2, PUREBIT); sim.divtestfn = library_function("__divtest", 1, 1, PUREBIT); sim.remfn = library_function("__remainder", 2, 2, PUREBIT); sim.uremfn = library_function("__uremainder", 2, 2, PUREBIT); sim.fdivfn = library_function("__fdivide", 2, 2, PUREBIT); sim.ddivfn = library_function("__ddivide", 2, 2, PUREBIT); #else /* the 'obsolete's below refer to the ARM only. */ sim.mulfn = library_function("x$multiply", 2, 2, PUREBIT); /* obsolete */ #if defined(TARGET_IS_ARM_OR_THUMB) && !defined(OBSOLETE_ARM_NAMES) sim.divfn = library_function(TARGET_PREFIX("__rt_sdiv"), 2, 2, PUREBIT); sim.udivfn = library_function(TARGET_PREFIX("__rt_udiv"), 2, 2, PUREBIT); sim.divtestfn = library_function(TARGET_PREFIX("__rt_divtest"), 1, 1, PUREBIT); #else sim.divfn = library_function("x$divide", 2, 2, PUREBIT); sim.udivfn = library_function("x$udivide", 2, 2, PUREBIT); sim.divtestfn = library_function("x$divtest", 1, 1, PUREBIT); #endif sim.remfn = library_function("x$remainder", 2, 2, PUREBIT); /* obsolete */ sim.uremfn = library_function("x$uremainder", 2, 2, PUREBIT); /* obsolete */ sim.fdivfn = library_function("x$fdivide", 2, 2, PUREBIT); sim.ddivfn = library_function("x$ddivide", 2, 2, PUREBIT); #endif #endif #ifdef TARGET_HAS_DIV_10_FUNCTION #if defined(TARGET_IS_ARM_OR_THUMB) && !defined(OBSOLETE_ARM_NAMES) sim.div10fn = library_function(TARGET_PREFIX("__rt_sdiv10"), 1, 1, PUREBIT); sim.udiv10fn = library_function(TARGET_PREFIX("__rt_udiv10"), 1, 1, PUREBIT); #else sim.div10fn = library_function("_kernel_sdiv10", 1, 1, PUREBIT); sim.udiv10fn = library_function("_kernel_udiv10", 1, 1, PUREBIT); #endif sim.rem10fn = library_function("_kernel_srem10", 1, 1, PUREBIT); /* obsolete */ sim.urem10fn = library_function("_kernel_urem10", 1, 1, PUREBIT); /* obsolete */ #endif sim.xprintf = library_function("_printf", 1, 1999, 0L); sim.xfprintf = library_function("_fprintf", 2, 1999, 0L); sim.xsprintf = library_function("_sprintf", 2, 1999, 0L); sim.yprintf = sym_insert_id("printf"); sim.yfprintf = sym_insert_id("fprintf"); sim.ysprintf = sym_insert_id("sprintf"); #ifdef STRING_COMPRESSION sim.xprintf_z = library_function("_printf$Z", 1, 1999, 0L); sim.xfprintf_z = library_function("_fprintf$Z", 2, 1999, 0L); sim.xsprintf_z = library_function("_sprintf$Z", 2, 1999, 0L); sim.yprintf_z = library_function("printf$Z", 1, 1999, 0L); sim.yfprintf_z = library_function("fprintf$Z", 2, 1999, 0L); sim.ysprintf_z = library_function("sprintf$Z", 2, 1999, 0L); #endif sim.dadd = floating_function(2,te_double,te_double,te_double,TARGET_PREFIX("_dadd"), COMMBIT); sim.dsubtract = floating_function(2,te_double,te_double,te_double,TARGET_PREFIX("_dsub"), 0); sim.dmultiply = floating_function(2,te_double,te_double,te_double,TARGET_PREFIX("_dmul"), COMMBIT); sim.ddivide = floating_function(2,te_double,te_double,te_double,TARGET_PREFIX("_ddiv"), 0); sim.dnegate = floating_function(1,te_double,te_double,NULL,TARGET_PREFIX("_dneg"), 0); if (resultinflags) { sim.dgreater = floating_function(2,te_int,te_double,te_double,TARGET_PREFIX("_dcmpge"), f_resultinflags | Q_HI); sim.dgeq = floating_function(2,te_int,te_double,te_double,TARGET_PREFIX("_dcmpge"), f_resultinflags | Q_HS); sim.dless = floating_function(2,te_int,te_double,te_double,TARGET_PREFIX("_dcmple"), f_resultinflags | Q_LO); sim.dleq = floating_function(2,te_int,te_double,te_double,TARGET_PREFIX("_dcmple"), f_resultinflags | Q_LS); sim.dequal = floating_function(2,te_int,te_double,te_double,TARGET_PREFIX("_dcmpeq"), COMMBIT | f_resultinflags | Q_EQ); sim.dneq = floating_function(2,te_int,te_double,te_double,TARGET_PREFIX("_dcmpeq"), COMMBIT | f_resultinflags | Q_NE); } else { sim.dgreater = floating_function(2,te_int,te_double,te_double,TARGET_PREFIX("_dgr"), 0); sim.dgeq = floating_function(2,te_int,te_double,te_double,TARGET_PREFIX("_dgeq"), 0); sim.dless = floating_function(2,te_int,te_double,te_double,TARGET_PREFIX("_dls"), 0); sim.dleq = floating_function(2,te_int,te_double,te_double,TARGET_PREFIX("_dleq"), 0); sim.dequal = floating_function(2,te_int,te_double,te_double,TARGET_PREFIX("_deq"), COMMBIT); sim.dneq = floating_function(2,te_int,te_double,te_double,TARGET_PREFIX("_dneq"), COMMBIT); } sim.dfloat = floating_function(1,te_double,te_int,NULL,TARGET_PREFIX("_dflt"), 0); sim.dfloatu = floating_function(1,te_double,te_uint,NULL,TARGET_PREFIX("_dfltu"), 0); sim.dfix = floating_function(1,te_int,te_double,NULL,TARGET_PREFIX("_dfix"), 0); sim.dfixu = floating_function(1,te_uint,te_double,NULL,TARGET_PREFIX("_dfixu"), 0); sim.fadd = floating_function(2,te_float,te_int,te_int,TARGET_PREFIX("_fadd"), COMMBIT); sim.fsubtract = floating_function(2,te_float,te_int,te_int,TARGET_PREFIX("_fsub"), 0); sim.fmultiply = floating_function(2,te_float,te_int,te_int,TARGET_PREFIX("_fmul"), COMMBIT); sim.fdivide = floating_function(2,te_float,te_int,te_int,TARGET_PREFIX("_fdiv"), 0); sim.fnegate = floating_function(1,te_float,te_int,NULL,TARGET_PREFIX("_fneg"), 0); if (resultinflags) { sim.fgreater = floating_function(2,te_int,te_int,te_int,TARGET_PREFIX("_fcmpge"), f_resultinflags | Q_HI); sim.fgeq = floating_function(2,te_int,te_int,te_int,TARGET_PREFIX("_fcmpge"), f_resultinflags | Q_HS); sim.fless = floating_function(2,te_int,te_int,te_int,TARGET_PREFIX("_fcmple"), f_resultinflags | Q_LO); sim.fleq = floating_function(2,te_int,te_int,te_int,TARGET_PREFIX("_fcmple"), f_resultinflags | Q_LS); sim.fequal = floating_function(2,te_int,te_int,te_int,TARGET_PREFIX("_fcmpeq"), COMMBIT | f_resultinflags | Q_EQ); sim.fneq = floating_function(2,te_int,te_int,te_int,TARGET_PREFIX("_fcmpeq"), COMMBIT | f_resultinflags | Q_NE); } else { sim.fgreater = floating_function(2,te_int,te_int,te_int,TARGET_PREFIX("_fgr"), 0); sim.fgeq = floating_function(2,te_int,te_int,te_int,TARGET_PREFIX("_fgeq"), 0); sim.fless = floating_function(2,te_int,te_int,te_int,TARGET_PREFIX("_fls"), 0); sim.fleq = floating_function(2,te_int,te_int,te_int,TARGET_PREFIX("_fleq"), 0); sim.fequal = floating_function(2,te_int,te_int,te_int,TARGET_PREFIX("_feq"), COMMBIT); sim.fneq = floating_function(2,te_int,te_int,te_int,TARGET_PREFIX("_fneq"), COMMBIT); } sim.ffloat = floating_function(1,te_float,te_int,NULL,TARGET_PREFIX("_fflt"), 0); sim.ffloatu = floating_function(1,te_float,te_uint,NULL,TARGET_PREFIX("_ffltu"), f_resultinintregs); sim.ffix = floating_function(1,te_int,te_int,NULL,TARGET_PREFIX("_ffix"), 0); sim.ffixu = floating_function(1,te_uint,te_int,NULL,TARGET_PREFIX("_ffixu"), f_nofpregargs); sim.fnarrow = floating_function(1,te_float,te_double,NULL,TARGET_PREFIX("_d2f"), f_nofpregargs|f_resultinintregs); sim.dwiden = floating_function(1,te_double,te_float,NULL,TARGET_PREFIX("_f2d"), f_nofpregargs|f_resultinintregs); #ifdef TARGET_SOFTFP_SUPPORT_INCLUDES_REVERSE_OPS sim.drsb = floating_function(2,te_double,te_double,te_double,TARGET_PREFIX("_drsb"), 0); sim.drdiv = floating_function(2,te_double,te_double,te_double,TARGET_PREFIX("_drdiv"), 0); sim.frsb = floating_function(2,te_float,te_int,te_int,TARGET_PREFIX("_frsb"), 0); sim.frdiv = floating_function(2,te_float,te_int,te_int,TARGET_PREFIX("_frdiv"), 0); #endif sim.llnot = ll_function(1, te_llint, te_llint, NULL, TARGET_PREFIX("_ll_not"), 0); sim.llneg = ll_function(1, te_llint, te_llint, NULL, TARGET_PREFIX("_ll_neg"), 0); sim.lladd = ll_function(2, te_llint, te_llint, te_llint, TARGET_PREFIX("_ll_add"), COMMBIT); sim.llrsb = ll_function(2, te_llint, te_llint, te_llint, TARGET_PREFIX("_ll_rsb"), 0); sim.llsub = ll_function(2, te_llint, te_llint, te_llint, TARGET_PREFIX("_ll_sub"), 0); sim.llmul = ll_function(2, te_llint, te_llint, te_llint, TARGET_PREFIX("_ll_mul"), COMMBIT); sim.llurdv = ll_function(2, te_llint, te_llint, te_llint, TARGET_PREFIX("_ll_urdv"), 0); sim.lludiv = ll_function(2, te_llint, te_llint, te_llint, TARGET_PREFIX("_ll_udiv"), 0); sim.llsrdv = ll_function(2, te_llint, te_llint, te_llint, TARGET_PREFIX("_ll_srdv"), 0); sim.llsdiv = ll_function(2, te_llint, te_llint, te_llint, TARGET_PREFIX("_ll_sdiv"), 0); sim.llurrem = ll_function(2, te_llint, te_llint, te_llint, TARGET_PREFIX("_ll_urrem"), 0); sim.llurem = ll_function(2, te_llint, te_llint, te_llint, TARGET_PREFIX("_ll_urem"), 0); sim.llsrrem = ll_function(2, te_llint, te_llint, te_llint, TARGET_PREFIX("_ll_srrem"), 0); sim.llsrem = ll_function(2, te_llint, te_llint, te_llint, TARGET_PREFIX("_ll_srem"), 0); sim.lland = ll_function(2, te_llint, te_llint, te_llint, TARGET_PREFIX("_ll_and"), COMMBIT); sim.llor = ll_function(2, te_llint, te_llint, te_llint, TARGET_PREFIX("_ll_or"), COMMBIT); sim.lleor = ll_function(2, te_llint, te_llint, te_llint, TARGET_PREFIX("_ll_eor"), COMMBIT); sim.llshiftl = ll_function(2, te_llint, te_llint, te_uint, TARGET_PREFIX("_ll_shift_l"), 0); sim.llushiftr = ll_function(2, te_llint, te_llint, te_uint, TARGET_PREFIX("_ll_ushift_r"), 0); sim.llsshiftr = ll_function(2, te_llint, te_llint, te_uint, TARGET_PREFIX("_ll_sshift_r"), 0); if (resultinflags) { sim.llcmpeq = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_cmpeq"), f_resultinflags + Q_EQ); sim.llcmpne = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_cmpeq"), f_resultinflags + Q_NE); sim.llucmpgt = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_cmpeq"), f_resultinflags + Q_HI); sim.llucmpge = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_cmpeq"), f_resultinflags + Q_HS); sim.llucmplt = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_cmpeq"), f_resultinflags + Q_LO); sim.llucmple = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_cmpeq"), f_resultinflags + Q_LS); sim.llscmpgt = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_scmple"), f_resultinflags + Q_LT); sim.llscmpge = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_scmpge"), f_resultinflags + Q_GE); sim.llscmplt = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_scmpge"), f_resultinflags + Q_LT); sim.llscmple = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_scmple"), f_resultinflags + Q_GE); } else { sim.llcmpeq = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_cmpeq"), 0); sim.llcmpne = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_cmpne"), 0); sim.llucmpgt = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_ucmpgt"), 0); sim.llucmpge = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_ucmpge"), 0); sim.llucmplt = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_ucmplt"), 0); sim.llucmple = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_ucmple"), 0); sim.llscmpgt = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_scmpgt"), 0); sim.llscmpge = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_scmpge"), 0); sim.llscmplt = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_scmplt"), 0); sim.llscmple = ll_function(2, te_int, te_llint, te_llint, TARGET_PREFIX("_ll_scmple"), 0); } sim.llfroml = ll_function(1, te_llint, te_lint, NULL, TARGET_PREFIX("_ll_from_l"), 0); sim.llfromu = ll_function(1, te_llint, te_ulint, NULL, TARGET_PREFIX("_ll_from_u"), 0); sim.llsfromd = ll_function(1, te_llint, te_double, NULL, TARGET_PREFIX("_ll_sfrom_d"), f_nofpregargs); sim.llsfromf = ll_function(1, te_llint, te_float, NULL, TARGET_PREFIX("_ll_sfrom_f"), f_nofpregargs); sim.llufromd = ll_function(1, te_ullint, te_double, NULL, TARGET_PREFIX("_ll_ufrom_d"), f_nofpregargs); sim.llufromf = ll_function(1, te_ullint, te_float, NULL, TARGET_PREFIX("_ll_ufrom_f"), f_nofpregargs); sim.lltol = ll_function(1, te_lint, te_llint, NULL, TARGET_PREFIX("_ll_to_l"), 0); sim.llstod = ll_function(1, te_double, te_llint, NULL, TARGET_PREFIX("_ll_sto_d"), f_resultinintregs); sim.llstof = ll_function(1, te_float, te_llint, NULL, TARGET_PREFIX("_ll_sto_f"), f_resultinintregs); sim.llutod = ll_function(1, te_double, te_ullint, NULL, TARGET_PREFIX("_ll_uto_d"), f_resultinintregs); sim.llutof = ll_function(1, te_float, te_ullint, NULL, TARGET_PREFIX("_ll_uto_f"), f_resultinintregs); #if defined(TARGET_IS_ARM) && !defined(OBSOLETE_ARM_NAMES) sim.readcheck1 = library_function("__rt_rd1chk", 1, 1, PUREBIT); sim.readcheck2 = library_function("__rt_rd2chk", 1, 1, PUREBIT); sim.readcheck4 = library_function("__rt_rd4chk", 1, 1, PUREBIT); sim.writecheck1 = library_function("__rt_wr1chk", 1, 1, PUREBIT); sim.writecheck2 = library_function("__rt_wr2chk", 1, 1, PUREBIT); sim.writecheck4 = library_function("__rt_wr4chk", 1, 1, PUREBIT); #else sim.readcheck1 = library_function("_rd1chk", 1, 1, PUREBIT); sim.readcheck2 = library_function("_rd2chk", 1, 1, PUREBIT); sim.readcheck4 = library_function("_rd4chk", 1, 1, PUREBIT); sim.writecheck1 = library_function("_wr1chk", 1, 1, PUREBIT); sim.writecheck2 = library_function("_wr2chk", 1, 1, PUREBIT); sim.writecheck4 = library_function("_wr4chk", 1, 1, PUREBIT); #endif sim.proc_entry = library_function("_proc_entry", 1, 1999, 0L); sim.proc_exit = library_function("_proc_exit", 1, 1999, 0L); /* _memcpyfn and _memsetfn are internals for (aligned) struct copy/clr */ sim.memcpyfn = library_function("_memcpy", 3, 3, 0L); sim.memsetfn = library_function("_memset", 3, 3, 0L); sim.realmemcpyfn = library_function("memcpy", 3, 3, 0L); sim.realmemsetfn = library_function("memset", 3, 3, 0L); sim.strcpysym = sym_insert_id("strcpy"); sim.strlensym = sym_insert_id("strlen"); mallocsym = sym_insert_id("malloc"); callocsym = sym_insert_id("calloc"); reallocsym = sym_insert_id("realloc"); sim.dpow = sym_insert_id("pow"); sim.dceil = sym_insert_id("ceil"); sim.dfloor = sym_insert_id("floor"); sim.dmod = sym_insert_id("fmod"); sim.dabs = sym_insert_id("fabs"); /* _word(nnn) is a specially-treated 'function' to put nnn in-line in the */ /* generated code. People may have views on a better name for it, esp. */ /* in view of machines with byte and halfword instructions! */ /* Introduced by ACN to help him with an 88000 library. */ sim.inserted_word = library_function("_word", 1, 1, 0L); add_toplevel_binder(exb_(arg1_(sim.inserted_word))); /* @@@? */ #ifdef TARGET_LINKER_OMITS_DOLLAR stackoverflow = sym_insert_id("__stack_overflow"); stack1overflow = sym_insert_id("__stack_overflow_1"); #else #if defined(TARGET_IS_ARM_OR_THUMB) && !defined(OBSOLETE_ARM_NAMES) stackoverflow = sym_insert_id(TARGET_PREFIX("__rt_stkovf_split_small")); stack1overflow = sym_insert_id(TARGET_PREFIX("__rt_stkovf_split_big")); #else stackoverflow = sym_insert_id("x$stack_overflow"); stack1overflow = sym_insert_id("x$stack_overflow_1"); #endif #endif datasegment = global_mk_binder(0, #ifdef UNIQUE_DATASEG_NAMES sym_insert_id(probably_unique_name('d')), #else #ifdef TARGET_LINKER_OMITS_DOLLAR sym_insert_id("__dataseg"), #else sym_insert_id("x$dataseg"), #endif #endif bitofstg_(s_static), te_void); codesegment = global_mk_binder(0, #ifdef UNIQUE_DATASEG_NAMES sym_insert_id(probably_unique_name('c')), #else #ifdef TARGET_LINKER_OMITS_DOLLAR sym_insert_id("__codeseg"), #else sym_insert_id("x$codeseg"), #endif #endif bitofstg_(s_static), te_void); #ifdef TARGET_HAS_BSS bsssegment = global_mk_binder(0, #ifdef UNIQUE_DATASEG_NAMES sym_insert_id(probably_unique_name('z')), #else #ifdef TARGET_LINKER_OMITS_DOLLAR sym_insert_id("_bssseg"), #else sym_insert_id("x$bssseg"), #endif #endif bitofstg_(s_static), te_void); #endif /* C++ only really */ ddtorsegment = global_mk_binder(0, #ifdef UNIQUE_DATASEG_NAMES sym_insert_id(probably_unique_name('v')), #else #ifdef TARGET_LINKER_OMITS_DOLLAR sym_insert_id("_ddtorvec"), #else sym_insert_id("x$ddtorvec"), #endif #endif bitofstg_(s_static), te_void); constdatasegment = global_mk_binder(0, #ifdef UNIQUE_DATASEG_NAMES sym_insert_id(probably_unique_name('q')), #else #ifdef TARGET_LINKER_OMITS_DOLLAR sym_insert_id("_constdata"), #else sym_insert_id("x$constdata"), #endif #endif bitofstg_(s_static)|u_constdata, te_void); extablesegment = global_mk_binder(0, #ifdef UNIQUE_DATASEG_NAMES sym_insert_id(probably_unique_name('t')), #else #ifdef TARGET_LINKER_OMITS_DOLLAR sym_insert_id("_extable"), #else sym_insert_id("x$extable"), #endif #endif bitofstg_(s_static), te_void); exhandlersegment = global_mk_binder(0, #ifdef UNIQUE_DATASEG_NAMES sym_insert_id(probably_unique_name('h')), #else #ifdef TARGET_LINKER_OMITS_DOLLAR sym_insert_id("_exhandler"), #else sym_insert_id("x$exhandler"), #endif #endif bitofstg_(s_static), te_void); mainsym = sym_insert_id("main"); setjmpsym = sym_insert_id("setjmp"); assertsym = sym_insert_id("___assert"); /* AM: hmm, is the name '___assert right in that users might get to see */ /* it if (say) a semicolon is omitted (check macro which use) and */ /* query the next line which would mean ___assert without () fn call */ /* would not get reported, or be done confusingly. Probably OK. */ implicit_decl(assertsym, 1); /* forge an 'extern int ___assert()' */ first_arg_sym = sym_insert_id("___first_arg"); last_arg_sym = sym_insert_id("___last_arg"); libentrypoint = sym_insert_id("__main"); #ifdef TARGET_LINKER_OMITS_DOLLAR countroutine = sym_insert_id("__mcount");/*for Unix, x$ goes*/ #else countroutine = sym_insert_id("x$mcount");/*for Unix, x$ goes*/ #endif count1routine = sym_insert_id("_count1"); #ifdef RANGECHECK_SUPPORTED #ifdef PASCAL /*ECN*/ sim.abcfault = sym_insert_id("_range"); sim.valfault = sym_insert_id("_badvalue"); #else sim.abcfault = sym_insert_id("__range"); /* BSD F77 library name */ # ifdef TARGET_LINKER_OMITS_DOLLAR sim.valfault = sym_insert_id("__badvalue"); # else sim.valfault = sym_insert_id("x$badvalue"); #endif #endif #endif traproutine = sym_insert_id("__syscall"); targeterrno = sym_insert_id("errno"); if (LanguageIsCPlusPlus) builtin_init_cpp(); else { te_boolean = te_int; te_wchar = initprimtype_(wchar_typespec); te_stringchar = te_char; te_wstringchar = te_wchar; #ifdef EXTENSION_UNSIGNED_STRINGS te_ustringchar = initprimtype_(bitoftype_(s_unsigned)|bitoftype_(s_char)); #endif } lit_false = globalize_integer(te_boolean, NO); lit_true = globalize_integer(te_boolean, YES); lit_zero = globalize_integer(te_int, 0); lit_one = globalize_integer(te_int, 1); } /* end of builtin.c */
stardot/ncc
mip/bind.c
<reponame>stardot/ncc /* * bind.c: various binding and lexing routines for C compiler * Copyright (C) Codemist Ltd., 1987-1992. * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Advanced RISC Machines Limited, 1991-1992. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 55 * Checkin $Date$ * Revising $Author$ */ /* AM memo: @@@ the use of assert(0) in the development of PASCAL is */ /* untidy but only temporary. */ /* #define DEBUG_TENTATIVE_DEFS 1 -- BUT ONLY during development */ /* AM Dec-90: the BSS code was broken in several interesting ways. */ /* Mend it, and move PCC mode nearer to being ANSI code with only */ /* local differences. u_tentative is now dead. */ /* BSS is now merged with tentatives both in ansi and pcc mode. */ /* AM Jul-87: experiment with memo-ising globalize_typeexpr(). */ /* exports globalize_int(), globalize_typeexpr() */ #ifndef _BIND_H #include <stddef.h> /* for offsetof() */ #include <string.h> #include <ctype.h> #include "globals.h" #include "defs.h" #include "aetree.h" #include "util.h" /* for padstrlen()... */ #include "codebuf.h" /* for padstatic()... */ #include "cgdefs.h" /* @@@ just for GAP */ #include "bind.h" #include "builtin.h" #include "lex.h" /* for curlex... */ #include "sem.h" /* for prunetype, equivtype... */ #include "store.h" #include "vargen.h" /* for initstaticvar()... */ #include "xrefs.h" /* for LIT_LABEL */ #include "errors.h" #include "aeops.h" /* for C-only compilers... */ #define merge_default_arguments(a,b) 0 #define check_access(a,b) (void)0 #define nullbinder(cl) 0 #define set_linkage(b,l,m) (void)0 #define hiddenmembername(a,b) 0 #define implicit_decl_cpp(a) ((Binder*)0) #endif int accessOK; #include "dump.h" #ifdef PASCAL /* for production qualify compilers prefer syserr() over assert(). */ # include <assert.h> #endif static int gensymline, gensymgen; /* For generating unique syms */ static Symstr *(*hashvec)[BIND_HASHSIZE]; /* Symbol table buckets */ const char *sym_name_table[s_NUMSYMS]; /* translation back to strings */ #define GENSYMV_SEGSIZE 256 #define GENSYMV_MAXSEGS 256 static Symstr ***gensymv; static uint32 ngensym, gensymlimit; #define GLOBBINDV_SEGSIZE 256 #define GLOBBINDV_MAXSEGS 256 static Binder ***globbindv; static uint32 nglobbind, globbindlimit; #define GLOBTAGV_SEGSIZE 256 #define GLOBTAGV_MAXSEGS 256 static TagBinder ***globtagv; static uint32 nglobtag, globtaglimit; #define NO_CHAIN 256 #ifdef PASCAL /* the following parameterisation allows PASCAL systems to use case- */ /* insensitive name matching while preserving the original case. */ #define lang_hashofchar(x) safe_tolower(x) static int lang_namecmp(char *s, char *t) { for (;;) { if (safe_tolower(*s) != safe_tolower(*t)) return 1; if (*s == 0) return 0; s++, t++; } } #else # define lang_hashofchar(x) (x) # define lang_namecmp(a, b) strcmp(a, b) #endif #ifdef CALLABLE_COMPILER #include "dbg_hdr.h" #include "dbg_hl.h" #endif Symstr *sym_lookup(char const *name, int glo) { int32 wsize; unsigned32 hash, temp; char const *s; Symstr *next, **lvptr = NULL; /* * 'glo' == SYM_LOCAL => allocate in Binder store * == SYM_GLOBAL => allocate in Global store * glo' & NO_CHAIN => don't chain to symtab buckets */ if (glo & NO_CHAIN) glo &= ~NO_CHAIN; else { #ifdef CALLABLE_COMPILER if ((next = dbg_findhash(name)) != NULL) return next; #endif hash = 1; for (s = name; *s != 0; ++s) { temp = just32bits_(hash << 7); hash = ((hash >> 25)^(temp >> 1)^(temp >> 4) ^ lang_hashofchar(*s)) & 0x7fffffff; } lvptr = &(*hashvec)[hash % BIND_HASHSIZE]; while ((next = *lvptr) != NULL) { if (lang_namecmp(symname_(next), name) == 0) return(next); lvptr = &symchain_(next); } } #ifdef CALLABLE_COMPILER wsize = offsetof(Symstr, symname[0]) + padstrlen(strlen(name)+1); #else wsize = offsetof(Symstr, symname[0]) + padstrlen(strlen(name)); #endif next = glo != SYM_LOCAL ? (Symstr *) GlobAlloc(SU_Sym, wsize) : (Symstr *) BindAlloc(wsize); memclr(next, (size_t)wsize); if (lvptr != NULL) { *lvptr = next; symchain_(next) = NULL; } else { symchain_(next) = next; /* non-hashed: see isgensym(). */ if (glo != SYM_LOCAL && (dump_state & DS_Dump)) { uint32 segno = ngensym / GENSYMV_SEGSIZE, segix = ngensym % GENSYMV_SEGSIZE; if (ngensym >= gensymlimit) { if (GENSYMV_MAXSEGS <= segno) syserr("Too many gensyms to dump"); gensymv[segno] = (Symstr **)GlobAlloc(SU_Other, sizeof(Symstr *) * GENSYMV_SEGSIZE); gensymlimit += GENSYMV_SEGSIZE; } gensymv[segno][segix] = next; ngensym++; } } symtype_(next) = s_identifier; bind_global_(next) = NULL; symlab_(next) = NULL; next->symtag = NULL; symext_(next) = NULL; symfold_(next) = NULL; #ifdef CALLABLE_COMPILER next->symname[0] = strlen(name); #endif strcpy(symname_(next), name); return(next); } Symstr *sym_insert(char const *name, AEop type) { Symstr *p = (sym_lookup)(name, SYM_GLOBAL); symtype_(p) = type; return(p); } Symstr *sym_insert_id(char const *name) { return (sym_lookup)(name, SYM_GLOBAL); } static void check_extern(Symstr *s) { Symstr *p; /* First an option to check ansi conformance ... */ /* (The return below ensures only one is executed. Because of room for */ /* the back pointer only one can be active at once, unfortunately). */ if (feature & FEATURE_6CHARMONOCASE) { char ch, v[6+1]; int n = 0; while ((ch = symname_(s)[n]) != 0 && n < 6) v[n++] = safe_tolower(ch); v[n] = 0; p = sym_lookup(v, SYM_GLOBAL); if (symfold_(p) == 0) symfold_(p) = s; if (symfold_(p) != s) cc_warn(bind_warn_extern_clash, s, symfold_(p)); return; } /* ... now a compiled-in form for things like 370 linkers */ #ifdef TARGET_HAS_LINKER_NAME_LIMIT /* e.g. 370 */ { char ch, v[LINKER_NAME_MAX+1]; int n = 0; while ((ch = symname_(s)[n]) != 0 && n < LINKER_NAME_MAX) v[n++] = LINKER_NAME_MONOCASE ? safe_tolower(ch) : ch; v[n] = 0; p = sym_lookup(v, SYM_GLOBAL); if (symfold_(p) == 0) symfold_(p) = s; if (symfold_(p) != s) cc_err(LINKER_NAME_MONOCASE ? bind_err_extern_clash_monocase, : bind_err_extern_clash, s, symfold_(p), (long)LINKER_NAME_MAX); } #endif /* TARGET_HAS_LINKER_NAME_LIMIT */ } Symstr *gensymval(bool glo) { /* Generates a new symbol with a unique name. */ /* (Not quite unique in that line 1 may occur in 2 files, but */ /* we RELY on NO_CHAIN below to treat as unique). */ char name[30]; #ifdef TARGET_IS_CLIPPER /* the next line is a hack to ensure these gensyms are assemblable */ /* Note that this HOPEs that the user has no names Intsym_nnn */ sprintf(name, "Intsym_%d", ++gensymgen); #else if (gensymline != curlex.fl.l) gensymline = curlex.fl.l, gensymgen = 1; else ++gensymgen; sprintf(name, "<Anon%d_at_line_%d>", gensymgen, gensymline); #endif return sym_lookup(name, (glo ? SYM_GLOBAL+NO_CHAIN : SYM_LOCAL+NO_CHAIN)); } Symstr *gensymvalwithname(bool glo, char const *name) { return sym_lookup(name, (glo ? SYM_GLOBAL+NO_CHAIN : SYM_LOCAL+NO_CHAIN)); } bool isgensym(Symstr const *sym) /* actually is-unchained-gensym! */ { return symchain_(sym) == sym; } static Binder *RecordGlobalBinder(Binder *p) { if (dump_state & DS_Dump) { uint32 segno = nglobbind / GLOBBINDV_SEGSIZE, segix = nglobbind % GLOBBINDV_SEGSIZE; if (nglobbind >= globbindlimit) { if (GLOBBINDV_MAXSEGS <= segno) syserr("Too many global binders to dump"); globbindv[segno] = (Binder **)GlobAlloc(SU_Other, sizeof(Binder *) * GLOBBINDV_SEGSIZE); globbindlimit += GLOBBINDV_SEGSIZE; } globbindv[segno][segix] = p; nglobbind++; } return p; } Binder *global_mk_binder(Binder *b, Symstr *c, SET_BITMAP d, TypeExpr *e) { int32 size = d & (bitofstg_(s_virtual)|b_globalregvar|bitofstg_(s_auto)) ? sizeof(Binder) : SIZEOF_NONAUTO_BINDER; Binder *p = (Binder*) GlobAlloc(SU_Bind, size); /* * This consistency check is removed so that front-ends for languages * other than C can create binders for auto variables in global store. >>> if (d & bitofstg_(s_auto)) syserr("Odd global binder(%lx)", (long)d); <<< */ if (d & bitofstg_(s_extern)) check_extern(c); h0_(p) = s_binder; bindcdr_(p)=b; bindsym_(p)=c; attributes_(p) = A_GLOBALSTORE; bindstg_(p) = d; bindtype_(p) = e; bindaddr_(p) = 0; /* soon BINDADDR_UNSET - remember 'datasegment' */ bindparent_(p) = 0; /* local_scope->class_tag? BEWARE member template */ bindconst_(p) = 0; bindinline_(p) = 0; bindscope_(p) = 0; bindactuals_(p) = 0; bindformals_(p) = 0; bindinstances_(p) = 0; bindtext_(p) = -1; bindftlist_(p) = 0; #ifdef TARGET_HAS_DEBUGGER binddbg_(p) = 0; #endif #ifdef PASCAL /*ECN*/ p->bindlevel = 0; p->synflags = 0; #endif if (size == sizeof(Binder)) bindxx_(p) = GAP; if (d & bitofstg_(s_auto)) bindmcrep_(p) = NOMCREPCACHE; return RecordGlobalBinder(p); } Binder *mk_binder(Symstr *c, SET_BITMAP d, TypeExpr *e) { Binder *p = (Binder*) BindAlloc( (d & (bitofstg_(s_auto)|bitofstg_(s_virtual))) ? sizeof(Binder) : SIZEOF_NONAUTO_BINDER); if (d & bitofstg_(s_extern)) check_extern(c); h0_(p) = s_binder; bindcdr_(p)=0; bindsym_(p)=c; attributes_(p) = A_LOCALSTORE; bindstg_(p) = d; bindtype_(p) = e; bindaddr_(p) = BINDADDR_UNSET; bindparent_(p) = 0; /* local_scope->class_tag?, BEWARE member template */ bindconst_(p) = 0; bindinline_(p) = 0; #ifdef TARGET_HAS_DEBUGGER binddbg_(p) = 0; #endif #ifdef PASCAL /*ECN*/ p->bindlevel = 0; p->synflags = 0; #endif bindscope_(p) = 0; bindactuals_(p) = 0; bindformals_(p) = 0; bindinstances_(p) = 0; bindtext_(p) = -1; bindftlist_(p) = 0; if (d & bitofstg_(s_auto)) { bindxx_(p) = GAP; bindmcrep_(p) = NOMCREPCACHE; } return p; } TagBinder *global_mk_tagbinder(TagBinder *b, Symstr *c, AEop d) { SET_BITMAP bits = bitoftype_(d); TagBinder *p = (TagBinder*) GlobAlloc(SU_Bind, sizeof(TagBinder)); h0_(p) = s_tagbind; tagbindcdr_(p)=b; tagbindsym_(p)=c; attributes_(p) = A_GLOBALSTORE; tagbindbits_(p) = bits; tagbindmems_(p) = 0; tagbindtype_(p) = globalize_typeexpr(primtype2_(bits, p)); if (LanguageIsCPlusPlus) { p->friends = NULL; p->tagparent = current_member_scope(); } else p->tagparent = NULL; taginstances_(p) = NULL; tagscope_(p) = NULL; tagformals_(p) = NULL; tagactuals_(p) = NULL; tagtext_(p) = -1; tagprimary_(p) = NULL; tagmemfns_(p) = NULL; #ifdef TARGET_HAS_DEBUGGER tagbinddbg_(p) = 0; #endif p->typedefname = NULL; if (dump_state & DS_Dump) { uint32 segno = nglobtag / GLOBTAGV_SEGSIZE, segix = nglobtag % GLOBTAGV_SEGSIZE; if (nglobtag >= globtaglimit) { if (GLOBTAGV_MAXSEGS <= segno) syserr("Too many global tagbinders to dump"); globtagv[segno] = (TagBinder **)GlobAlloc(SU_Other, sizeof(TagBinder *) * GLOBTAGV_SEGSIZE); globtaglimit += GLOBTAGV_SEGSIZE; } globtagv[segno][segix] = p; nglobtag++; } return p; } TagBinder *mk_tagbinder(Symstr *c, AEop d) { SET_BITMAP bits = bitoftype_(d); TagBinder *p = (TagBinder*) SynAlloc(sizeof(TagBinder)); h0_(p) = s_tagbind; tagbindcdr_(p)=0; tagbindsym_(p)=c; attributes_(p) = A_LOCALSTORE; tagbindbits_(p) = bits; tagbindmems_(p) = 0; tagbindtype_(p) = primtype2_(bits, p); if (LanguageIsCPlusPlus) { p->friends = NULL; p->tagparent = current_member_scope(); } else p->tagparent = NULL; taginstances_(p) = NULL; tagscope_(p) = NULL; tagformals_(p) = NULL; tagactuals_(p) = NULL; tagtext_(p) = -1; tagprimary_(p) = NULL; tagmemfns_(p) = NULL; #ifdef TARGET_HAS_DEBUGGER tagbinddbg_(p) = 0; #endif p->typedefname = NULL; return p; } extern LabBind *mk_labbind(LabBind *b, Symstr *c) { LabBind *p = (LabBind*) SynAlloc(sizeof(LabBind)); p->labcdr = b; p->labsym = c; p->labinternlab = 0; p->labuses = 0; p->labu.ref = 0; return p; } /* Binding: There are 5 overloading classes, of which 3 (labels, vars, struct tags) are bindings in the traditional sense. All code concerning binding and unbinding is in this file. Access routes are the procedures below: Labels: label_xxx; Vars: instate_declaration, findbinding. Tags: instate_tagbinding, findtagbinding. Scopes: push_scope, pop_scope, clear_stacked_scopes. Note that typedef names share the same binding space with variables. Labels have function scope and function scopes do not nest. Function scopes and the global (file) scope for variables and tags is implemented using a hash table of Symstrs with separate Binder, TagBinder and LabBind pointer fields. Local scopes for Binders and TagBinders are implemented using the 'deep binding' strategy, as are C++ class scopes. For each scope there is a list of Binders/ TagBinders which can be searched for the matching Symstr. If the search fails in each local scope then the global binding (if any) is found in O(1) time. In a C++ class scope, class members, class-scope Binders and class-scope TagBinders exist on a single list, discrimiated by the leading AEop field of each entry (s_binder, s_tagbind, s_member). APOLOGY: This assumes that Binder, TagBinder and ClassMember all begin: {AEop sort; SelfType *cdr; Symstr *sv; ...} so we can pun. It can be made cleaner with a common initial structure and casts, but this spreads the filth over several modules rather than localising it here in bind.c. NOTE: binding information persists only for the duration of parsing - consequently it makes sense for the parse tree to contain references to binding records rather than the main symbol table entries. Toplevel binding are allocated in 'global' store which is not reclaimed after each top-level phrase. NOTE: This also means that local Binders/TagBinders may not be inspected during/after register allocation (which reuses syntax store). */ /* AM: create a globalized Binder. For use in rd_decl and implicit_decl. Beware: its components still need globalizing. Possible optimisation: overwrite if already there on re-definition. Precondition to call: loc must not represent a local binding. */ #define topbind2(sv, stg, typ) \ (bind_global_(sv) = topbindingchain = \ global_mk_binder(topbindingchain, sv, stg, typ)) static Binder *topbindingchain; /* vars */ static TagBinder *toptagbindchain; /* tags */ static LabBind *labelchain; /* labels */ /* FW: 01-Apr-96 definition of Scope published in bind.h */ static Scope *local_scope, *freeScopes; static bool tag_found_in_local_scope; static bool tpara_found_in_enclosing_scope; /* used to avoid searching twice in instate_xxx... */ static int scope_level; #ifdef CALLABLE_COMPILER void set_local_scope(Scope *scope) { local_scope = scope; } #endif static int push_init_scope(TagBinder *class_tag, ScopeSaver init, ScopeSort kind) { Scope *scope = freeScopes; if (scope != NULL) freeScopes = freeScopes->prev; else scope = (Scope *) GlobAlloc(SU_Bind, sizeof(Scope)); if (debugging(DEBUG_BIND)) cc_msg("push_scope($b) -> %d\n", class_tag, scope_level); scope->scopemems = init; scope->prev = local_scope; local_scope = scope; scope->class_tag = class_tag; scope->kind = kind; return scope_level++; } int push_scope(TagBinder *class_tag, ScopeSort kind) { return push_init_scope(class_tag, 0, kind); } int push_var_scope(ScopeSaver init, ScopeSort kind) { return push_init_scope(0, init, kind); } /* The pop_scope routines return values giving the (last) popped */ /* scope so this can be restored for argument scopes in fn defs. */ static ScopeSaver pop_scope_1(int level, bool check_unrefd) { Scope *scope = local_scope; ScopeSaver poppling = 0; Binder *p; if (level > scope_level) syserr("pop_scope: level=%d >= scope_level=%d", level, scope_level); while (scope_level > level) { if (debugging(DEBUG_BIND)) cc_msg("pop_scope(%d)\n", scope_level); if (scope == NULL) syserr("pop_scope: NULL scope pointer"); poppling = scope->scopemems; /* empty for class scopes */ if (scope->class_tag == NULL && check_unrefd) { /* Check for unreferenced names in local scopes */ Symstr *sv; for (p = poppling; p != 0; p = bindcdr_(p)) { if (h0_(p) != s_binder || h0_(bindtype_(p)) == t_ovld) continue; sv = bindsym_(p); /* do a bit more in the next line for used/set */ /* suppress warning for gensym'd vars, which patch up user errs */ if (!(binduses_(p) & u_referenced) && !isgensym(sv) && !(bindstg_(p) & b_pseudonym)) { if (sv == thissym) { if (!(suppress & D_UNUSEDTHIS)) cc_warn(bind_warn_unused_this_in_member); } else if (bindstg_(p) & bitofstg_(s_typedef)) cc_warn(istypevar(bindtype_(p)) ? bind_warn_typename_not_used : bind_warn_typedef_not_used, p); else if (bindstg_(p) & b_fnconst) cc_warn(bind_warn_function_not_used, p); else cc_warn(bind_warn_variable_not_used, p); } } } else /* The next line fixes nasties like: */ /* "struct d { struct d { int a; } c; } x;" by inhibiting the */ /* outer setting and so recovering to "struct d { int a; }. */ { TagBinder *b = scope->class_tag; scope->class_tag = NULL; /* @@@ kill... */ /* This is only for C: C++ has already closed the class (in */ /* cpp_end_strdecl). Hence no need to do this for the core class*/ if (b != NULL && (tagbindbits_(b) & TB_BEINGDEFD)) tagbindbits_(b) = (tagbindbits_(b) & ~TB_BEINGDEFD) | TB_DEFD; } local_scope = scope->prev; scope->prev = freeScopes; freeScopes = scope; scope = local_scope; --scope_level; } return poppling; } ScopeSaver pop_scope(int level) { return pop_scope_1(level, YES); } ScopeSaver pop_scope_no_check(int level) { return pop_scope_1(level, NO); } static Scope *set_local_block_scope(void) { Scope *scope0 = local_scope; if (!LanguageIsCPlusPlus) { Scope *scope; for (scope = scope0; scope != 0; scope = scope->prev) if (scope->class_tag == 0) break; /* Intentionally, if local_scope is 0, instate_declaration_1() */ /* will syserr(). Note: this is the ONLY caller... */ local_scope = scope; } return scope0; } static TagBinder *findtag_in_members(Symstr *sv, ClassMember *ll) { TagBinder *l = (TagBinder *)ll; for (; l != NULL; l = tagbindcdr_(l)) { if (debugging(DEBUG_BIND)) cc_msg("findtag try $r %lx\n", memsv_(l), (long)attributes_(l)); if (h0_(l) == s_tagbind && (h0_(sv)==s_tagbind && l == (TagBinder *)sv || tagbindsym_(l)==sv)) break; /* this happens only in template arg scope where the tagbinders were deliberately lost. */ if (tagbindsym_(l) == sv && isclasstype_(princtype(tagbindtype_(l)))) { Expr *deftexpr = bindconst_((ClassMember *)l); TagBinder *res = typespectagbind_(princtype(tagbindtype_(l))); if (local_scope->class_tag != NULL && !(tagbindbits_(local_scope->class_tag) & TB_TEMPLATE) && deftexpr != NULL) { if (!isclasstype_(princtype(type_(deftexpr)))) syserr("default class type expected"); res = typespectagbind_(princtype(type_(deftexpr))); } return res; } } return l; } /* @@@ no access control? */ TagBinder *findtagbinding(Symstr *sv, TagBinder *cl, int fbflags) { Scope *scope; bool first = 1; tag_found_in_local_scope = 0; tpara_found_in_enclosing_scope = NO; if (!LanguageIsCPlusPlus && cl != NULL) syserr("strange findtagbinding for C"); /* @@@ note that we don't inherit classes via bases! */ if (cl != NULL) { if (tagbindbits_(cl) & TB_TEMPLATE) { Binder *b = tagformals_(cl); for (; b; b = bindcdr_(b)) if (bindsym_(b) == sv && istypevar(bindtype_(b))) { tpara_found_in_enclosing_scope = YES; break; } } return findtag_in_members(sv, tagbindmems_(core_class(cl))); } if (fbflags == ALLSCOPES) for (scope = local_scope; scope != NULL; scope = scope->prev) { ClassMember *l; TagBinder *b; if ((cl = scope->class_tag) != NULL) { if (LanguageIsCPlusPlus) l = tagbindmems_(core_class(cl)); else continue; /* C class scopes don't nest. */ } else l = scope->scopemems; if ((b = findtag_in_members(sv, l)) != 0) return (tag_found_in_local_scope = first, b); first = 0; } return tag_global_(sv); } /* routine finds both members and binders -- in C these can be checked */ /* to be consistent by caller. In C++ they are equivalent. */ /* find_scopemember finds ANY suitably named member, but will get */ /* the nearest in case of ambiguity. */ /* For anonymous unions it returns the whole union, not the element. */ static ClassMember *find_scopemember(Symstr *sv, ClassMember *p) { ClassMember *l; TagBinder *cl = NULL; for (l = p; l != NULL; l = memcdr_(l)) { if (debugging(DEBUG_BIND)) cc_msg("findscopemember try $r %lx\n", memsv_(l), (long)attributes_(l)); if ((h0_(l) == s_member || h0_(l) == s_binder) && memsv_(l) == sv) return l; } if (LanguageIsCPlusPlus && (local_scope->kind == Scope_TemplateArgs || ((cl = local_scope->class_tag) != NULL && tagbindbits_(cl) & TB_TEMPLATE))) { Scope *scope = local_scope; Binder *temp; for (; scope; scope = scope->prev) { if (scope->kind != Scope_TemplateArgs) continue; for (temp = scope->scopemems; temp; temp = bindcdr_(temp)) if (memsv_(temp) == sv) return temp; } } return 0; } static TagBinder *qualifyingBase; /* extra IN arg to path_to_member_1 */ static TagBinder *startScope; /* another one */ static Expr *path_to_member_1(ClassMember *member, TagBinder *tb, int flags, ClassMember *vbases, TagBinder *privately_deriving_class) { ClassMember *l; /* This can never happen C-only... */ if (qualifyingBase != 0 && (qualifyingBase == tb || core_class(qualifyingBase) == tb)) flags &= ~FB_NOTYET; if (!(flags & FB_NOTYET)) { if ((tagbindbits_(tb) & TB_DEFD) && !(tagbindbits_(tb) & TB_SIZECACHED)) { SET_BITMAP opaque = tagbindbits_(tb) & TB_OPAQUE; /* mometarily not opaque so we can look up mem fns */ tagbindbits_(tb) &= ~TB_OPAQUE; (void)sizeofclass(tb, NULL); tagbindbits_(tb) |= opaque; } for (l = tagbindmems_(tb); l != NULL; l = memcdr_(l)) { if (debugging(DEBUG_BIND)) cc_msg("see $r %lx in $c\n", memsv_(l), (long)attributes_(l), tb); if (h0_(member) == s_identifier) { Symstr *sv = (Symstr *)member; if (memsv_(l) != sv) continue; } else if (l != member) continue; /* The next line avoids spurious errors for class-within-class defn. */ /* (path_to_member() ignores s_tagbind's.) */ if (h0_(l) == s_tagbind) continue; if (startScope != NULL && core_class(startScope) != tb && h0_(l) == s_member && !derived_from(tb, core_class(startScope))) { cc_err(bind_err_cant_use_outer_member, tb, memsv_(l)); return (Expr*)implicit_decl(memsv_(l), 0); } curlex_member = l; /* this saves some searching and helps with */ /* diagnosing access faults. */ if (LanguageIsCPlusPlus) { if (memtype_(l) == ACCESSADJ) /* access decl */ { accessOK = 1; continue; } check_access(l, privately_deriving_class); } /* the following save store when searching for tyenames... */ if (flags & (FB_CLASSNAME|FB_TYPENAME|FB_FNBINDER)) return (Expr *)l; if (LanguageIsCPlusPlus) { if (h0_(l) == s_binder) { Binder *b = (Binder *)l; if (bindstg_(b) & b_pseudonym) b = realbinder_(b); if (!(flags & FB_FNBINDER) && /* BEWARE: a local memfn_a is static... */ ( (bindstg_(b) & b_memfna) || !(bindstg_(b) & (bitofstg_(s_static)|bitofstg_(s_typedef))) ) && /* overloaded fns can't be typedefs; use ovld-stg bit? */ /* match both generic and specific functions. */ (h0_(bindtype_(b)) == t_ovld || h0_(bindtype_(b)) == t_fnap) ) /* exprdotmemfn_() */ return mk_exprwdot(s_dot, bindtype_(b), nullbinder(bindparent_(b)), (IPtr)b); /* Otherwise: a typedef name, static member, enumerator */ /* or a function binder was requested via FB_FNBINDER. */ return (Expr *)b; } } /* Assert: h0_(l) == s_member, whether C or C++ */ if (tagbindbits_(tb) & TB_OPAQUE) cc_rerr(bind_rerr_mem_opaque, l); { int32 n = 0; if (membits_(l) != 0) { if (target_lsbitfirst) { int32 maxsize = MAXBITSIZE; if (int_islonglong_(typespecmap_(memtype_(l)))) maxsize = sizeof_longlong*8; n = (membits_(l)+memboff_(l)) % maxsize; if (n != 0) n = maxsize - n; } else n = memboff_(l); } return mk_exprbdot(s_dot, memtype_(l), nullbinder(tb), memwoff_(l), membits_(l), n); } } } if (LanguageIsCPlusPlus && (flags & FB_INHERIT)) return path_to_base_member(member, tb, flags, vbases, privately_deriving_class); else { IGNORE(vbases); IGNORE(privately_deriving_class); } return NULL; } Expr *path_to_member(ClassMember *member, TagBinder *b, int flags) { Expr *e; if (b == 0 || !isclasstagbinder_(b)) syserr("path_to_member of no or non-class tagbinder"); if (member == NULL) return NULL; if (debugging(DEBUG_BIND)) { Symstr *sv = h0_(member) == s_identifier ? (Symstr *)member : memsv_(member); cc_msg("path_to_member($r, $b, 0x%.3x) at $l\n", sv, b, flags); } if (LanguageIsCPlusPlus) { accessOK = 0; curlex_member = 0; { ClassMember *l = tagbindmems_(b); if (l != NULL && !(attributes_(l) & CB_CORE)) l = NULL; e = path_to_member_2(member, b, flags, l, NULL); } if (e != 0 && h0_(e) == s_invisible && !(flags & FB_KEEPI)) e = arg2_(e); } else e = path_to_member_1(member, b, flags, NULL, NULL); return e; } Expr *findpath(Symstr *sv, TagBinder *cl, int flags, TagBinder *inBase) { Scope *scope; Binder *b = NULL; ClassMember *member = (ClassMember *)sv; if ((qualifyingBase = inBase) != NULL) flags |= FB_NOTYET; if (cl != NULL) return path_to_member(member, cl, flags); for (scope = local_scope; scope != NULL; scope = scope->prev) if ((startScope = scope->class_tag) != NULL) break; for (scope = local_scope; scope != NULL; scope = scope->prev) { b = NULL; cl = scope->class_tag; if (cl != NULL && (flags & FB_CLASSES)) b = (Binder *)path_to_member(member, cl, flags); else if (cl == NULL && (flags & FB_LOCALS)) b = find_scopemember(sv, scope->scopemems); if ((flags & FB_THISSCOPE) || b != NULL && ( LanguageIsCPlusPlus && ((flags & FB_CLASSNAME) == 0 || h0_(b) == s_binder && (bindstg_(b) & bitofstg_(s_typedef)) && isclasstype_(princtype(bindtype_(b))) ) || !LanguageIsCPlusPlus && ((flags & FB_TYPENAME) == 0 || (cl == NULL) || h0_(b) == s_binder && (bindstg_(b) & bitofstg_(s_typedef)) ) )) break; } startScope = 0; /* The following code is extremely curious. It has the effect of looking up a base class name! And only if there is no curlex_scope. */ /* This ignores 'flags' -- even FB_GLOBAL */ return (Expr *)((scope != NULL) ? b : bind_global_(sv)); } Binder *findbinding(Symstr *sv, TagBinder *cl, int flags) { return (Binder *)findpath(sv, cl, flags | FB_FNBINDER, 0); } void add_toplevel_binder(Binder *b) { bind_global_(bindsym_(b)) = b; bindcdr_(b) = topbindingchain; topbindingchain = b; } static Binder **insertionpoint(Scope *scope) { /* Now we are supposedly about to ADD to a partially made scope. */ /* Hence we must have either a local scope or a TB_BEINGDEFD class. */ /* We need to worry about CB_CORE for partially made class scopes... */ TagBinder *cl = scope->class_tag; /* duplicate names must be seen first for local (auto) scopes since */ /* argument narrowing relies on it, similarly members must be placed */ /* in proper order (at least eventually): */ if (cl == 0) { if (/*scope->kind == Scope_TemplateArgs ||*/ scope->kind == Scope_TemplateDef) syserr("attempt to insert into read-only scope"); return &scope->scopemems; } else { ClassMember **q, *l; if (!(tagbindbits_(cl) & TB_BEINGDEFD)) syserr("adding to completed scope $c", cl); cl = core_class(cl); q = &tagbindmems_(cl); while ((l = *q) != NULL) q = &bindcdr_(l); return q; } } static void add_local_binder(Binder *b) { Scope *scope = local_scope; Binder **p = insertionpoint(scope); #if 0 /* only generics binders */ if (isfntype(bindtype_(b))) return; #endif if (debugging(DEBUG_BIND)) { cc_msg("add_local_binder($b) in scope %p\n", b, scope); if (debugging(DEBUG_TYPE)) cc_msg("princtype %ld\n", h0_(bindtype_(b))); } bindcdr_(b) = *p; *p = b; } static void add_local_tagbinder(TagBinder *b, bool implicit) /* Note that in C, class scopes don't nest; see also findtagbinding(). */ /* 'implicit' is set when we have a non-explicit declaration which is */ /* not a definition of a class tag, within another class or a formal */ /* parameter list. Lift to first unnamed scope. */ { Scope *scope = local_scope; if (implicit || !LanguageIsCPlusPlus) while (scope && (scope->class_tag != NULL || (LanguageIsCPlusPlus && (scope->kind == Scope_Args || scope->kind == Scope_TemplateDef || scope->kind == Scope_TemplateArgs)))) scope = scope->prev; if (scope == NULL) { if (!LanguageIsCPlusPlus) syserr("add_local_tagbinder"); tagbindcdr_(b) = toptagbindchain; tag_global_(tagbindsym_(b)) = toptagbindchain = b; } else { TagBinder **p = (TagBinder **)insertionpoint(scope); tagbindcdr_(b) = *p; *p = b; if (scope->kind == Scope_Args) cc_warn(bind_warn_new_tag_in_formals, b); } if (LanguageIsCPlusPlus) { /* local classes MUST have INTERNAL linkage... */ while (scope && (scope->class_tag != NULL || scope->kind == Scope_Args || scope->kind == Scope_TemplateArgs)) scope = scope->prev; if (scope != NULL) set_linkage((Binder *)b, A_NOLINKAGE, NULL); } } static void add_member(ClassMember *m) { Scope *scope = local_scope; ClassMember **p = insertionpoint(scope); if (debugging(DEBUG_BIND)) cc_msg("add_member($r) in scope %p\n", memsv_(m), scope); memcdr_(m) = *p; *p = m; } static ClassMember *instate_member_1(DeclRhsList *d, int bindflg) { ClassMember *m, *oldm; int32 bitsize; TypeExpr *t; bool implicit_typedef_exists = NO; Symstr *sv = d->declname; SET_BITMAP access = attribofstgacc_(d->declstg); /* note: other users of d->declstg should use killstgacc_(d->declstg). */ if (access==0) syserr("instate_member(access==0)"); oldm = m = (sv == NULL) ? NULL : find_scopemember(sv, tagbindmems_(local_scope->class_tag)); /* LDS: 29-Mar-95: Changed (O(N**2) performance reasons) from: */ /* findbinding(sv, local_scope->class_tag, INCLASSONLY); */ if (m != NULL) { if (bindstg_(m) & d->declstg & bitofstg_(s_typedef)) { if ((d->declstg & bitofstg_(s_typedef)) && (d->declstg & u_implicitdef)) return NULL; else if ((bindstg_(m) & bitofstg_(s_typedef)) && (bindstg_(m) & u_implicitdef)) /* supercede it... */ bindstg_(m) |= u_referenced; else syserr("instate_member_1"); } else if (bindstg_(m) & bitofstg_(s_typedef) && bindstg_(m) & u_implicitdef) implicit_typedef_exists = YES; else { if (istypevar(bindtype_(m))) cc_rerr(syn_rerr_temp_para_redefinition, m); else cc_rerr(syn_rerr_duplicate_member(m)); d->declname = gensymval(1); } } /* bindflg is set so that all structs are globalized except within fns. */ /* This includes structs declared in formal parameter lists whose scope */ /* is only the function. */ t = d->decltype; /*/* @@@ LDS 05-Oct-94: the first ! was missing - what is really meant? */ /* Do we still need to globalize for local classes?? */ if (!LanguageIsCPlusPlus && !(bindflg & (GLOBALSTG|TOPLEVEL))) { m = (ClassMember *)BindAlloc(SIZEOF_CLASSMEMBER); } else /* always allocate globally for C++ local class memfns. */ { m = (ClassMember *)GlobAlloc(SU_Bind, SIZEOF_CLASSMEMBER); RecordGlobalBinder(m); t = globalize_typeexpr(t); } /* We now evaluate a bitfield's size here, rather than later: by so */ /* doing, membits no longer tells us whether a member is a bitfield */ /* but this is only a consistency check since memtype & BITFIELD is */ /* what really distinguishes bitfields. */ bitsize = (declbits_(d) == NULL) ? 0 : evaluate(declbits_(d)); h0_(m) = s_member; memcdr_(m) = NULL; memsv_(m) = sv; /* 0 for padding (:0) bit fields */ memtype_(m) = t; memwoff_(m) = OFFSET_UNSET; memboff_(m) = 0; membits_(m) = (uint8)bitsize; attributes_(m) = access; bindstg_(m) = 0; /* b_member? */ bindparent_(m) = local_scope->class_tag; if (implicit_typedef_exists) { ClassMember *l = tagbindmems_(local_scope->class_tag); for (; l != NULL; l = memcdr_(l)) if (memcdr_(l) == oldm) break; if (l == NULL) syserr("lost in instate_member_1"); memcdr_(l) = m; memcdr_(m) = memcdr_(oldm); memcdr_(oldm) = NULL; add_member(oldm); } else add_member(m); return m; } /* struct/union/enum tag bindings ... */ TagBinder *instate_tagbinding(Symstr *sv, AEop s, TagDefSort defining, int bindflg, bool *newtag) { TagBinder *b; if (sv == 0) { sv = gensymval(1); defining = TD_ContentDef; } *newtag = NO; if (bindflg & TOPLEVEL) { b = tag_global_(sv); if (b == 0 || defining != TD_NotDef) { /* new tag or tag being defined... */ if (debugging(DEBUG_BIND)) cc_msg("top level struct $r@%p\n", sv, (VoidStar)b); if (b == 0) /* introduction of new tag */ { *newtag = YES; tag_global_(sv) = toptagbindchain = b = global_mk_tagbinder(toptagbindchain,sv,s); if (tagbindparent_(b) != 0 && !(bindflg & TEMPLATE)) syserr("instate_tagbinding($b)", b); if (!LanguageIsCPlusPlus && defining != TD_NotDef && local_scope != 0 && !isgensym(sv) && !(suppress & D_FUTURE)) cc_warn(bind_warn_cpp_scope_differ, b); } else if (defining != TD_Decl && (tagbindbits_(b) & (TB_DEFD|TB_BEINGDEFD))) cc_err(bind_err_duplicate_tag, tagbindsort(b),b); } } else { b = findtagbinding(sv, 0, ALLSCOPES); if (b == 0 || defining != TD_NotDef) { /* new tag or tag being defined... */ bool implicit = 0; if (debugging(DEBUG_BIND)) cc_msg("local struct $r@%p\n", sv, (VoidStar)b); if (LanguageIsCPlusPlus && tpara_found_in_enclosing_scope) { cc_err(bind_err_template_tpara_redeclared, sv); b = NULL; } if (b != 0 && tag_found_in_local_scope && (((tagbindbits_(b) & TB_DEFD) && defining != TD_Decl) || /* re-definition */ (tagbindbits_(b) & TB_BEINGDEFD))) { cc_err(bind_err_duplicate_tag, tagbindsort(b), b); b = 0; } if (b == 0 || defining == TD_ContentDef && !tag_found_in_local_scope) { *newtag = YES; /* bindflg & GLOBALSTG refers to tags in formals: these need careful */ /* treatment in that they are somewhat visible. e.g. equivtype needs */ /* to see "f(struct a { int b,c;})" differing from g of similar type. */ /* For C++, always allocate even local structs in global store since */ /* they may have member fns. */ b = (bindflg & GLOBALSTG) || LanguageIsCPlusPlus ? global_mk_tagbinder(0, sv, s) : mk_tagbinder(sv, s); if (bindflg & TEMPLATE) tagbindbits_(b) |= TB_TEMPLATE; /* The next lines avoids 'true' scoping as a hack to make B=B in: */ /* class A { class B *p; }; class B { whatever }; */ /* Also in class A {friend class B; }; class B { whatever }; */ if (defining == TD_NotDef && !(bindflg & TEMPLATE)) implicit = 1; else if (!LanguageIsCPlusPlus) /* @@@ the following can't be right for C compilers: current_member_scope() is always NULL */ { if (!isgensym(sv) && current_member_scope() != 0 && !(suppress & D_FUTURE)) cc_warn(bind_warn_cpp_scope_differ, b); implicit = 1; } if (implicit) b->tagparent = 0; add_local_tagbinder(b, implicit); } } } if ((tagbindbits_(b) & ENUMORCLASSBITS) != bitoftype_(s) && ((tagbindbits_(b) & (bitoftype_(s_union)|bitoftype_(s_enum))) || s == s_union || s == s_enum)) cc_err(bind_err_reuse_tag, tagbindsort(b), b, s); if (defining == TD_ContentDef) tagbindbits_(b) = (tagbindbits_(b) & ~ENUMORCLASSBITS) | bitoftype_(s); /* AM: the next test was != TD_NotDef but BEINGDEFD should not be set */ /* after "struct A;" (to match with "struct A *p"). */ /* Has anyone started using TB_BEINGDEFD to distinguish? */ if (defining == TD_ContentDef) tagbindbits_(b) |= TB_BEINGDEFD; return b; } /* variable and typedef bindings... */ Binder *implicit_decl(Symstr *a, int32 fn) { /* implicit declaration of 'extern int x' or 'extern int f()' */ /* N.B. the information has to be generated in the global heap */ if (LanguageIsCPlusPlus && fn) return implicit_decl_cpp(a); { TypeExpr *t = te_int; TypeExprFnAux s; if (fn) t = g_mkTypeExprfn(t_fnap, t, 0, 0, packTypeExprFnAux(s, 0, 999, 0, 0, fpregargs_disabled ? f_nofpregargs : 0)); /* minargs_ */ topbind2(a, (fn ? bitofstg_(s_extern)|b_undef|b_fnconst : bitofstg_(s_extern)|b_undef), t); binduses_(topbindingchain) |= u_implicitdef; return topbindingchain; } } /* * Used below and in instate_declaration for tentative Ansi definitions. * To say that this code is NASTY is a gross understatement. In fact, * it is hard to describe its nastiness in mere words. * @@@ AM (Sep 89) wants to re-work all this structure soon. */ struct TentativeDefn { TentativeDefn *next; DataAreaSort datasort; DataDesc data; int32 size, align; int32 elt_size; /* for open array */ /* When TARGET_HAS_BSS is NOT set, maybebss=1 <==> size=0. */ bool maybebss; bool statik; Symstr *sv; }; static TentativeDefn *tentative_defs; /* also init'd by bind_init */ static DataInit *datahead, *datasplice, *datatail; static TentativeDefn saved_vg_state; void save_vargen_state(TentativeDefn *td) { td->datasort = SetDataArea(DS_None); td->data.head = get_datadesc_ht(YES); td->data.tail = get_datadesc_ht(NO); td->data.size = get_datadesc_size(); } static void restore_vargen_state(TentativeDefn *td) { SetDataArea(td->datasort); set_datadesc_ht(YES, td->data.head); set_datadesc_ht(NO, td->data.tail); set_datadesc_size(td->data.size); } /* * Used to make a tentative defns list for the following routines. * Basically, this routine is called to record information about * the state of vargen.c before a zero initialiser for a tentative * static is processed. * It also holds whether we hope to allocate a top-level variable in bss. */ static bool addTentativeDefn( Symstr *sv, int32 size, int32 elt_size, int32 align, DeclRhsList *d) { TentativeDefn *td = NULL; for (td = tentative_defs; td != NULL; td = td->next) if (td->sv == sv) break; if (td == NULL) { td = (TentativeDefn *) GlobAlloc(SU_Other, sizeof(TentativeDefn)); td->data.head = td->data.tail = (DataInit *)DUFF_ADDR; td->data.size = 0; td->datasort = DS_None; td->next = tentative_defs; td->size = 0; td->elt_size = elt_size; td->align = align; td->sv = sv; td->maybebss = YES; td->statik = (d->declstg & bitofstg_(s_static)) != 0; tentative_defs= td; } /* The following test fills in the size details in: int a[],a[100]; */ if (size != 0) { td->size = size; #ifdef TARGET_HAS_BSS td->maybebss = (feature & FEATURE_PCC) || (size > BSS_THRESHOLD); #else td->maybebss = 0; #endif #if 0 /* We now defer the saving of vargen's state until after we know */ /* whether the variable is to go in read-write or const data */ SetDataArea(stg & u_constdata ? DS_Const : DS_ReadWrite); save_vargen_state(td); /* size = 0 => tentative foo[] */ #endif d->tentative = td; } #ifdef DEBUG_TENTATIVE_DEFS if (debugging(DEBUG_BIND)) cc_msg( "addTentativeDefn %lx, %lx next %lx (%s) head %lx tail %lx loc %ld name %s size %ld\n", (int32)get_datadesc(), (int32) td, (int32) td->next, (td->next) ? symname_(td->next->sv) : "", (int32)get_datadesc_ht(YES), (int32)get_datadesc_ht(NO), (int32)get_datadesc_size(), symname_(sv), size); #endif return td->maybebss; } #ifdef DEBUG_TENTATIVE_DEFS static void show_vargen_state(char *when) { if (debugging(DEBUG_BIND)) { DataInit *tmpdataq; cc_msg("vargen state %lx %s restoration:-\n", (int32)get_datadesc(), when); for (tmpdataq = get_datadesc_ht(YES); tmpdataq != 0; tmpdataq = tmpdataq->datacdr) { cc_msg( "DataInit %lx: cdr %lx rpt %ld sort %lx len %ld val %ld\n", (int32) tmpdataq, (int32) tmpdataq->datacdr, tmpdataq->rpt, tmpdataq->sort, tmpdataq->len, tmpdataq->val); } cc_msg("head = %lx tail = %lx size = %ld\n\n", (int32)get_datadesc_ht(YES), (int32)get_datadesc_ht(NO), get_datadesc_size()); } } #endif /* * The following routines are the ones that do the messing around with * vargen pointers in order to throw away old (zero) tentative initialisers * and replace them with new initialisers. */ static bool is_tentative(Symstr *sv) { TentativeDefn *td = tentative_defs, *prev; for (prev = NULL; td != NULL; prev = td, td = td->next) { if (td->sv == sv) { /* we are going to return TRUE at the end of this iteration. */ int32 count=0; DataInit *tmpdataq; /* * Found a tentative definition so let's reset vargen's state * ready for the initialiser... but only if (old) size != 0. * @@@ the 'size' test next is becoming subsumed by the bss test. */ if (td->size != 0 && !td->maybebss) { SetDataArea(td->datasort); save_vargen_state(&saved_vg_state); #ifdef DEBUG_TENTATIVE_DEFS if (debugging(DEBUG_BIND)) show_vargen_state("before"); #endif /* Restore vg's state to that before reading the initialiser */ restore_vargen_state(td); datahead = td->data.head; #ifdef DEBUG_TENTATIVE_DEFS if (debugging(DEBUG_BIND)) show_vargen_state("after"); #endif /* * Throw away old tentative (zero) initialiser ready for * replacement by genstaticparts(). */ if (get_datadesc_ht(YES) == 0) tmpdataq = saved_vg_state.data.head; else { /* FW: It used to say data.tail->datacdr here, but I think it meant datap */ tmpdataq = get_datadesc_ht(NO)->datacdr; get_datadesc_ht(NO)->datacdr = 0; } while (count < td->size) { if (tmpdataq == NULL) syserr(syserr_tentative); /* skip labels in static init chain */ if (tmpdataq->sort != LIT_LABEL) { /* AM: insert check for ->len field being valid (i.e. not LABEL/ADCON */ /* maybe this cannot happen, but AM gets very worried by this sort */ /* of 'if not LABEL then nice' reasoning. */ if (tmpdataq->sort == LIT_ADCON) syserr(syserr_tentative1); count += tmpdataq->rpt * tmpdataq->len; datasplice = tmpdataq; } tmpdataq = tmpdataq->datacdr; } if (count != padsize(td->size,alignof_toplevel_static)) syserr(syserr_tentative2); datatail = tmpdataq; /* set flag for reset_vg_after_init_of_tentative_defn() */ saved_vg_state.size = td->size; } else { if (debugging(DEBUG_BIND)) cc_msg("maybebss found\n"); } /* remove entry from tentative list */ if (prev == NULL) tentative_defs = td->next; else prev->next = td->next; return YES; } } return NO; } void reset_vg_after_init_of_tentative_defn(void) { TentativeDefn *td; if (saved_vg_state.size == 0) return; /* * Vargen has now inserted the new initialiser just where we want it. * Hum, however I might have removed an item from the list which I * have in my own tables. Check for this and update any items found. */ for (td = tentative_defs; td != 0; td = td->next) if (td->data.tail == datasplice) td->data.tail = get_datadesc_ht(NO); /* link new initialiser to the rest of the chain */ get_datadesc_ht(NO)->datacdr = datatail; /* * Reset all the pointers so that vargen does not realise that its * internal lists have been modified. */ if (datahead != 0) set_datadesc_ht(YES, saved_vg_state.data.head); if (datatail != 0) set_datadesc_ht(NO, saved_vg_state.data.tail); set_datadesc_size(saved_vg_state.data.size); saved_vg_state.size = 0; /* unset flag to prevent recall */ } static void check_for_incomplete_tentative_defs(TentativeDefn *td) { for (; td != NULL; td = td->next) { if (td->size == 0) { /* Variable had an incomplete type when defined: see whether */ /* it's still incomplete (tentatives are always toplevel */ /* objects, so bind_global_() and bindtype_() are legal. */ Binder *b = bind_global_(td->sv); if (sizeoftypelegal(bindtype_(b))) td->size = sizeoftype(bindtype_(b)); else { if (td->elt_size == 0 || td->statik) { cc_err(bind_err_incomplete_tentative, td->sv); continue; } td->size = td->elt_size; } td->maybebss = YES; /* Bodge: need to sort out allocation into data area (for fwd-refd struct too) */ } #ifdef TARGET_HAS_BSS if (td->maybebss) addbsssym(td->sv, td->size, td->align, td->statik, 0); #endif } } static void check_for_fwd_static_decl(Binder *b, Symstr *sv) { /* The following feature optionally enables spurious forward */ /* static declarations to be weeded out. */ if (feature & FEATURE_PREDECLARE && !(binduses_(b) & u_referenced) && bindstg_(b) & bitofstg_(s_static)) cc_warn(bind_warn_unused_static_decl, sv); } static void check_ansi_linkage(Binder *b, DeclRhsList *d) { if ((bindstg_(b) ^ d->declstg) & PRINCSTGBITS) { /* Linkage clash, but do not moan about stray 'extern type name's */ if ((d->declstg & b_globalregvar) || (d->declstg & bitofstg_(s_static)) && !(d->declstg & b_implicitstg) || (d->declstg & bitofstg_(s_extern)) && (d->declstg & b_implicitstg) || ((bindstg_(b) ^ d->declstg) & bitofstg_(s_weak))) { /* Oldest linkage wins... */ SET_BITMAP oldstg = bindstg_(b) & (bitofstg_(s_static)|bitofstg_(s_extern)|bitofstg_(s_weak)); if (oldstg == 0) oldstg = d->declstg & (b_implicitstg|bitofstg_(s_static)|bitofstg_(s_extern)|bitofstg_(s_weak)); /* ECN - convert errors about different linkage types to warnings */ if (suppress & D_LINKAGE) cc_warn(bind_rerr_linkage_disagreement, d->declname, oldstg); else cc_rerr(bind_rerr_linkage_disagreement, d->declname, oldstg); /* patch d->declstg to a compatible tentative type... */ d->declstg = (d->declstg & ~(b_implicitstg|bitofstg_(s_static)|bitofstg_(s_extern)|bitofstg_(s_weak))) | oldstg; } else if (bindstg_(b) & bitofstg_(s_static)) /* test is needed because of global register variables */ /* /* Explicit extern here, previous was static. Change d to say static and no longer extern, implicit nor C linkage Check OK for C++ */ d->declstg = (d->declstg & ~(b_implicitstg|b_clinkage|bitofstg_(s_static)|bitofstg_(s_extern)|bitofstg_(s_weak))) | (bindstg_(b) & (bitofstg_(s_static) | bitofstg_(s_extern) | bitofstg_(s_weak))); else if (bindstg_(b) & bitofstg_(s_extern)) /* test is needed because of global register variables */ /* /* Implicit static here, previous was extern. Change d to say extern and no longer static. Check OK for C++ */ d->declstg = (d->declstg & ~(bitofstg_(s_static)|bitofstg_(s_extern)|bitofstg_(s_weak))) | (bindstg_(b) & (bitofstg_(s_static) | bitofstg_(s_extern) | bitofstg_(s_weak))); } else check_for_fwd_static_decl(b, d->declname); } static TypeExpr *is_openarray(TypeExpr *t) { t = princtype(t); /* skip leading typedefs */ if (h0_(t) == t_subscript && (typesubsize_(t) == 0 || h0_(typesubsize_(t)) == s_binder)) return typearg_(t); return NULL; } void instate_alias(Symstr *a, Binder *b) /* * Make the symbol a an alias for b. This curious facility is used to * provide local pseudonyms ___first_arg and ___last_arg which share * binders with the first and last args in a function's definition, and * which are sometimes useful when implementing va_args on awkward machines. * Note that pop_varenv (qv) will not moan if the symbols I use as aliases * are unused. */ { /* should take care over storage lifetimes here... */ Binder *pseudonym = mk_binder(a, bindstg_(b)|b_pseudonym, bindtype_(b)); realbinder_(pseudonym) = /* cautious: shouldn't ever happen now. */ (bindstg_(b) & b_pseudonym) ? realbinder_(b) : b; add_local_binder(pseudonym); } #ifdef FOR_ACORN #ifndef PASCAL #ifndef FORTRAN static int cfront_special_name(Binder *b) { char *s; s = symname_(bindsym_(b)); if (s[0] == '_' && s[1] == '_') { s += 2; if (isdigit(*s)) { while (isdigit(*++s)); if (s[0] == '_' && s[1] == '_') return 1; } else if (strcmp(s, "link") == 0) return 1; } return 0; } #endif #endif #endif static Binder *instate_declaration_1(DeclRhsList *d, int declflag) /* only the TOPLEVEL and DUPL_OK bits of declflag are examined */ { /* I have just parsed a declarator, and in that identifiers are held */ /* as Symstr *'s which contain an h0 of s_identifier. Instate the */ /* declaration, returning the Binder record hung off the symbind_ entry.*/ Symstr *sv = d->declname; Binder *b; int32 olduses = 0; bool maybebss = 0; #ifdef PASCAL /*ECN*/ int level = declflag >> 2; declflag &= 3; #endif if (sv == 0 || h0_(sv) != s_identifier) /* check/remove*/ { syserr(syserr_instate_decl, (long)(sv==0 ? 0 : h0_(sv))); return 0; } if (attribofstgacc_(d->declstg)) syserr("instate_decl(access!=0)"); if (debugging(DEBUG_BIND)) { cc_msg("instate_declaration(%x, %lx): $r\n", declflag, d->declstg, sv); pr_typeexpr(d->decltype, sv); cc_msg("\n"); } /* No need to prunetype as inner typedef would have already been used: */ if (LanguageIsCPlusPlus && (d->declstg & bitofstg_(s_typedef)) && isprimtypein_(d->decltype, ENUMORCLASSBITS)) { TagBinder *tb = typespectagbind_(d->decltype); if (isgensym(tagbindsym_(tb))) { tagbindsym_(tb) = sv; if (declflag & TOPLEVEL) tag_global_(sv) = tb; } } if (declflag & TOPLEVEL) /* Top level declarations may only surplant previous top level extern decls */ /* Really we should also unify 'local' extern decls. @@@ not done yet. */ { TypeExpr *glotype = 0; b = bind_global_(sv); #ifdef PASCAL /*ECN*/ if (b && (bindstg_(b) & b_synbit1)) b = 0; #endif if (b != 0) { if (bindstg_(b) & bitofstg_(s_typedef)) { if (LanguageIsCPlusPlus && d->declstg & bitofstg_(s_typedef) && !(d->declstg & u_implicitdef) && equivtype(bindtype_(b), d->decltype) != 2) { cc_err(bind_err_type_disagreement, sv); b = 0; } else if (bindstg_(b) & u_implicitdef) b = 0; } else if (d->declstg & bitofstg_(s_typedef) && d->declstg & u_implicitdef) { Binder *bnew = topbind2(sv, d->declstg, globalize_typeexpr(d->decltype)); Binder *mem = topbindingchain; for (; mem != NULL; mem = bindcdr_(mem)) if (bindcdr_(mem) == b) break; if (mem == NULL) syserr("lost in instate_declaration_1"); bindcdr_(mem) = bindcdr_(b); bindcdr_(b) = topbindingchain; bind_global_(sv) = topbindingchain = b; return bnew; } } if (b != 0) { bool discardb = NO; olduses = binduses_(b); /* check the types match */ if (h0_(bindtype_(b)) == t_fnap && h0_(d->decltype) == t_fnap) { /* propagate #pragma -v and -y info from decl to defn */ if (typefnaux_(d->decltype).variad == 0) typefnaux_(d->decltype).variad = typefnaux_(bindtype_(b)).variad; typefnaux_(d->decltype).flags |= typefnaux_(bindtype_(b)).flags & ~typefnaux_(d->decltype).flags; if ((d->declstg & bitofstg_(s_inline)) && (bindstg_(b) & b_maybeinline)) bindstg_(b) = (bindstg_(b) & ~bitofstg_(s_extern)) | bitofstg_(s_static); bindstg_(b) &= ~b_maybeinline; /* /* @@@ old-style bit here. */ } switch (equivtype(bindtype_(b), d->decltype)) { default: if ((suppress & D_MPWCOMPATIBLE) && widened_equivtype(b->bindtype, d->decltype)) /* f(char) incompatibility with f(int) */ /* (or f(c) char c; {}) gets just a warning*/ cc_warn(bind_err_type_disagreement, sv); else { TypeExpr *bt = princtype(bindtype_(b)); TypeExpr *dt = princtype(d->decltype); /* The next line helps the 'SPECMARK' suite... */ if (h0_(bt) == t_fnap && h0_(dt) == t_fnap) cc_rerr(bind_err_type_disagreement, sv); else cc_err(bind_err_type_disagreement, sv); discardb = YES; /* new one wins (or trouble if old was a fn declaration and this is a var definition */ } break; case 2: glotype = bindtype_(b); /* d->decltype; /* IDENTICAL */ case 1: if (LanguageIsCPlusPlus && h0_(bindtype_(b)) == t_fnap && merge_default_arguments(bindtype_(b), d->decltype) == 2) glotype = bindtype_(b); /* d->decltype; /* IDENTICAL */ break; } /* It would be nice to merge the type/stgclass errors so we don't get */ /* 2 errors for 'typedef int a; extern double a;' */ /* Check for duplicate and conflicting definitions */ if ((bindstg_(b) | d->declstg) & bitofstg_(s_typedef)) { if ((bindstg_(b) & d->declstg) & bitofstg_(s_typedef)) { /* can duplicate a typedef in C++, not in C */ if (!LanguageIsCPlusPlus) cc_rerr(bind_rerr_duplicate_typedef, sv); } else { if ((d->declstg & bitofstg_(s_typedef)) && (d->declstg & u_implicitdef)) return NULL; else if ((bindstg_(b) & bitofstg_(s_typedef)) && (bindstg_(b) & u_implicitdef)) discardb = 1; else cc_err(bind_err_duplicate_definition, sv); } } /* The next two tests are perhaps more natural the other way round -- */ /* if we have two *definitions* then fault (unless one is tentative), */ /* otherwise essentially ignore one of the *declarations*. */ /* It is arguable the PCC case should make a more careful test on u_bss */ /* but this is compatible with previous version. */ else if (bindstg_(b) & b_undef && !(bindstg_(b) & u_bss) && (feature & FEATURE_PCC || !(bindstg_(b) & bitofstg_(s_extern) && bindstg_(b) & b_implicitstg && is_openarray(bindtype_(b))) ) || d->declstg & b_undef) { /* At least one of the declarations has no initialiser. */ /* N.B. an existing static declaration will appear to */ /* have an initialiser, as do ansi tentatives. */ /* (Provisional) BSS tentatives have b_undef but */ /* they also have u_bss, which we avoid. Messy! */ /* The delicate case: plain int [] has b_undef. */ if (feature & FEATURE_PCC) { /* pcc/as faults b is static or initialised plain, */ /* d is static or plain (whether or not init'd). */ if (!(bindstg_(b) & b_undef) && (d->declstg & bitofstg_(s_static) || d->declstg & bitofstg_(s_extern) && d->declstg & b_implicitstg)) cc_err(bind_err_duplicate_definition, sv); else check_for_fwd_static_decl(b, sv); } else if (LanguageIsCPlusPlus && !(h0_(bindtype_(b)) == t_fnap) && (bindstg_(b) & b_implicitstg) && (d->declstg & b_implicitstg)) cc_err(bind_err_duplicate_definition, sv); else check_ansi_linkage(b, d); } else if (!(bindstg_(b) & b_fnconst) && !(d->declstg & b_fnconst) && !(feature & FEATURE_PCC) && is_tentative(sv)) check_ansi_linkage(b, d); else cc_err(bind_err_duplicate_definition, sv); if (!(bindstg_(b) & b_clinkage) && (d->declstg & b_clinkage)) cc_rerr(bind_rerr_linkage_previously_c,b); if (discardb) { binduses_(b) |= u_superceded; b = 0; } } else { if (feature & FEATURE_PREDECLARE) { /* The following is a feature to enable policing of a software */ /* quality policy which says "only objects previously DECLARED */ /* as extern (presumably in a header) may be DEFINED extern". */ if ((d->declstg & bitofstg_(s_extern)) && (!(d->declstg & b_undef) || (d->declstg & b_implicitstg)) && sv != mainsym) cc_warn(bind_warn_not_in_hdr, sv); } if ((d->declstg & bitofstg_(s_typedef)) && isprimtypein_(d->decltype, ENUMORCLASSBITS)) { TagBinder *tb = typespectagbind_(d->decltype); tb->typedefname = sv; } if (LanguageIsCPlusPlus && h0_(d->decltype) == t_fnap) (void) merge_default_arguments(d->decltype, d->decltype); } /* Maybe we wish to turn off the following for non-hosted system. */ if (sv == mainsym && (d->declstg & bitofstg_(s_extern))) { TypeExpr *t = princtype(d->decltype); /* check args here too one day? */ if (h0_(t) != t_fnap || !equivtype(typearg_(t), te_int)) if (!(feature & FEATURE_PCC) || (feature & FEATURE_FUSSY)) cc_warn(bind_warn_main_not_int); } if (feature & FEATURE_PCC) { if ((d->declstg & (bitofstg_(s_static)|b_fnconst|b_globalregvar|bitofstg_(s_typedef)) ) == bitofstg_(s_static) && (d->declstg & b_undef)) { maybebss = addTentativeDefn(sv, sizeoftype(d->decltype), 0, alignoftype(d->decltype), d) #ifdef CONST_DATA_IN_CODE && !(d->declstg & u_constdata) #endif ; if (!maybebss) d->declstg &= ~b_undef; } } else { if ((b == 0 || bindstg_(b) & b_undef) && !(d->declstg & (b_fnconst|b_globalregvar|bitofstg_(s_typedef))) && (d->declstg & b_undef) && ((d->declstg & bitofstg_(s_static)) || ((d->declstg & bitofstg_(s_extern)) && (d->declstg & b_implicitstg)))) { /* no pre-exisiting defn and not a function defn and */ /* no initializer and (static blah... or plain blah...) */ TypeExpr *elt_t = is_openarray(d->decltype); int32 size, elt_size; if (elt_t == NULL) { size = 0; if (LanguageIsCPlusPlus /* C++ doesn't allow tentative definitions with */ /* incomplete type */ || (d->declstg & bitoftype_(s_static)) /* Nor does C if they have internal linkage */ || sizeoftypelegal(d->decltype)) /* But it does for external linkage (DR16) */ size = sizeoftype(d->decltype); elt_size = 0; } else size = 0, elt_size = sizeoftype(elt_t); if (disallow_tentative_statics && (d->declstg & (bitofstg_(s_static) | b_undef | u_constdata) == bitofstg_(s_static) | b_undef)) { maybebss = sizeoftype(d->decltype) > BSS_THRESHOLD; } else { maybebss = addTentativeDefn(sv, size, elt_size, alignoftype(d->decltype), d) #ifdef CONST_DATA_IN_CODE && !(d->declstg & u_constdata) #endif ; } if (!maybebss) d->declstg &= ~b_undef; } } /* * Decls such as 'extern int a;' may be superceded by decls such * as 'extern int a=1;'. However, decls such as 'extern int a=1;' * may not be superceded (but useless decls such as 'extern int a;' * will still be accepted). BUT BEWARE: 'extern int foo[]' MUST be * superceded by [extern] int foo[FOOSIZE] or chaos will ensue in * -pcc mode (only the size distinguishes Common Def from Ext Ref). */ if ((b != 0) && (glotype == 0)) { /* * Assert: glotype == 0 iff equivtype(b, d->...) == 1 * equivtype(b,d...) == 1 iff one of b, d is blah[]. * No: could be (int (*b)()) and (int (*d)(int)). * Now check for b (the original decl) being an open array. */ if (is_openarray(bindtype_(b))) { binduses_(b) |= u_superceded; b = 0; /* force treatment of d, below, as if new */ } } if (b == 0 || !(d->declstg & b_undef)) { #ifdef PASCAL /*ECN*/ TypeExpr *gt = glotype ? glotype : d->decltype; #else TypeExpr *gt = glotype ? glotype : globalize_typeexpr(d->decltype); #endif #ifndef OLD_VSN /* This code updates the old binder when a DEFINITION supercedes a */ /* DECLARATION. Thus bind_global_(sv) is set (init. 0) at most once. */ /* (except for the is_openarray() supercession above.). */ if (b == 0) b = topbind2(sv, d->declstg, gt); else if (!(bindstg_(b) & b_globalregvar)) { /* Assert: !(d->declstg & b_undef) */ bindstg_(b) = d->declstg | (bindstg_(b) & (bitofstg_(s_virtual)|bitofstg_(s_inline)|b_impl|b_purevirtual)); bindtype_(b) = gt; /* @@@ bindstg/bindconst too? */ } #else /* !OLD_VSN */ /* suppress new DECLARATION if already DEFINED. */ if (b != 0) binduses_(b) |= u_superceded; topbind2(sv, d->declstg, gt); /* sets bind_global_(sv) */ b = bind_global_(sv); #endif } #ifdef TARGET_HAS_BSS if (maybebss) { /* addbsssym() now called when we know for certain. */ TypeExpr *t = bindtype_(b); if (disallow_tentative_statics) { bindstg_(b) &= ~b_undef; bindaddr_(b) = addbsssym(sv, sizeoftype(t), alignoftype(t), (bindstg_(b) & bitofstg_(s_static)) != 0, YES); } else bindaddr_(b) = BINDADDR_UNSET; } #endif } else { /* NOT a top-level declaration */ Binder *bnew; Scope *saved_local_scope = set_local_block_scope(); if (local_scope == NULL) syserr("instate_declaration_1 - no local scope/local block scope"); if ((b = find_scopemember(sv, local_scope->scopemems)) != NULL) { if ((bindstg_(b) | d->declstg) & bitofstg_(s_typedef)) { if ((bindstg_(b) & d->declstg & bitofstg_(s_typedef)) && (d->declstg & u_implicitdef)) { if (!(d->declstg & b_undef)) { bindstg_(b) = d->declstg | (bindstg_(b) & (bitofstg_(s_virtual)|bitofstg_(s_inline))); bindtype_(b) = globalize_typeexpr(d->decltype); } return NULL; } else if (bindstg_(b) & bitofstg_(s_typedef)) { if (bindstg_(b) & u_implicitdef) declflag |= DUPL_OK; } else { Binder *bnew = global_mk_binder(NULL, sv, d->declstg, globalize_typeexpr(d->decltype)); Binder *mem; add_local_binder(bnew); mem = local_scope->scopemems; for (; mem != NULL; mem = bindcdr_(mem)) if (bindcdr_(mem) == b) break; if (mem == NULL) syserr("lost in instate_declaration_1"); bindcdr_(mem) = bindcdr_(b); bindcdr_(b) = local_scope->scopemems; local_scope->scopemems = b; return bnew; } } if (!(declflag & DUPL_OK)) { if (!(bindstg_(b) & d->declstg & bitofstg_(s_extern) || (LanguageIsCPlusPlus && bindstg_(b) & d->declstg & bitofstg_(s_typedef)))) { if (istypevar(bindtype_(b))) cc_rerr(syn_rerr_temp_para_redefinition, b); else cc_err(bind_err_duplicate_definition, sv); } else if (equivtype(d->decltype, bindtype_(b)) == 0) cc_err(bind_err_duplicate_definition, sv); else if (LanguageIsCPlusPlus && h0_(bindtype_(b)) == t_fnap) (void)merge_default_arguments(bindtype_(b), d->decltype); } /* flag old one as referenced to avoid spurious warns: */ binduses_(b) |= u_referenced; } else if (LanguageIsCPlusPlus && h0_(d->decltype) == t_fnap) (void) merge_default_arguments(d->decltype, d->decltype); /* AM: at some time we may wish to check or export C 'local' extern */ /* decls for checking purposes. At that point we must ensure */ /* that d->decltype is globalize()d. */ if (b != NULL && !(declflag & DUPL_OK)) bnew = b; else { if (declflag & GLOBALSTG) /* TOPLEVEL doesn't come here. */ bnew = global_mk_binder(NULL, sv, d->declstg, d->decltype = globalize_typeexpr(d->decltype)); else bnew = mk_binder(sv, d->declstg, d->decltype); add_local_binder(bnew); /* stop regalloc moan about typefnaux */ if (d->declstg & bitofstg_(s_extern) && isfntype(bindtype_(bnew))) bindtype_(bnew) = globalize_typeexpr(bindtype_(bnew)); } /* If a local extern is already bound, try to find on topbindingchain: */ if ((d->declstg & b_undef) && ((d->declstg & (bitofstg_(s_extern))) || ((d->declstg & (bitofstg_(s_static))) && (h0_(d->decltype) == t_fnap)))) { /* The following lines are written to cope with curios like: */ /* extern int i=0; void f() { auto i; { extern int i; ... */ /* However, note ANSI ambiguities in: */ /* typedef int i; void f() { auto int i; { extern int i; ... */ /* and */ /* void g(double); void f() { extern void g(); g(1); } */ Binder *btop = 0, *t; for (t = topbindingchain; t != NULL; t = bindcdr_(t)) if (bindsym_(t) == sv && !(binduses_(t) & u_superceded)) btop = t; if (btop) { if (!equivtype(bindtype_(btop), d->decltype) || bindstg_(btop) & bitofstg_(s_typedef)) /* warn about above ambiguities? */ cc_rerr_cppwarn(bind_rerr_local_extern, sv); /* The following lines specifically please INMOS, but are otherwise OK. */ /* Update the storage class/bindaddr field, but NOT type (ambiguity): */ /* @@@ what about local externs to register globals (extension)? */ else { /* Inherit old storage class: */ bindstg_(bnew) = bindstg_(bnew) & ~(STGBITS | u_loctype) | bindstg_(btop) & (STGBITS | u_loctype); if (!(bindstg_(btop) & b_undef)) { /* change undef extern to this-module-defd. */ bindaddr_(bnew) = bindaddr_(btop); bindstg_(bnew) &= ~b_undef; } } } } if (h0_(d->decltype) != t_fnap && (d->declstg & bitofstg_(s_static))) { #ifdef TARGET_HAS_BSS /* Note that that this BSS_THRESHOLD applies in PCC mode too. */ if ( (d->declstg & b_undef) && sizeoftype(d->decltype) > BSS_THRESHOLD && !(d->declstg & u_constdata) ) maybebss = YES; else #endif d->declstg &= ~b_undef, bindstg_(bnew) &= ~b_undef; } b = bnew; #ifdef TARGET_HAS_BSS if (maybebss) { TypeExpr *t = bindtype_(b); bindaddr_(b) = addbsssym(sv, sizeoftype(t), alignoftype(t), (bindstg_(b) & bitofstg_(s_static)) != 0, YES); } #endif local_scope = saved_local_scope; } /* not a top-level declaration */ /* * Make sure information about old definitions and previous references * gets carried over from the old binder to the new binder. * (ie. '{f();}; f(){}'). */ #ifdef PASCAL /*ECN*/ b->bindlevel = level; b->synflags = d->synflags; #endif binduses_(b) |= olduses & u_referenced | (d->declstg & u_constdata) #ifdef TARGET_HAS_BSS /* @@@ Dec 90: when does the u_bss get removed if later init'ed? */ | (maybebss ? u_bss : 0) #endif ; #ifdef FOR_ACORN #ifndef PASCAL #ifndef FORTRAN if (cplusplus_flag && cfront_special_name(b)) binduses_(b) |= u_referenced; #endif #endif #endif return b; } ClassMember *instate_member(DeclRhsList *d, int bindflg) { return LanguageIsCPlusPlus ? instate_member_cpp(d, bindflg) : instate_member_1(d, bindflg); } Binder *instate_declaration(DeclRhsList *d, int declflag) { return LanguageIsCPlusPlus ? instate_declaration_cpp(d, declflag) : instate_declaration_1(d, declflag); } /* label bindings... */ static LabBind *label_create(Symstr *id) /* Called when a label is referenced - arranges for a check to be made */ /* at the end of the block to ensure that the label is properly defined. */ { LabBind *x = symlab_(id); if (x == 0) labelchain = symlab_(id) = x = mk_labbind(labelchain, id); return x; } LabBind *label_define(Symstr *id) /* Called when a label is defined. NULL return iff duplicate */ { LabBind *x = label_create(id); if (x->labuses & l_defined) { cc_err(bind_err_duplicate_label, id); return 0; } x->labuses |= l_defined; return x; } LabBind *label_reference(Symstr *id) /* Called when a label is referenced - arranges for a check to be made */ /* at the end of the block to ensure that the label is properly defined. */ { LabBind *x = label_create(id); x->labuses |= l_referenced; return x; } void label_resolve(void) { LabBind *lc; for (lc = labelchain; lc!=NULL; lc = lc->labcdr) { Symstr *id = lc->labsym; symlab_(id) = NULL; if (!(lc->labuses & l_defined)) cc_err(bind_err_unset_label, id); /* NB the CG or SEM should ignore goto's to label 0 (undef'd). */ if (!(lc->labuses & l_referenced)) cc_warn(bind_warn_label_not_used, id); } labelchain = NULL; } #ifndef NO_DUMP_STATE void Bind_LoadState(FILE *f) { union { uint16 h[8]; uint32 w[8]; } x; uint32 i, j; Dump_Init(Dump_Load, f); for (i = 1; i < dump_loadstate.ngensym; i++) { Symstr *sym; fread(x.h, sizeof(uint16), 1, f); sym = Dump_LoadSym(x.h[0], f); symchain_(sym) = sym; } for (j = 0; j < BIND_HASHSIZE; j++) { Symstr **tailp = &(*hashvec)[j]; for (;;) { Symstr *sym; fread(x.h, sizeof(uint16), 1, f); if (x.h[0] == 0) break; sym = Dump_LoadSym(x.h[0], f); *tailp = sym; tailp = &symchain_(sym); } *tailp = NULL; } for (i = 1; i < dump_loadstate.nglobbind; i++) { Binder *b = Dump_LoadedBinder(i); fread(x.w, sizeof(uint32), 6, f); h0_(b) = x.w[0]; bindsym_(b) = Dump_LoadedSym(x.w[1]); bindcdr_(b) = Dump_LoadedTagOrBinder(x.w[2]); attributes_(b) = x.w[3]; bindstg_(b) = x.w[4]; bindparent_(b) = Dump_LoadedTag(x.w[5]); if (bindstg_(b) & b_bindaddrlist) { fread(x.w, sizeof(uint32), 1, f); bindbl_(b) = Dump_LoadedSharedBindList(x.w[0]); } else if (attributes_(b) & (CB_ANON|CB_HASCOREFN) || bindstg_(b) & (b_impl|b_pseudonym)) { fread(x.w, sizeof(uint32), 1, f); realbinder_(b) = Dump_LoadedBinder(x.w[0]); } else fread(&bindaddr_(b), sizeof(IPtr), 1, f); if (h0_(b) == s_member) { fread(&memwoff_(b), sizeof(uint32), 1, f); fread(&membits_(b), sizeof(uint8), 1, f); fread(&memboff_(b), sizeof(uint8), 1, f); } else { bindconst_(b) = (bindstg_(b) & bitofstg_(s_inline)) ? NULL : Dump_LoadExpr(f); } fread(x.w, sizeof(int32), 1, f); if (bindstg_(b) & bitofstg_(s_auto)) { bindmcrep_(b) = x.w[0]; fread(&bindxx_(b), sizeof(VRegnum), 1, f); } bindtype_(b) = (x.w[0] != (uint32)NOMCREPCACHE) ? (TypeExpr *)DUFF_ADDR : Dump_LoadType(f); bindinline_(b) = NULL; } for (i = 1; i < dump_loadstate.nglobtag; i++) { TagBinder *b = Dump_LoadedTag(i); fread(x.w, sizeof(uint32), 8, f); h0_(b) = x.w[0]; tagbindsym_(b) = Dump_LoadedSym(x.w[1]); tagbindcdr_(b) = (TagBinder *)Dump_LoadedTagOrBinder(x.w[2]); attributes_(b) = x.w[3]; tagbindbits_(b) = x.w[4]; tagbindparent_(b) = Dump_LoadedTag(x.w[5]); b->cachedsize = x.w[6]; b->typedefname = Dump_LoadedSym(x.w[7]); if (tagbindbits_(b) & bitoftype_(s_enum)) tagbindenums_(b) = Dump_LoadBindList(f); else { fread(x.w, sizeof(uint32), 1, f); tagbindmems_(b) = Dump_LoadedTagOrBinder(x.w[0]); } b->friends = Dump_LoadFriends(f); tagbindtype_(b) = Dump_LoadType(f); } for (i = 1; i < dump_loadstate.nsym; i++) { Symstr *sym = Dump_LoadedSym(i); symfold_(sym) = Dump_LoadedSym((IPtr)symfold_(sym)); } Inline_LoadState(f); for (i = 1; i < dump_loadstate.nbindlist; i++) { BindList *bl = Dump_LoadedSharedBindList(i); fread(x.w, sizeof(uint32), 2, f); bl->bindlistcdr = Dump_LoadedSharedBindList(x.w[0]); bl->bindlistcar = Dump_LoadedBinder(x.w[1]); } Builtin_LoadState(f); } void Bind_DumpState(FILE *f) { uint32 i, symno; TagBinder **bindersave[GLOBBINDV_MAXSEGS]; TagBinder **tagbindersave[GLOBTAGV_MAXSEGS]; long headerpos; Dump_Init(Dump_Dump, f); for (i = 1; i < ngensym; i++) { uint32 segno = i / GENSYMV_SEGSIZE, segix = i % GENSYMV_SEGSIZE; Symstr *sym = gensymv[segno][segix]; symlab_(sym) = (LabBind *)(IPtr)i; } for (symno = ngensym, i = 0; i < BIND_HASHSIZE; i++) { Symstr *sym = (*hashvec)[i]; for (; sym != 0; sym = symchain_(sym)) symlab_(sym) = (LabBind *)(IPtr)symno++; } for (i = 0; i < globbindlimit; i += GLOBBINDV_SEGSIZE) bindersave[i / GLOBBINDV_SEGSIZE] = (TagBinder **)SynAlloc(sizeof(TagBinder *) * GLOBBINDV_SEGSIZE); for (i = 0; i < globtaglimit; i += GLOBTAGV_SEGSIZE) tagbindersave[i / GLOBTAGV_SEGSIZE] = (TagBinder **)SynAlloc(sizeof(TagBinder *) * GLOBTAGV_SEGSIZE); for (i = 1; i < nglobbind; i++) { uint32 segno = i / GLOBBINDV_SEGSIZE, segix = i % GLOBBINDV_SEGSIZE; Binder *b = globbindv[segno][segix]; bindersave[segno][segix] = bindparent_(b); bindparent_(b) = (TagBinder *)(IPtr)i; } for (i = 1; i < nglobtag; i++) { uint32 segno = i / GLOBTAGV_SEGSIZE, segix = i % GLOBTAGV_SEGSIZE; TagBinder *b = globtagv[segno][segix]; tagbindersave[segno][segix] = tagbindparent_(b); tagbindparent_(b) = (TagBinder *)(IPtr)i; } { union { uint16 h[8]; uint32 w[8]; } x; headerpos = ftell(f); x.w[0] = ngensym; x.w[1] = symno - ngensym; x.w[2] = nglobbind; x.w[3] = nglobtag; x.w[4] = 0; /* rewritten with dump_loadstate.nbindlist at end */; fwrite(x.w, sizeof(uint32), 5, f); for (i = 1; i < ngensym; i++) { uint32 segno = i / GENSYMV_SEGSIZE, segix = i % GENSYMV_SEGSIZE; Dump_Sym(gensymv[segno][segix], f); } for (i = 0; i < BIND_HASHSIZE; i++) { Symstr *sym = (*hashvec)[i]; for (; sym != 0; sym = symchain_(sym)) Dump_Sym(sym, f); x.h[0] = 0; fwrite(x.h, sizeof(uint16), 1, f); } for (i = 1; i < nglobbind; i++) { uint32 segno = i / GLOBBINDV_SEGSIZE, segix = i % GLOBBINDV_SEGSIZE; Binder *b = globbindv[segno][segix]; x.w[0] = h0_(b); x.w[1] = Dump_SymRef(bindsym_(b)); x.w[2] = Dump_TagOrBinderRef(bindcdr_(b)); x.w[3] = attributes_(b); x.w[4] = bindstg_(b); x.w[5] = Dump_TagRef(bindersave[segno][segix]); fwrite(x.w, sizeof(uint32), 6, f); if (bindstg_(b) & b_bindaddrlist) { x.w[0] = Dump_NoteSharedBindList(bindbl_(b)); fwrite(x.w, sizeof(uint32), 1, f); } else if (attributes_(b) & (CB_ANON|CB_HASCOREFN) || bindstg_(b) & (b_impl|b_pseudonym)) { x.w[0] = Dump_BinderRef(realbinder_(b)); fwrite(x.w, sizeof(uint32), 1, f); } else fwrite(&bindaddr_(b), sizeof(IPtr), 1, f); if (h0_(b) == s_member) { fwrite(&memwoff_(b), sizeof(uint32), 1, f); fwrite(&membits_(b), sizeof(uint8), 1, f); fwrite(&memboff_(b), sizeof(uint8), 1, f); } else if (!(bindstg_(b) & bitofstg_(s_inline))) { Dump_Expr(bindconst_(b), f); } if (bindstg_(b) & bitofstg_(s_auto)) { x.w[0] = bindmcrep_(b); x.w[1] = bindxx_(b); fwrite(x.w, sizeof(uint32), 2, f); } else { x.w[0] = NOMCREPCACHE; fwrite(x.w, sizeof(uint32), 1, f); } if (x.w[0] == (uint32)NOMCREPCACHE) Dump_Type(bindtype_(b), f); } for (i = 1; i < nglobtag; i++) { uint32 segno = i / GLOBTAGV_SEGSIZE, segix = i % GLOBTAGV_SEGSIZE; TagBinder *b = globtagv[segno][segix]; x.w[0] = h0_(b); x.w[1] = Dump_SymRef(tagbindsym_(b)); x.w[2] = Dump_TagOrBinderRef((Binder *)tagbindcdr_(b)); x.w[3] = attributes_(b); x.w[4] = tagbindbits_(b); x.w[5] = Dump_TagRef(tagbindersave[segno][segix]); x.w[6] = b->cachedsize; x.w[7] = Dump_SymRef(b->typedefname); fwrite(x.w, sizeof(uint32), 8, f); if (tagbindbits_(b) & bitoftype_(s_enum)) Dump_BindList(tagbindenums_(b), f); else { x.w[0] = Dump_TagOrBinderRef(tagbindmems_(b)); fwrite(x.w, sizeof(uint32), 1, f); } Dump_Friends(b->friends, f); Dump_Type(tagbindtype_(b), f); } } Inline_DumpState(f); Dump_SharedBindLists(f); Builtin_DumpState(f); fseek(f, headerpos + 4*sizeof(Uint), SEEK_SET); fwrite(&dump_loadstate.nbindlist, sizeof(uint32), 1, f); for (i = 1; i < nglobbind; i++) { uint32 segno = i / GLOBBINDV_SEGSIZE, segix = i % GLOBBINDV_SEGSIZE; Binder *b = globbindv[segno][segix]; bindparent_(b) = bindersave[segno][segix]; } for (i = 1; i < nglobtag; i++) { uint32 segno = i / GLOBTAGV_SEGSIZE, segix = i % GLOBTAGV_SEGSIZE; TagBinder *b = globtagv[segno][segix]; tagbindparent_(b) = tagbindersave[segno][segix]; } } #endif /* NO_DUMP_STATE */ void bind_cleanup(void) /* see comment on unbindlocals */ { TagBinder *p; Binder *b; for (p = toptagbindchain; p != 0; p = tagbindcdr_(p)) { Symstr *sv = bindsym_(p); if (debugging(DEBUG_BIND)) cc_msg("top struct unbind $r of %p\n", sv, (VoidStar)tag_global_(sv)); tag_global_(sv) = 0; /* restore previous binding */ } toptagbindchain = 0; /* just for tidyness */ check_for_incomplete_tentative_defs( (TentativeDefn *) dreverse((List *)tentative_defs)); for (b = topbindingchain; b != 0; b = bindcdr_(b)) { Symstr *sv = bindsym_(b); bind_global_(sv) = 0; /* restore previous binding */ if (!(binduses_(b) & u_superceded) && (bindstg_(b) & bitofstg_(s_static))) { if (!(qualifiersoftype(bindtype_(b)) & bitoftype_(s_const)) || (bindstg_(b) & b_generated)) /* ignore un-generated consts */ { if (binduses_(b) & u_referenced) { if (bindstg_(b) & b_undef) { /* surely b_undef static MUST be fnconst after */ /* tentative resolution? u_bss? */ /* @@@ check_for_imcomplete_tentative_defs() */ /* does not unset b_undef for [] nor bss! */ if (bindstg_(b) & b_fnconst) { if (suppress & D_LINKAGE) /* @@@ this should probably be removed now */ cc_warn(bind_err_undefined_static, b); else cc_pccwarn(bind_err_undefined_static, b); } } } else if (!(bindstg_(b) & bitofstg_(s_inline))) cc_warn(bind_warn_static_not_used, b); } } else if (feature & FEATURE_NOUSE) { if (!(binduses_(b) & u_referenced) && !(bindstg_(b) & bitofstg_(s_typedef))) { if (bindstg_(b) & b_fnconst) { cc_warn(bind_warn_function_not_used, b); } else { cc_warn(bind_warn_variable_not_used, b); } } } } topbindingchain = 0; /* just for tidyness */ } void bind_init(void) { int i; topbindingchain = 0, toptagbindchain = 0, labelchain = 0; freeScopes = local_scope = NULL; tag_found_in_local_scope = NO; scope_level = 0; tentative_defs = 0; saved_vg_state.size = 0; if (dump_state & DS_Dump) { ngensym = 1; gensymlimit = 0; nglobbind = 1; globbindlimit = 0; nglobtag = 1; globtaglimit = 0; gensymv = (Symstr ***)GlobAlloc(SU_Other, sizeof(Symstr **) * GENSYMV_MAXSEGS); globbindv = (Binder ***)GlobAlloc(SU_Other, sizeof(Binder **) * GLOBBINDV_MAXSEGS); globtagv = (TagBinder ***)GlobAlloc(SU_Other, sizeof(TagBinder **) * GLOBTAGV_MAXSEGS); } gensymline = gensymgen = 0; hashvec = (Symstr *((*)[BIND_HASHSIZE])) GlobAlloc(SU_Other, sizeof(*hashvec)); for (i = 0; i < BIND_HASHSIZE; i++) (*hashvec)[i] = NULL; } /* end of bind.c */
stardot/ncc
tests/llong.c
<reponame>stardot/ncc<filename>tests/llong.c<gh_stars>0 /* * ARM C compiler regression test $RCSfile$ * Copyright (C) 1995 Advanced Risc Machines Ltd. All rights reserved. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <stdio.h> #include "testutil.h" /* The tests below are designed to exercise the compiler's */ /* internal constant folding (expressions involving constant */ /* operands), the compiler's internal constant folding after */ /* dataflow analysis (expressions involving local non-address */ /* taken variables and constants) and the run-time support */ /* (expressions involving statics, one function call removed */ /* from the point of assignment to the static). */ static long long l, l1; static unsigned long long ul, ul1; static unsigned u, u1; static int i, i1; static int a[1LL]; static int b = 123LL; double d; typedef struct { long long a: 55; long long b: 12; long long c: 40; } LL; void set_bf(LL *p) { p->a = 0x123456789abcd; p->b = 33; p->c = 0xa987654321; } void t_bf(void) { LL ll; set_bf(&ll); EQLL(ll.a, 0x123456789abcd); EQLL(ll.b, 33); EQLL(ll.c, 0xa987654321); } void t_sw(void) { l = 0; a[0LL] = 1; switch(u) { case 1LL: break; default: EQI(u, 1); break; } switch(l) { case 1: break; default: EQI(u, 1); break; } EQI(a[0], 1); EQI(a[l], 1); } long long l_7(void) { return 7; } unsigned long long u_7(void) { return 7; } void t_add(void) { long long a, b; EQLL(1+2, 3); EQLL(1+0xffffffff, 0); EQLL(1+0xffffffffLL, 0x100000000); EQLL(5LL+7, 12); a = 3; b = 9; l = 5; l1 = 7; u = 0xffffffff; u1 = 4; EQLL(a+b, 12); EQLL(a+b, l+l1); EQLL(u+u1, 3); EQLL(u+(long long)u1, 0x100000003); a = -1; b = 3; l = -3; EQLL(a+b, 2); EQLL(a+5, 4); EQLL(l+b, 0); EQLL(l+2, a); } void t_sub(void) { long long a, b; EQLL(1-2, -1); EQLL(7-5LL, 2); a = 3; b = 9; l = 5; l1 = 7; EQLL(b-a, 6); EQLL(l1-l, l-a); a = -1; b = 3; l = -3; EQLL(a-b, -4); EQLL(a-(b-1), -3); EQLL(b-a, 4); EQLL(a-5, -6); EQLL(b-l, 6); EQLL(l-a, -2); } void t_mul(void) { long long a, b; EQLL(2*3, 6); EQLL(0x100000*0x300000LL, 0x30000000000); a = 3; b = 9; l = 5; l1 = 7; EQLL(b*a, 27); EQLL(l1*l, 35); a = -2; b = 3; l = -3; l1 = u = 0x123456; EQLL(a*b, -6); EQLL(a*5, -10); EQLL(b*l, -9); EQLL(l*a, 6); EQLL(0x123456*0x123456LL, 0x14b66cb0ce4); EQLL(l1*l1, 0x14b66cb0ce4); EQLL(u*u, 0x66cb0ce4); } void t_div(void) { l = 0x123456; i = -5; i1 = -3; EQLL(0x14b66cb0ce4 / l, l); EQLL(0x14b66cb0ce4 / l, l); EQLL(-5 / -3, 1); EQLL(i / i1, 1); EQLL(i / 2, -2); EQLL(40 / l_7(), 5); EQLL(40 % u_7(), 5); l = 0x8000000000000000; EQLL(l / -1, l); EQLL(l / -1, l); EQLL(l / -1, l); EQLL(l / -1, l); } void t_rem(void) { l = 0x123456; i = -5; i1 = -3; EQLL(0x14b66cb0ce4 % l, 0); EQLL(0x14b66cb0ce4 % l, 0); EQLL(-5 % -3, -2); EQLL(i % i1, -2); EQLL(i % 2, -1); EQLL(40 % u_7(), 5); EQLL(40 % l_7(), 5); } void t_neg(void) { long long ll = l1 = 0x123456789; l = 1; EQLL(-ll, -0x123456789); EQLL(-l1, -0x123456789); l1 = -1; EQLL(-l, -1); EQLL(-l1, 1); } void t_cmp(void) { long long ll = -1; unsigned long long lul = -1; ul = -1; l = -1; EQI(-1LL > 0, 0); EQI((unsigned long long)-1 > 0, 1); EQI(ll > 0, 0); EQI(lul > 0, 1); EQI(l > 0, 0); EQI(ul > 0, 1); EQI(l >= 0, 0); EQI(ul >= 0, 1); EQI(l < 0, 1); EQI(ul < 0, 0); EQI(l <= 0, 1); EQI(ul <= 0, 0); EQI(0x123456789ab > 0x123456789ac, 0); EQI(0x223456789ab > 0x123456789aa, 1); } void t_and(void) { unsigned long long lul; ul = lul = 0x1234567890123456; EQLL(0x1234567890123456 & 0xff00ff00ff00ff00, 0x1200560090003400); EQLL(0x1234567890123456 & 0xf0f0f0f00f0f0f0f, 0x1030507000020406); EQLL(lul & 0xff00ff00ff00ff00, 0x1200560090003400); EQLL(lul & 0xf0f0f0f00f0f0f0f, 0x1030507000020406); EQLL(ul & 0xff00ff00ff00ff00, 0x1200560090003400); EQLL(ul & 0xf0f0f0f00f0f0f0f, 0x1030507000020406); } void t_or(void) { unsigned long long lul; ul = lul = 0x1234567890123456; EQLL(0x1234567890123456 | 0xff00ff00ff00ff00, 0xff34ff78ff12ff56); EQLL(0x1234567890123456 | 0xf0f0f0f00f0f0f0f, 0xf2f4f6f89f1f3f5f); EQLL(lul | 0xff00ff00ff00ff00, 0xff34ff78ff12ff56); EQLL(lul | 0xf0f0f0f00f0f0f0f, 0xf2f4f6f89f1f3f5f); EQLL(ul | 0xff00ff00ff00ff00, 0xff34ff78ff12ff56); EQLL(ul | 0xf0f0f0f00f0f0f0f, 0xf2f4f6f89f1f3f5f); } void t_eor(void) { unsigned long long lul; ul = lul = 0x1234567890123456; EQLL(0x1234567890123456 ^ 0xff00ff00ff00ff00, 0xed34a9786f12cb56); EQLL(0x1234567890123456 | 0xf0f0f0f00f0f0f0f, 0xe2c4a6889f1d3b59); EQLL(lul | 0xff00ff00ff00ff00, 0xed34a9786f12cb56); EQLL(lul | 0xf0f0f0f00f0f0f0f, 0xe2c4a6889f1d3b59); EQLL(ul | 0xff00ff00ff00ff00, 0xed34a9786f12cb56); EQLL(ul | 0xf0f0f0f00f0f0f0f, 0xe2c4a6889f1d3b59); } void t_shift(void) { long long ll = -1; unsigned long long lul = -1; l = -1; ul = -1; EQLL(0xffffffffffffffff >> 5, 0x07ffffffffffffff); EQLL(-1LL >> 5, -1); EQLL(0xffffffffffffffff >> 34, 0x3fffffff); EQLL(-1LL >> 34, -1); EQLL(lul >> 5, 0x07ffffffffffffff); EQLL(ll >> 5, -1); EQLL(lul >> 34, 0x3fffffff); EQLL(ll >> 34, -1); EQLL(ul >> 5, 0x07ffffffffffffff); EQLL(l >> 5, -1); EQLL(ul >> 34, 0x3fffffff); EQLL(l >> 34, -1); l = ul = ll = lul = 0x9876543210234567; EQLL(0x9876543210234567 >> 40, 0x987654); EQLL((long long)0x9876543210234567 >> 40, 0xffffffffff987654); EQLL(0x9876543210234567 >> 20, 0x98765432102); EQLL((long long)0x9876543210234567 >> 20, 0xfffff98765432102); EQLL(lul >> 40, 0x987654); EQLL(ll >> 40, 0xffffffffff987654); EQLL(lul >> 20, 0x98765432102); EQLL(ll >> 20, 0xfffff98765432102); EQLL(ul >> 40, 0x987654); EQLL(l >> 40, 0xffffffffff987654); EQLL(ul >> 20, 0x98765432102); EQLL(l >> 20, 0xfffff98765432102); EQLL(0x9876543210234567 << 12, 0x6543210234567000); EQLL(0x9876543210234567 << 40, 0x2345670000000000); EQLL(lul << 12, 0x6543210234567000); EQLL(lul << 40, 0x2345670000000000); EQLL(l << 12, 0x6543210234567000); EQLL(l << 40, 0x2345670000000000); l = 1; i = 3; EQI(i << l, 6); EQI(i << l, 6); EQLL(i << l, 6); } void t_not(void) { } void t_pr(void) { char b[32]; sprintf(b, "%llx", 0x9876543210234567); EQS(b, "9876543210234567"); sscanf(b, "%llx", &ul); EQLL(ul, 0x9876543210234567); sprintf(b, "%lld", 0x1234567890); EQS(b, "78187493520"); sscanf(b, "%lld", &l); EQLL(l, 0x1234567890); sprintf(b, "%lld", -0x1234567890); EQS(b, "-78187493520"); sscanf(b, "%lld", &l); EQLL(l, -0x1234567890); } int main(void) { BeginTest(); EQI(sizeof(long long), 8); t_add(); t_sub(); t_mul(); t_div(); t_rem(); t_cmp(); t_neg(); t_and(); t_or(); t_not(); t_shift(); l = 1; u = 1; t_sw(); t_bf(); t_pr(); EndTest(); return 0; }
stardot/ncc
mip/regalloc.h
/* * mip/regalloc.h * Copyright (C) Acorn Computers Ltd., 1988. * Copyright (C) Codemist Ltd., 1988. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _regalloc_h #define _regalloc_h #ifndef _defs_LOADED # include "defs.h" #endif #ifndef _cgdefs_LOADED # include "cgdefs.h" #endif extern VRegnum vregister(RegSort type); extern RegSort vregsort(VRegnum r); extern void allocate_registers(BindList *spill_order); extern RealRegSet regmaskvec; /* * Note that old back-ends will have used a variable regmask which can * now be re-written as (regmaskvec.map)[0], but only if there are at most * 32 registers to be so mapped. */ #if (NMAGICREGS <= 32) /* AM never wants to chase bugs of regmask being used if MAGICREGS>32. */ # define regmask ((regmaskvec.map)[0]) /* backwards compatibility. */ #endif extern RealRegister register_number(VRegnum a); extern void globalregistervariable(VRegnum r); extern void note_slave(VRegnum slave, VRegnum master); extern void forget_slave(VRegnum slave, VRegnum master); typedef union { char **s; VRegSetP vr; VRegnum r; } RealRegSet_MapArg; typedef void RealRegSet_MapFn(RealRegister r, RealRegSet_MapArg *arg); extern void augment_RealRegSet(RealRegSet *, unsigned32); extern bool member_RealRegSet(RealRegSet const *, unsigned32); extern unsigned32 delete_RealRegSet(RealRegSet *, unsigned32); extern bool intersect_RealRegSet(RealRegSet *a, RealRegSet const *b, RealRegSet const *c); extern void union_RealRegSet(RealRegSet *a, RealRegSet const *b, RealRegSet const *c); extern void difference_RealRegSet(RealRegSet *a, const RealRegSet *b, const RealRegSet *c); extern void map_RealRegSet(RealRegSet const *a, RealRegSet_MapFn *f, RealRegSet_MapArg *arg); extern void print_RealRegSet(RealRegSet const *a); RealRegSet const *globalregset(void); void avoidallocating(VRegnum); /* modifications to ALLOCATION_ORDER */ extern void regalloc_init(void); extern void regalloc_reinit(void); extern void regalloc_tidy(void); #endif /* end of regalloc.h */
stardot/ncc
cppfe/xsem.c
/* * xsem.c: semantic analysis phase of the C++ compiler * Copyright (C) Codemist Ltd, 1988-1992 * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Advanced RISC Machines Limited, 1991-1992, 1994 * SPDX-Licence-Identifier: Apache-2.0 * All rights reserved. */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include <string.h> /* for memset and strcmp */ #include "globals.h" #include "sem.h" #include "bind.h" #include "aetree.h" #include "builtin.h" #include "aeops.h" #include "store.h" #include "errors.h" #include "util.h" /* for padsize */ #include "simplify.h" #include "syn.h" /* for add_pendingfn() & recursing */ #define _SEM_H static Expr *mkfnap_cpp(Expr *e, ExprList **l, bool *curried, Expr** let, Expr **firstarg); static Expr *cpp_ptrcast(AEop op, Expr *e, TypeExpr *te, TypeExpr *tr, AEop h0t); static Expr *cpp_mkcast(AEop op, Expr **ep, TypeExpr *tr); static Expr *nullptr(TagBinder *cl); TypeExpr *lvalue_type(Expr *x); /* isaddressablelvalue?? */ static ExprList *exprlist_of_default_args(FormTypeList *d, int); static Binder *ovld_resolve_addr(Expr *e, BindList *bl); static Binder *ovld_resolve_addr_2(AEop, TypeExpr *desttype, BindList *bl, Binder *generic); static bool common_pointer_type(AEop op, TypeExpr *t1, Expr *e1, Expr **newe1, TypeExpr *t2, Expr *e2, Expr **newe2, TypeExpr **common); static bool common_reference_type(AEop op, TypeExpr *t1, Expr *e1, Expr **newe1, TypeExpr *t2, Expr *e2, Expr **newe2, TypeExpr **common); static bool call_dependency_type(TypeExpr *t, ScopeSaver tactuals); static bool call_dependency_val(Expr *e, ScopeSaver tactuals); static void sem_attempt_template_function(Binder *generic, Binder *specific); static bool is_comparable_specialization(TypeExpr *t1, TypeExpr *t2); static Binder *sem_instantiate_tmptfn(Binder *b, TypeExpr *bt, ExprList **l); #define ensurelvalue_s_invisible \ /* a more general version of s_integer ... */\ /* ... to replace that idea. */\ if (h0_(orig_(x)) == s_ctor) { x = orig_(x); break; } /* tidy! */\ /* taking the address of a t_ref behaves like s_content. */\ /* e.g. 'int &f(); ... return &f(); ... */\ if (h0_(princtype(typeofexpr(orig_(x)))) == t_ref) return e; #include "vargen.h" /* for vg_note_vtable() */ #include "sem.c" int env_size(Binder *b) { int i = 0; for (; b; b = bindcdr_(b)) i++; return i; } static Binder *ovld_resolve_addr(Expr *e, BindList *bl) { /* Taking the address of an ordinary or (possibly static) member fn. */ /* For fn 'f', we treat &A::f, &a->f (and, in value ctxt) A::f, a->f */ /* identically, returning type 't (A::*)(f())'. */ /* @@@ Well, at least we intend to! */ int len = length((List *) bl); if (h0_(e) == s_dot || h0_(e) == s_qualdot) e = exprdotmemfn_(e); if (h0_(e) != s_binder || (bl == NULL && bindactuals_(exb_(e)) == NULL && bindftlist_(exb_(e)) == NULL)) syserr("sem(odd ovld)"); switch (len) { case 0: { Binder *bspecific = NULL; if (bindactuals_(exb_(e)) != NULL) { ExprList *l = NULL; ExprList *tactuals = bindactuals_(exb_(e)); for (; tactuals; tactuals = cdr_(tactuals)) l = mkExprList(l, gentempbinder(typeofexpr(exprcar_(tactuals)))); l = (ExprList *)dreverse((List *)l); bspecific = sem_instantiate_tmptfn(exb_(e), typeofexpr(e), &l); } return (bspecific != NULL) ? bspecific : (cc_err(sem_err_addr_template, e), (Binder *)errornode); } case 1: /* The rationale is that all use of a overloaded fn name refers to the generic binder. Overload resolution is performed again when usage is known i.e. mkcast. */ { Binder *bspecific = bl->bindlistcar; binduses_(bspecific) |= u_referenced; bindstg_(bindstg_(bspecific) & b_impl ? realbinder_(bspecific) : bspecific) &= ~b_maybeinline; return bspecific; } default: return exb_(e); } } static Binder *ovld_resolve_addr_2(AEop op, TypeExpr *desttype, BindList *bl, Binder *generic) { Binder *bspecific = NULL; BindList *const origbl = bl; bool memtype = h0_(desttype) == t_coloncolon; if (op == s_cast && bl != NULL && bl->bindlistcdr == NULL && memtype == ((bindstg_(bl->bindlistcar) & b_memfna) != 0)) return bl->bindlistcar; if (memtype) desttype = typearg_(desttype); for (; bl != NULL; bl = bl->bindlistcdr) { bspecific = bl->bindlistcar; if ((memtype == ((bindstg_(bspecific) & b_memfna) != 0)) && equivtype(desttype, bindtype_(bspecific)) == 2) { binduses_(bspecific) |= u_referenced; bindstg_(bindstg_(bspecific) & b_impl ? realbinder_(bspecific) : bspecific) &= ~b_maybeinline; return bspecific; } } if (!(feature & FEATURE_CFRONT) || origbl->bindlistcdr != NULL) cc_rerr(sem_rerr_noncallsite_ovld, bspecific, generic); return bspecific; } TagBinder *isclassenumorref_type(TypeExpr *t) { t = princtype(t); if (h0_(t) == t_ref) t = princtype(typearg_(t)); return isclassorenumtype_(t) ? typespectagbind_(t) : 0; } Expr *thisify(Expr *e) { Binder *thisb = findbinding(thissym, NULL, LOCALSCOPES); if (thisb && h0_(thisb) == s_binder) { binduses_(thisb) |= u_referenced; if (h0_(e) == s_member || h0_(e) == s_dot) { ClassMember *member = (ClassMember *)e; return mkfieldselector(s_arrow, (Expr *)thisb, member); } } cc_err(sem_err_no_this_pntr); return errornode; } static Expr *nullptr(TagBinder *cl) { return mkintconst(ptrtotype_(tagbindtype_(cl)), TARGET_NULL_BITPATTERN, 0); } typedef struct BinderCopyList { struct BinderCopyList *cdr; Binder *orig; Binder *copy; } BinderCopyList; static BinderCopyList *append_bl_copy(SynBindList *bl, SynBindList **copy) { BinderCopyList *bl_copy = NULL; for (; bl != NULL; bl = bl->bindlistcdr) { Binder *b = bl->bindlistcar; bl_copy = binder_list3(bl_copy, b, gentempbinder(bindtype_(b))); *copy = mkSynBindList(*copy, bl_copy->copy); } return bl_copy; } static Expr *clone_expr_replace_exprtemps(Expr *e, BinderCopyList *bl_copy); static ExprList *clone_exprlist_replace_exprtemps(ExprList *l, BinderCopyList *bl_copy) { return (ExprList *) (l == NULL) ? NULL : syn_cons2(clone_exprlist_replace_exprtemps(l->cdr, bl_copy), clone_expr_replace_exprtemps(exprcar_(l), bl_copy)); } /* Modelled on globalize_expr(), perhaps a generic tree-walker needed? */ static Expr *clone_expr_replace_exprtemps(Expr *e, BinderCopyList *bl_copy) { AEop op; if (e == NULL || h0_(e) == s_error) syserr("Null or error expr can't be cloned"); switch (op = h0_(e)) { case s_fnapstruct: case s_fnap: return (Expr *)syn_list5(op, type_(e), exprfileline_(e), clone_expr_replace_exprtemps(arg1_(e), bl_copy), clone_exprlist_replace_exprtemps(exprfnargs_(e), bl_copy)); case s_binder: for (; bl_copy != NULL; bl_copy = bl_copy->cdr) if (bl_copy->orig == exb_(e)) return (Expr *)bl_copy->copy; return e; #ifdef EXTENSION_UNSIGNED_STRINGS case s_ustring: #endif case s_wstring: case s_string: case s_integer: case s_floatcon: return e; case s_let: return (Expr *)syn_list5(op, type_(e), exprfileline_(e), exprletbind_(e), clone_expr_replace_exprtemps(arg2_(e), bl_copy)); case s_dot: { bool is_bitfield = isbitfield_type(type_(e)); Expr *r = (Expr *)SynAlloc(is_bitfield ? 7L*sizeof(int32) : 5L*sizeof(int32)); h0_(r) = op; type_(r) = type_(e); exprfileline_(r) = exprfileline_(e); arg1_(r) = clone_expr_replace_exprtemps(arg1_(e), bl_copy); exprdotoff_(r) = exprdotoff_(e); if (is_bitfield) { exprbsize_(r) = exprbsize_(e); exprmsboff_(r) = exprmsboff_(e); } return r; } case s_cond: return (Expr *)syn_list6(op, type_(e), exprfileline_(e), clone_expr_replace_exprtemps(arg1_(e), bl_copy), clone_expr_replace_exprtemps(arg2_(e), bl_copy), clone_expr_replace_exprtemps(arg3_(e), bl_copy)); default: if (ismonad_(op) || op == s_cast) { return (Expr *)syn_list4(op, type_(e), exprfileline_(e), clone_expr_replace_exprtemps(arg1_(e), bl_copy)); } else if (isdiad_(op) || op == s_init #ifdef RANGECHECK_SUPPORTED || op == s_checknot #endif ) return (Expr *)syn_list5(op, type_(e), exprfileline_(e), clone_expr_replace_exprtemps(arg1_(e), bl_copy), clone_expr_replace_exprtemps(arg2_(e), bl_copy)); } syserr("clone_expr_replace_exprtemps(%p:%.lu)", e, op); return NULL; } static Expr *clone_default_expr(Expr *e) { BinderCopyList *bl; SynBindList *tmps = NULL; if (h0_(e) != s_let+s_qualified) return e; bl = append_bl_copy(exprletbind_(e), &tmps); if (h0_(arg2_(e)) != s_comma) syserr("comma expr expected"); add_to_saved_temps(tmps); add_expr_dtors(clone_expr_replace_exprtemps(arg2_(arg2_(e)), bl)); return clone_expr_replace_exprtemps(arg1_(arg2_(e)), bl); } /* @@@ Perhaps we should mark these args so they avoid a 2nd optimise! */ /* They certainly must not go via coerceunary (as type info may have */ /* been changed by previous optimise0()). */ static ExprList *exprlist_of_default_args(FormTypeList *d, int argindex) { ExprList *p = 0, *q = 0; for (; d != NULL; d = d->ftcdr, ++argindex) { Expr *e = d->ftdefault; if (e) { ExprList *t; set_fnap_arg(argindex); t = mkExprList1(clone_default_expr(e)); if (p) cdr_(q) = t, q = t; else p = q = t; } else if (p) syserr("non-contiguous default args!"); } return p; } static Expr *pointerkeepnull(Expr *ee, Expr *e, Binder *gen) { /* 'ee' contains 'gen' as a subexpression. Ensure that ee[e/gen] */ /* preserves NULL -- see [ES, p233]. */ /* @@@ arguably the 'if' here should be part of simplify.c where */ /* it could be of more general use. */ if (h0_(ee) == s_addrof) { Expr *x = arg1_(ee); while (h0_(x) == s_dot && exprdotoff_(x) == 0) x = arg1_(x); if (h0_(x) == s_content && arg1_(x) == (Expr *)gen) { arg1_(x) = e; return ee; } } return mklet(gen, typeofexpr(ee), mkbinary(s_comma, mkbinary(s_init, (Expr *)gen, e), mkcond((Expr *)gen, ee, lit_zero))); } /* AM memo: if just 1 v.fn then use fn itself (not table) for a base. */ /* AM memo: vfntab in 1st phys base can be extended to derived class. */ TypeExpr *core_type(TagBinder *base_tag) { ClassMember *p = tagbindmems_(base_tag); if (p != NULL && (attributes_(p) & CB_CORE)) return memtype_(p); else return tagbindtype_(base_tag); } TagBinder *core_class(TagBinder *cl) { ClassMember *l = tagbindmems_(cl); if (l && attributes_(l) & CB_CORE) { TypeExpr *t = princtype(memtype_(l)); if (!isclasstype_(t)) syserr("core_class $c", cl); cl = typespectagbind_(t); } return cl; } ClassMember *type_derived_from(TypeExpr *tbase, TypeExpr *tderived) { TypeExpr *ptbase = princtype(tbase), *ptderived = princtype(tderived); return isclasstype_(ptbase) && isclasstype_(ptderived) ? derived_from(typespectagbind_(ptbase), typespectagbind_(ptderived)) :0; } Expr *commacons(Expr *a, Expr *b) { /* of more general use (NULL == optional, errornode == error). */ return a == 0 ? b : b == 0 ? a : mkbinary(s_comma, a, b); } static Expr *mkcommalist_1(Expr *a, va_list ap) { /* NULL == terminator, errornode = error */ Expr *e = va_arg(ap, Expr *); if (e == NULL) return a; else { Expr *rest; if (h0_(e) == s_error) return errornode; rest = mkcommalist_1(e, ap); if (h0_(rest) == s_error) return errornode; return mkbinary(s_comma, a, rest); } } Expr *mkcommalist(Expr *a, ...) { /* NULL == terminator, errornode = error */ va_list ap; if (a == NULL) syserr("empty commaconsmany"); va_start(ap, a); if (h0_(a) == s_error) return errornode; return mkcommalist_1(a, ap); } #define mkopapcheck(b) \ if (h0_(b) != s_binder|| bindstg_(b) & bitofstg_(s_typedef)) \ syserr("non fn operator") #define prefer_tmptfn(a) (a != NULL && exprcar_(a) == NULL) static bool match_non_type_args(ScopeSaver tformals, ExprList *actuals) { for (; tformals && actuals; tformals = bindcdr_(tformals), actuals = actuals->cdr) if (bindconst_(tformals) && exprcar_(actuals) && (evaluate(bindconst_(tformals)) == evaluate(exprcar_(actuals)))) continue; else return NO; return (!tformals && !actuals) ? YES : NO; } static Binder *sem_instantiate_tmptfn(Binder *b, TypeExpr *bt, ExprList **l) { Binder *fb = NULL; BindList *tmpts; if ((tmpts = temp_reduce(NULL, *l, NULL, b)) != NULL) { Binder *ftemp = tmpts->bindlistcar; TypeExpr *t; BindList *bl; Symstr *sv; bool has_failed = NO; ScopeSaver env = bindformals_(ftemp); t = type_deduction(bindtype_(ftemp), *l, bindactuals_(b), &env, NO, &has_failed); if (bindsym_(ftemp) == currentfunction.symstr) { /* Not really an instance if the call is made inside itself. It goes on the typeovldlist_ nonetheless for parsing purpose. Of course, template fn can't be code generated! */ add_instance(ftemp, &typeovldlist_(bt), NO); has_failed = YES; } /* Is there already a suitable one around? Non-deduced types are the best.*/ if (!prefer_tmptfn(bindactuals_(b))) for (bl = typeovldlist_(bt); bl && !has_failed; bl = bl->bindlistcdr) if ((bindenv_(bl->bindlistcar) == NULL) && !((bindstg_(bl->bindlistcar) & b_undef) && !(bindstg_(ftemp) & b_undef)) && equivtype(t, bindtype_(bl->bindlistcar)) && (bindactuals_(b) == NULL || match_non_type_args(bindformals_(bl->bindlistcar), bindactuals_(b)))) has_failed = YES; for (bl = bindinstances_(ftemp); bl && !has_failed; bl = bl->bindlistcdr) if (equivtype(t, bindtype_(bl->bindlistcar)) && !((bindstg_(bl->bindlistcar) & b_undef) && !(bindstg_(ftemp) & b_undef)) && (bindactuals_(b) == NULL || match_non_type_args(bindformals_(bl->bindlistcar), bindactuals_(b)))) { has_failed = YES; /* pretends it's failed */ fb = bl->bindlistcar; } if (!has_failed) { Binder *fbind = NULL; Symstr *declname; binduses_(ftemp) |= u_referenced; fixup_template_arg_type(t, env); sv = ovld_tmptfn_instance_name(bindsym_(ftemp), env); declname = ovld_instance_name(sv, t); for (bl = typeovldlist_(bt); bl; bl = bl->bindlistcdr) if (bindsym_(bl->bindlistcar) == declname) { fbind = bl->bindlistcar; break; } if (!fbind) { env = globalize_env(env); t = globalize_typeexpr(t); fixup_template_arg_type(t, env); fb = fbind = instate_declaration(mkDeclRhsList(declname, t, killstgacc_(bindstg_(ftemp))), TOPLEVEL|INSTANCE); attributes_(fbind) |= attributes_(ftemp); /* @@@ check temp type and non-type args are not extern */ bindstg_(fbind) |= b_undef; bindenv_(fbind) = (!prefer_tmptfn(bindactuals_(b))) ? globalize_template_arg_binders(env, bindactuals_(b)) : env; add_instance(fbind, &typeovldlist_(bt), NO); add_instance(fbind, &bindinstances_(ftemp), YES); if (bindstg_(ftemp) & (b_memfna+b_memfns)) { TagBinder *parent = bindparent_(ftemp); Binder *btop; SET_BITMAP stg; DeclRhsList decl; decl.declname = ovld_add_memclass(declname, parent, (bindstg_(ftemp) & b_memfns) != 0); stg = killstgacc_(bindstg_(ftemp)); if (stg & bitofstg_(s_static)) stg = (stg & ~bitofstg_(s_static))|bitofstg_(s_extern); decl.declstg = stg; decl.decltype = (stg & b_memfna) ? memfn_realtype(t, parent) : t; btop = instate_declaration(&decl, TOPLEVEL); bindstg_(fbind) |= b_impl; bindstg_(btop) |= b_undef; bindenv_(btop) = bindenv_(fbind); realbinder_(fbind) = btop; fbind = btop; } } else { fb = fbind; if (realbinder_(fbind) != NULL) fbind = realbinder_(fbind); if (!bindenv_(fb)) bindenv_(fb) = globalize_env(env); parameter_names_transfer(typefnargs_(t), typefnargs_(bindtype_(fb))); } if (!contains_typevars(bindtype_(fbind)) && (bindstg_(fbind) & b_undef) && !(bindstg_(ftemp) & b_undef)) { bool ismemtemp = (bindstg_(ftemp) & (b_memfns+b_memfna)) != 0; /* OK since overload resolution always chooses the exact match. */ if (debugging(DEBUG_TEMPLATE)) cc_msg("instantiate $r -> $r\n", bindsym_(b), sv); add_pendingfn(ismemtemp ? bindsym_(fbind) : bindsym_(b), ismemtemp ? NULL : sv, globalize_typeexpr_no_default_arg_vals(bindtype_(fb)), (bindstg_(fbind)&~b_undef), bindparent_(ftemp), NULL, bindtext_(ftemp), bindenv_(fbind), YES); bindstg_(fb) &= ~b_undef; } } } bindactuals_(b) = NULL; return fb; } static Expr *mkfnap_cpp(Expr *e, ExprList **l, bool *curried, Expr **let_, Expr **firstarg) { Binder *thisb = 0; bool validobj = 0; /* Rationale: if we have a s_dot or s_dotstar (s_arrow/s_arrowstar */ /* have already gone) which gives a fn value (impossible in C) */ /* then we have to add its LHS as a *potential* first arg for overload */ /* resolution. Potential because it only applies to non-static memfns. */ /* We also need to do this for 'Binder's (an implicit thisify() if */ /* and only if there is a non-static memfn). */ /* We need to do this before coerceunary() can moan about unresolvable */ /* overloadings (note this is OK because no refs to fns). */ Expr *let = 0; ExprList *ll = *l, *let_ll = 0; /* We need a let to avoid double side->effects when making virtual */ /* function calls because p->vf() will become (*(p + n)+ m)(p). But we */ /* don't know if the function is virtual until after overload */ /* resolution for which we need an argument list. So we make the */ /* argument list with (let_ll) and without (ll) the let and choose */ /* whether or not to use the let down below. We could always use the */ /* let but the temporary elimination scheme in mkopap is confused by */ /* it. */ Expr *ee = skip_invisible(e); bool may_be_virtual = h0_(ee) != s_qualdot; bool trivialfirstarg = NO; bool use_corefn = NO; /* Needed in C++ - A+B may generate an invisible node for, */ /* for example, A.operator+(B); also conversion fns... */ *curried = NO; *let_ = 0; if ((h0_(ee) == s_dot || h0_(ee) == s_qualdot) && (h0_(type_(ee)) == t_ovld || h0_(type_(ee)) == t_fnap)) { /* C++ member function (e.g. explicit 'this') */ /* beware: vbase members maybe unrooted via a vbase ptr */ if (is_unrooted(arg1_(ee)) || (h0_(arg1_(ee)) == s_content && is_unrooted(arg1_(arg1_(ee))))) /* just A::f() rather than a.A::f() */ e = ee = exprdotmemfn_(ee); else { Expr *thisobj = arg1_(ee); TypeExpr *pt = typeofexpr(thisobj); bool is_class = isclasstype_(princtype(pt)); TypeExpr *bt = ptrtotype_(pt); Expr *thisptr = is_class ? mkaddr(thisobj) : mkunary(s_addrof, thisobj); Binder *tempthisb = gentempbinder(bt); validobj = 1; pt = princtype(pt); if (is_class && (tagbindbits_(typespectagbind_(pt)) & TB_CORE)) use_corefn = YES; ll = mkExprList(*l, thisptr); let = mklet(tempthisb, bt, mkbinary(s_init, (Expr *)tempthisb, thisptr)); let_ll = mkExprList(*l, tempthisb); if (h0_(thisobj) == s_binder) bindstg_((exb_(thisobj))) |= b_addrof|u_referenced; e = exprdotmemfn_(ee); /* s_binder of (generic) memfn. */ /* make an s_invisible node? */ } } if (h0_(ee) == s_binder && bindstg_(exb_(ee)) & b_fnconst) { /* C++ member function (with implicit 'this'). */ /* Invent this->f() or NULL->f() (in static memfn), then */ /* moan about NULL if f is b_memfna. */ TagBinder *cl = bindparent_(exb_(ee)); if (cl) { thisb = findbinding(thissym, NULL, LOCALSCOPES); if (thisb == NULL || !derived_fromeq(cl, typespectagbind_(typearg_(bindtype_(thisb))))) /* potential error (unless static memfn calls same). */ ll = mkExprList(*l, nullptr(cl)); else if (h0_(thisb) == s_binder) { ll = mkExprList(*l, (Expr *)thisb), validobj = 1; } else syserr("mkfnap(thisb)"); /* save unnecessary s_comma node in a fairly common case */ trivialfirstarg = YES; } } if (h0_(ee) == s_dotstar) /* see [ES, p71] */ { Expr *thisobj = arg1_(ee); validobj = 1; *l = ll = mkExprList(*l, mkunary(s_addrof, thisobj)); e = arg2_(ee); *curried = 1; } /* The placing of the next line is tentative --- we should really */ /* do the pre-overloading-resolution coercions on args (things like */ /* array->pointer but not char->int) before it... */ /* @@@ well, what about "int v[10]; void f(int (&v)[10]); ... f(v);"? */ /* Also, given "ovldfn(1)" valid, is "(*ovldfn)(1)" or "(&ovldfn)(1)"? */ else if (h0_(e) == s_binder) { Binder *b = exb_(e), *b2; TypeExpr *bt = princtype(bindtype_(b)); if (h0_(bt) == t_ovld || h0_(bt) == t_fnap) { bool call_is_virtual; ExprList *arglist = *l; /* An arg with a dependent type or previous error indicates a no-call. */ for (; arglist; arglist = cdr_(arglist)) if (is_dependent_type(typeofexpr(exprcar_(arglist))) || h0_(exprcar_(arglist)) == s_error) return errornode; /* An actual that's a s_evalerror or s_error indicates a no-call */ for (arglist = bindactuals_(b); arglist; arglist = cdr_(arglist)) { Expr *e = exprcar_(arglist); if (e && (h0_(e) == s_evalerror || h0_(e) == s_error)) return errornode; } if (h0_(bt) == t_ovld) { Binder *tmpt_bspecific = sem_instantiate_tmptfn(b, bt, l); b = (tmpt_bspecific) ? tmpt_bspecific : ovld_resolve(b, typeovldlist_(bt), *l, ll, NO); if (h0_(b) == s_error) return errornode; } if ((bindstg_(b) & b_undef) && !contains_typevars(bindtype_(b))) { if (bindparent_(b) != NULL) { if (bindstg_(realbinder_(b)) & b_undef) syn_attempt_template_memfn(exb_(e), b); else bindstg_(b) &= ~b_undef; } else sem_attempt_template_function(exb_(e), b); } /* here we should check access rights to the member before indirecting. */ b2 = (bindstg_(b) & b_impl) ? realbinder_(b) : b; /* @@@ are vfns really REFERENCED here? */ binduses_(b2) |= u_referenced; if (use_corefn && (attributes_(b2) & CB_HASCOREFN)) b2 = realbinder_(b2); if ((bindstg_(b2) & STGBITS) == 0) syserr("mkfnap(bindstg %lx)\n", bindstg_(b2)); call_is_virtual = may_be_virtual && (bindstg_(b) & bitofstg_(s_virtual)); if (bindstg_(b) & b_memfna) { if (call_is_virtual && let) { ll = let_ll; *let_ = let; } *l = ll; /* implicit first arg for 'this' */ if (!validobj) /* see thisify(). */ cc_err(sem_err_no_this_pntr2, e); if (thisb) binduses_(thisb) |= u_referenced; } if (call_is_virtual) { TagBinder *tb = bindparent_(b); Binder *thisvtab = findbinding(vtabsym, tb, INCLASSONLY); Expr *lv = exprcar_(*l); TypeExpr *te = typeofexpr(lv); TypeExpr *ttb = tagbindtype_(tb); TypeExpr *thist = indexable(te) ? ptrtotype_(ttb) : ttb; Expr *vtab = mkfieldselector(s_arrow, mkcast(s_cast, lv, (bindstg_(thisvtab) & bitofstg_(s_typedef)) ? bindtype_(thisvtab) : thist), (ClassMember *)vtabsym); if (!(suppress & D_CFRONTCALLER)) cc_warn(sem_warn_virtual, b); #ifdef TARGET_HAS_DATA_VTABLES if (target_has_data_vtables) { e = mk_expr1(s_cast, ptrtotype_(bindtype_(b2)), mk_expr1(s_content, ptrtotype_(te_int), mk_expr2(s_plus, type_(vtab), vtab, mkintconst(te_int, TARGET_VTAB_ELTSIZE*bindxx_(b2), 0)))); } else #endif { e = mk_expr1(s_cast, ptrtotype_(bindtype_(b2)), mk_expr2(s_plus, type_(vtab), vtab, mkintconst(te_int, TARGET_VTAB_ELTSIZE*bindxx_(b2), 0))); } e = mkinvisible(type_(e), (Expr *)b2, e); } else { bindstg_(b2) &= ~b_maybeinline; e = (Expr *)b2; } } if (!trivialfirstarg && *l != ll) *firstarg = exprcar_(ll); } return e; } /* mkopap() applies an operator. Binary operators need to be */ /* simultaneously overload resolved against in-scope diadic functions */ /* and monadic member functions. */ /* It returns 1. a s_fnap node, 2. an errornode or 3. NULL, the last */ /* indicating no resolution possible (for operators like '&' '=', ',' */ /* which have predefined meaning on structs if not hidden. */ Expr *mkopap(AEop op, TagBinder *cla, Expr *a, ExprList *l) { Symstr *opname = op == s_init ? ctorsym : operator_name(op); Binder *b1 = op == s_init ? 0 : findbinding(opname, NULL, FB_LOCALS+FB_GLOBAL); Binder *b2 = (cla == NULL || !isclasstagbinder_(cla)) ? NULL : findbinding(opname, cla, (op == s_assign || op == s_init) ? INCLASSONLY : INDERIVATION); ExprList *ll = mkExprList(l, a); int nargs = length((List *)ll); List *candidates = NULL; if (b1) { mkopapcheck(b1); (void)sem_instantiate_tmptfn(b1, bindtype_(b1), &ll); candidates = mk_candidates(typeovldlist_(bindtype_(b1)), nargs, 0, candidates); } if (b2) { mkopapcheck(b2); /* @@@ b2 is the generic, needs a specific for syn_attempt_template_memfn() */ candidates = mk_candidates(typeovldlist_(bindtype_(b2)), nargs, 0, candidates); } switch (op) { case s_fnap: /* TEMPORARILY exclude fnaps... */ case s_init: case s_assign: case s_comma: case s_addrof: /* no built-in operators... */ break; default: candidates = mk_operator_candidates(op, typeofexpr(a), (l == 0) ? 0 : typeofexpr(exprcar_(l)), candidates); } if (candidates == 0) return 0; { Binder bb, *b; bb.h0 = op; bb.bindparent = cla; b = ovld_reduce(&bb, candidates, l, ll); if (b == 0) { if (op == s_assign && cla != 0 && (tagbindbits_(cla) & TB_NEEDSOPEQ)) { cc_err(sem_err_assign_ovld, cla); return errornode; } return 0; } if (h0_(b) == s_error) return errornode; if (h0_(b) == op) { h0_(b) = s_operator; return (Expr *)b; } if (b->bindparent == 0) /* not a class member */ return mkfnap((Expr *)b1, ll); else { Expr *aa = 0; if (op == s_init) /* lose const/volatile qualification for 'this' arg to s_init ctors... */ /* if 'a' has type (<maybequalified> T *), cast to (<unqualified> T *); */ /* otherwise make *((<unqualified> T *)&a)... */ { TypeExpr *pta = princtype(typeofexpr(a)); TypeExpr *pte = h0_(pta) != t_content ? mkqualifiedtype_1(pta, 0, bitoftype_(s_const)) : princtype(typearg_(pta)); Expr *e = mkcast(s_cast|s_qualified, h0_(pta) == t_content ? a : mkunary(s_addrof, a), ptrtotype_(pte)); aa = e; a = h0_(pta) == t_content ? e : mkunary(s_content, e); } a = mkfnap(mkfieldselector(s_dot, a, b), l); /* /* this no longer works, 'cause mkfnap now returns a s_let node for */ /* member function calls. I can't quite bring myself to reanimate the */ /* hack -- will think about the problem instead. */ if (op == s_init && nargs == 2 && h0_(a) == s_fnap) /* Here is a (generated) copy ctor; eliminate both the call and the */ /* temp if (and only if) it is copying from a generated temp. */ /* Effectively, cctor(&x, &(ctor(temp, y), temp)) ==> ctor(&x,y) */ { ExprList *args = (ExprList *)arg2_(a); Expr *init = exprcar_(cdr_(args)); if (h0_(init) == s_cast && h0_(init = skip_invisible_or_cast(arg1_(init))) == s_addrof && h0_(init = skip_invisible_or_cast(arg1_(init))) == s_comma && h0_(skip_invisible_or_cast(arg1_(init))) == s_fnap) { Expr *e = skip_invisible_or_cast(arg1_(init)); Binder *t = exb_(arg2_(init)); if (equivtype(bindtype_(t), typearg_(typeofexpr(aa))) == 2) if (killnexprtemp(t)) return mkfnap(arg1_(e), mkExprList(cdr_(exprfnargs_(e)), aa)); } } return a; } } } Expr *user_conversion(Expr *e, TagBinder *cl, TypeExpr *t) { Binder *b; /* enums don't have user conversions */ if (cl == 0 || !isclasstagbinder_(cl)) return e; b = findbinding(conversion_name(t), cl, INDERIVATION); if (b == 0) { cc_rerr("No conversion to type $t in $c", t, cl); return errornode; } return mkfnap(mkfieldselector(s_dot, e, b), /* NOARGS */0); } /* Cfront allows things like 'T* t; void** p = &t;' This checks if */ /* Cfront allows implicit casting from ptr-to-te to a ptr-to-tr. */ bool cfront_allows_pointercast(TypeExpr *te, TypeExpr *tr) { if (isvoidtype(tr)) return YES; else return h0_(te) == t_content && h0_(tr) == t_content && cfront_allows_pointercast(typearg_(te), typearg_(tr)); } static Expr *cpp_ptrcast(AEop op, Expr *e, TypeExpr *te, TypeExpr *tr, AEop h0t) { /* Here we have a cast from pointer-to-te to a pointer-to-tr. */ /* te and tr may both be non-pruned. Return a suitable Expr (which */ /* in C will always be 'e' but may be e+/-delta in C++). */ /* Moan while doing so for unsuitable implicit casts. */ /* The Oct 88 draft clarifies that void pointers ARE required */ /* to respect const/volatile qualification too. */ int err = op != s_cast; /* @@@ We need to enable EXPLICIT (and implicit with error msg) casts */ /* from base type to (uniquely) derived type. */ /* The following code allows casts from derived type to unique base. */ TypeExpr *tep = princtype(te), *trp = princtype(tr); TagBinder *teb = 0; TagBinder *trb = 0; ClassMember *basemem = 0; bool is_ptrtomem = (h0_(tep) == t_coloncolon && h0_(trp) == t_coloncolon); SET_BITMAP q = 0; if ((isclasstype_(tep) && isclasstype_(trp)) || is_ptrtomem) { teb = core_class(typespectagbind_(tep)); trb = core_class(typespectagbind_(trp)); } /* Allow a pointer to CORE type to cast to pointer to its owning class: */ /* This code may be temporary! */ if (teb && trb && teb == trb) { /* always 0 offset, so 'e' unchanged. */ if (err && (q = qualifiers_lost(te,tr)) == 0) err = 0; } else if (teb && trb && !is_ptrtomem && (basemem = derived_from(trb, teb)) != 0) { /* Assert: (attributes_(basemem) & (CB_BASE|CB_VBPTR)) != 0 */ /* Now check access by looking up the member... */ path_to_member((ClassMember *)memsv_(basemem), typespectagbind_(tep), INDERIVATION); if (!accessOK) diagnose_access(bindsym_(typespectagbind_(trp)), typespectagbind_(tep)); { Binder *gen = 0; /* op == s_this indicates virtual function invocation. There's no point */ /* keeping p==0, because if p==0 we can't locate the vtable anyway... */ Expr *g = h0t == t_ref || op == s_this ? e : (Expr *)(gen = gentempbinder(typeofexpr(e))); Expr *ee = mkfieldselector(s_arrow, g, basemem); if (h0_(memtype_(basemem)) != t_content) ee = mkaddr(ee); e = gen == 0 ? ee : pointerkeepnull(ee,e,gen); /* @@@ note this cannot affect qualifiers (no class A: const B {}). */ /* Hmm, what about "typedef class X {} const B; class A:B {};"? */ } if (err && (q = qualifiers_lost(te,tr)) == 0) err = 0; } else if (teb && trb && (basemem = derived_from(teb, trb)) != 0) { TypeExpr *tt = (is_ptrtomem) ? tagbindtype_(typespectagbind_(trp)) : tr; Expr *n = mkunary(s_content, mkintconst(ptrtotype_(tt), TARGET_NULL_BITPATTERN, 0)); Expr *f = mkfieldselector(s_dot, n, basemem); int32 off = 0; /* BEWARE: relies on form of result of mkfieldselector(). */ if (h0_(memtype_(basemem)) == t_content) f = mkunary(s_content,f); /* so 'f' is now an expression of type te. */ if (err) err = (is_ptrtomem) ? 0 : 2; if (debugging(DEBUG_SYN)) cc_msg("cast-to-derived: "), pr_expr_nl(f); if (!is_ptrtomem || h0_(tep) != t_fnap) for (;;) { if (f == n) { Expr *ee = mk_expr2((is_ptrtomem) ? s_plus : s_minus, ptrtotype_(tr), e, mkintconst(te_int, off, 0)); if (h0t != t_ref && off != 0) { if (is_ptrtomem) e = ee; else { Binder *gen = gentempbinder(typeofexpr(e)); arg1_(ee) = (Expr *)gen; e = mklet(gen, type_(ee), mkbinary(s_comma, mkbinary(s_init, (Expr *)gen, e), mkcond((Expr *)gen, ee, lit_zero))); } } break; } else if (h0_(f) == s_dot) { off += exprdotoff_(f); f = arg1_(f); } else { cc_rerr(sem_rerr_cast_dtype_from_vbase); err = 0; /* avoid repeated error messages. */ break; } } } else if ((feature & FEATURE_CFRONT) && op != s_cast && h0t == t_content && !qualfree_equivtype(te, tr) && cfront_allows_pointercast(te, tr)) err = 0; else { if (teb && trb && (!(tagbindbits_(teb) & TB_DEFD) || !(tagbindbits_(trb) & TB_DEFD))) cc_warn(xsem_warn_cast_undef_struct, trb, teb); return pointercast(op, e, te, tr); /* same as for C */ } if (err && !(suppress & D_IMPLICITCAST)) { if (err & 2) cc_rerr(sem_rerr_implicit_cast1, op); else cc_rerr(sem_rerr_implicit_cast5, op, q); } return e; } static bool common_pointer_type(AEop op, TypeExpr *t1, Expr *e1, Expr **newe1, TypeExpr *t2, Expr *e2, Expr **newe2, TypeExpr **common) /* Find a common pointer type for t1 and t2 which must be pointers to */ /* (possibly qualified) class types, if any. If found return newe1 and */ /* newe2 as the cast expressions as well as the common type chosen (t1 */ /* or t2). */ /* e1 == *newe1, e2 == *newe2, t1 == *common, t2 == *common are ok. */ { TypeExpr *t1x = typearg_(princtype(t1)), *t2x = typearg_(princtype(t2)); if (type_derived_from(t1x, t2x)) { Expr *newe = cpp_ptrcast(op, e2, t2x, t1x, t_content); *newe1 = e1; *newe2 = newe; *common = h0_(*newe2) == s_error ? 0 : t1; return YES; } if (type_derived_from(t2x, t1x)) { Expr *newe = cpp_ptrcast(op, e1, t1x, t2x, t_content); *newe1 = newe; *newe2 = e2; *common = h0_(newe) == s_error ? 0 : t2; return YES; } return NO; } static bool common_reference_type(AEop op, TypeExpr *t1, Expr *e1, Expr **newe1, TypeExpr *t2, Expr *e2, Expr **newe2, TypeExpr **common) /* Find a common reference type for t1 and t2 which must be */ /* (possibly qualified) class types, if any. If found return newe1 and */ /* newe2 as the cast expressions as well as the common type chosen (t1 */ /* or t2). */ /* e1 == *newe1, e2 == *newe2, t1 == *common, t2 == *common are ok. */ { if (type_derived_from(t1, t2)) { TypeExpr* reft1 = mk_typeexpr1(t_ref, t1, 0); Expr *newe = cpp_mkcast(op, &e2, reft1); if (h0_(newe) == s_error) return NO; *newe1 = e1; *newe2 = newe; *common = reft1; return YES; } if (type_derived_from(t2, t1)) { TypeExpr* reft2 = mk_typeexpr1(t_ref, t2, 0); Expr *newe = cpp_mkcast(op, &e1, reft2); if (h0_(newe) == s_error) return NO; *newe1 = newe; *newe2 = e2; *common = reft2; return YES; } return NO; } /* Handle casts involving refs, constructors and conversion fns. */ /* Return non-0 to indicate all done; 0 to indicate that work remains */ /* for sem.c::mkcast(), our caller. */ static Expr *cpp_mkcast(AEop op, Expr **ep, TypeExpr *tr) { Expr *e = *ep; TypeExpr *x = princtype(tr); TypeExpr *te = typeofexpr(e); TypeExpr *y = princtype(te); if (h0_(x) == t_unknown) return (op == s_cast)? mk_expr1(s_cast, tr, coerceunary(e)) : coerceunary_2(e, COERCE_ASSIGN); if (h0_(y) == t_unknown) return mk_expr1(s_cast, tr, coerceunary(e)); if (h0_(x) == t_ref) { /* don't coerceunary yet, e.g. int a[5], (&x)[5] = a. */ /* are refs to fns/arrays allowed? Unwritable! */ /* but should we ref->content? */ TypeExpr *xr = typearg_(x); /* Rationale: explicit casts to refs share an lvalue, but implicit */ /* ones do not unless types match. See [ES, p69, p155]. Whee(p). */ /* The text on p154 differs from the examples: we allow a const ref */ /* to refer to a non-const lvalue (as per 'rcd' in example). */ TypeExpr *lvt = lvalue_type(e); Binder *conv; bool is_ref_compatible_type = NO; if (lvt != NULL && (op == s_cast || #ifdef NEVER /* consider: volatile int i; const int &ri = i; temp or not? */ qualifier_subset(lvt, xr) && #endif ((is_ref_compatible_type = (qualfree_equivtype(lvt, xr) || type_derived_from(xr, lvt))) || h0_(xr) == t_fnap))) /* The t_fnap case allows int f(); int (&g)() = f; */ /* @@@ The following is sordid: lvalue_type considers all class values */ /* to be ref-lvalues (q.v.) since they all have addresses */ /* (@@@ modulo one-word structs) and rely on struct manipulation code */ /* to have inserted temp locations were needed. This seems necessary */ /* so that complex x = sqrt(z); can make a ref to the result of sqrt */ /* which can be passed to the copy constructor. Hmmm. Standard?? */ /* mkaddr() below skips the ensurelvalue test in mkunary(s_addrof). */ /* It is not clear whether complex(3,4) is an lvalue. */ /* @@@ also maybe non optimal, given 'class D:A, B { ... };'. */ /* (D *) => (B *) requires a NULL test, but (D &) => (B &) doesn't! */ /* (pointercast() leaves type unchanged, but does any addition.) */ { Expr *ea; TypeExpr *tea; if (isclasstype_(lvt)) { if (op == s_init && (!is_ref_compatible_type || (h0_(e) == s_invisible && h0_(orig_(e)) == s_ctor))) { TypeExpr *plvt = ptrtotype_(lvt); Binder *b = genreftemp(lvt); ea = mkopap(s_init, typespectagbind_(lvt), (Expr *)b, mkExprList1(e)); ea = mk_expr2(s_comma, plvt, ea, mk_expr1(s_addrof, plvt, (Expr *)b)); } else { ea = mkaddr(coerceunary(e)); if (h0_(e) == s_binder) bindstg_((exb_(e))) |= b_addrof|u_referenced; } } else ea = mkunary(s_addrof, e); tea = princtype(type_(ea)); /* differs from lvt if t_ovld->t_fnap. */ if (h0_(tea) != t_content) syserr("mkcast(ref)"); e = cpp_ptrcast(op, ea, typearg_(tea), xr, t_ref); } else if (op != s_cast && isclasstype_(y) && (conv = class_has_conversion(typespectagbind_(y), x, YES)) != 0) { e = mkfnap(mkfieldselector(s_dot, e, conv), 0); return mkcast(op, e, tr); } else { Binder *b = (op == s_init) ? genreftemp(xr) : genexprtemp(xr); TypeExpr *pxr = ptrtotype_(xr); if (!(qualifiersoftype(xr) & bitoftype_(s_const))) { cc_rerr(sem_rerr_valcasttoref, op); return errornode; /* @@@ explicit/implicit casts differ? */ /* beware refs to fns/arrays -- will syserr!? */ } { TypeExpr *pt = princtype(xr); TagBinder *cla = isclasstype_(pt) ? typespectagbind_(pt) : 0; if (cla != 0) pt = primtype2_( typespecmap_(pt) & ~bitoftype_(s_const), cla); e = mkcast(s_init, e, pt); if (cla == NULL) { /* the following call caused tempbinders to be introduced into scope such as s_fnap. Bad. But its purpose maybe related to the comment below. */ e = mkbinary(s_init, (Expr *)b, e); } else e = mkopap(s_init, cla, (Expr *)b, mkExprList1(e)); if (e == 0) /* @@@ FW found this apprehensive, no diagnostics ehh!!! */ e = errornode; else if (e != errornode) { e = mk_expr2(s_comma, pxr, e, mk_expr1(s_addrof, pxr, (Expr *)b)); bindstg_(b) |= b_addrof|u_referenced; } } #if 0 e = mkcast(s_init, e, xr); if (e != errornode) e = mk_expr2(s_comma, pxr, e, mk_expr1(s_addrof, pxr, (Expr *)b)); #endif } /* The above Expr 'e' always has pointer type -- cast to ref type: */ return h0_(e) == s_error ? e : mk_expr1(s_cast, tr, e); } if (isvoidtype(x)) { if (h0_(y) == t_ovld || (h0_(y) == t_content && h0_(typearg_(y)) == t_ovld)) { cc_rerr(sem_rerr_noncallsite_ovld, NULL, exb_(e)); return errornode; } else return 0 /* handle as in C */; } if (h0_(y) == t_ref) { TypeExpr *tt = princtype(typearg_(y)); if (isclasstype_(tt)) /* ref class may involve conversions... */ { e = mkinvisible(typearg_(y), e, mk_expr1(s_content,typearg_(y),e)); te = typearg_(y); y = tt; } } if (h0_(y) == t_ovld || (h0_(y) == t_content && h0_(typearg_(y)) == t_ovld)) { Binder *generic = NULL; Binder *specific; if (h0_(e) == s_addrof) generic = exb_(arg1_(e)); else if (h0_(e) == s_dot || h0_(e) == s_qualdot) generic = exb_(arg2_(e)); else if (h0_(e) == s_binder) generic = exb_(e); if (generic == NULL || h0_(generic) != s_binder) syserr("cpp_mkcast odd t_ovld expr"); if (h0_(y) == t_content && h0_(x) != t_content) syserr("odd desttype for ovld fn"); specific = ovld_resolve_addr_2(op, (h0_(x) == t_content) ? typearg_(x) : x, typeovldlist_(h0_(y) == t_content ? typearg_(y) : y), generic); if (specific == NULL) return errornode; if ((bindstg_(specific) & b_memfna) && h0_(e) != s_addrof) { if (feature & FEATURE_CFRONT) cc_warn(simplify_err_illegal_use_of_mem_fn, generic); else cc_rerr(simplify_err_illegal_use_of_mem_fn, generic); } e = mkaddr((Expr *)specific); if (op == s_cast) { *ep = e; return NULL; /* now handle as in 'C' */ } return e; } if (isclasstype_(x) && isclasstype_(y) && (core_class(typespectagbind_(x)) == core_class(typespectagbind_(y)) || derived_from(typespectagbind_(x), typespectagbind_(y)))) { if (typespectagbind_(x) == typespectagbind_(y)) /* identical class; handle as in C */ return 0; else if (h0_(e) == s_binder) { /* y is derived from tr, or core_class(x) is core_class(y) */ /* next line to handle: struct B {}; struct D : B {}; */ /* const D d; B b; b = d; */ Expr *ea; TypeExpr *tea; tr = mkqualifiedtype(tr, qualifiersoftype(typeofexpr(e))); ea = mkaddr(e); tea = princtype(type_(ea)); return mkunary(s_content, cpp_ptrcast(op, ea, typearg_(tea), tr, t_content)); } else { ClassMember *basemem = derived_from(typespectagbind_(x), typespectagbind_(y)); return (!basemem) ? e : mkfieldselector(s_dot, e, basemem); } } else { Binder *convfn = 0, *convctor = 0; if (isclasstype_(y)) convfn = class_has_conversion(typespectagbind_(y), x, YES); if (isclasstype_(x)) convctor = class_has_ctor(typespectagbind_(x), y, e, YES); if (convfn != 0 && convctor != 0) { cc_err(syn_err_ambiguous_user_defined_conv, typespectagbind_(y), typespectagbind_(x)); } if (convfn != 0) { e = mkfnap(mkfieldselector(s_dot, e, convfn), 0); return mkcast(op, e, tr); } else { if (convctor != 0) { /* @@@ LDS 28-Sep-94: The following has been done above, I believe, */ /* first by ref stripping and then by checking for the same tagbinder. */ /* if (qualfree_equivtype(x, typeofexpr(coerceunary_2(e, COERCE_ARG)))) */ /* goto same_as_C; */ TypeExpr *bt = primtype2_( typespecmap_(x) & ~bitoftype_(s_const), typespectagbind_(x)); Binder *b = genexprtemp(bt); Expr *init; /* beware the following line -- two deficiencies: 1. too much at */ /* run-time and doesn't alwyas require init. */ attributes_(b) |= A_DYNINIT; if (op != s_cast) { if (suppress & D_IMPLICITCTOR) xwarncount++; else /* see the discussion in [ES, p272] */ cc_warn(sem_warn_implicit_constructor, x); } init = mk_expr2(s_comma, bt, mkfnap(mkfieldselector(s_dot, (Expr *)b, convctor), mkExprList1(e)), (Expr *)b); return mkinvisible(tr, mk_expr1(s_ctor, tr, e), mkcast(op, init, tr)); } } } return 0; } /* Now stuff about constructors, first the virtual fn and base stuff... */ /* vfn_list() must keep in step with vtab_init(). */ static VfnList *vfn_list_1(TagBinder *cl, int32 n, int32 off, VfnList *vfl, TagBinder *derivation) { ClassMember *m; for (m = tagbindmems_(cl); m != NULL; m = memcdr_(m)) if (h0_(m) == s_binder && bindstg_(m) & bitofstg_(s_virtual)) /* Here, we really do want to search for the Symstr of the member */ /* not for the member, or we won't find the most-derived vfn. */ { Expr *e = path_to_member((ClassMember *)memsv_(m), derivation, INDERIVATION+FB_FNBINDER+FB_KEEPI); int32 thisoffset = off; Binder *b = exb_(((h0_(e) == s_invisible) ? (thisoffset += arg3i_(e), arg2_(e)) : e)); if (h0_(b) != s_binder) syserr("vfn $b not in class $b\n", m, derivation); if (bindstg_(b) & b_impl) b = realbinder_(b); /* @@@ we shouldn't use 'b' here but lookup for the nearest b in the */ /* derivation hierarchy. But what about multiple (virtual) paths? */ /* Oh, that's OK, use l-r algorithm (from vbase-init [ES])? */ if (debugging(DEBUG_BIND)) cc_msg("vfn $b/$c,%ld, thisoff=%ld\n", b, cl, n, thisoffset); vfl = mkVfnList(vfl, b, thisoffset); n--; } /* left-most vtable sharing wrecked the following ... if (n != 0) syserr("vtable count $c", cl); */ return vfl; } typedef List VtabList; typedef struct VtabElt VtabElt; struct VtabElt { TagBinder *cl; ClassMember *vtab; int32 offset; }; static VtabList *lmost_derived, *rest; #define mkVtabList(a,b) ((VtabList *)syn_list2(a,b)) #define mkVtabElt(a,b,c) ((int32 *)syn_list3(a,b,c)) static void vfn_list_r(TagBinder *cl, int32 off, TagBinder *derivation) { ClassMember *m = tagbindmems_(cl); bool done = NO; if (m == NULL) return; if (attributes_(m) & (CB_CORE|CB_BASE)) { vfn_list_r(typespectagbind_(princtype(memtype_(m))), off, derivation); m = memcdr_(m); } { ClassMember *tmp = m; for (; tmp != NULL; tmp = memcdr_(tmp)) { if (attributes_(tmp) & CB_VTAB) { lmost_derived = mkVtabList(lmost_derived, mkVtabElt(cl, tmp, off)); done = YES; break; } } } for (; m != NULL; m = memcdr_(m)) { TypeExpr *t = princtype(memtype_(m)); if (!is_datamember_(m)) continue; /* In the next lines it is important to calculate the vbase 'this' */ /* delta value from the base layout and not via vbase pointers (which */ /* would arise when using mkcast(base-pointer to derived-pointer). */ if (attributes_(m) & CB_VTAB && !done) /* i.e. vtabsym (for fgrep). */ { int32 off1 = off == OFFSET_UNSET || memwoff_(m) == OFFSET_UNSET ? OFFSET_UNSET : off + memwoff_(m); rest = mkVtabList(rest, mkVtabElt(cl, m, off1)); } else if (attributes_(m) & (CB_CORE|CB_VBASE|CB_BASE) && isclasstype_(t)) { int32 off1 = off == OFFSET_UNSET || memwoff_(m) == OFFSET_UNSET ? OFFSET_UNSET : off + memwoff_(m); vfn_list_r(typespectagbind_(t), off1, derivation); } } } /* vfn_list() collects a (reverse) list of the virtual functions and */ /* their deltas for a class 'cl'. 'e' is NULL and 'off' 0 initially. */ VfnList *vfn_list(TagBinder *cl) { VfnList *e = 0, *pe, *last; List *vp; lmost_derived = 0, rest = 0; vfn_list_r(cl, 0, cl); lmost_derived = (VtabList *)dreverse(lmost_derived); rest = (VtabList *)dreverse(rest); for (vp = lmost_derived; vp != 0; vp = vp->cdr) { VtabElt *tmp = (VtabElt *)car_(vp); e = vfn_list_1(tmp->cl, memvtablesize_(tmp->vtab), -tmp->offset, e, cl); } /* prefix preserving elimination of duplicates */ e = (VfnList*)dreverse((List *)e); for (last = pe = e; pe != 0; pe = pe->vfcdr) { VfnList *ppe; Symstr *sv = bindsym_(pe->vfmem); for (ppe = e; ppe != pe; ppe = ppe->vfcdr) if (bindsym_(ppe->vfmem) == sv && ppe->vfdelta == pe->vfdelta) break; if (ppe != pe) last->vfcdr = pe->vfcdr; else last = pe; } e = (VfnList *)dreverse((List *)e); for (vp = rest; vp != 0; vp = vp->cdr) { VtabElt *tmp = (VtabElt *)car_(vp); e = vfn_list_1(tmp->cl, memvtablesize_(tmp->vtab), -tmp->offset, e, cl); } /* do not refer to pure virtual fns, but catch calls through them... */ for (pe = e; pe != 0; pe = pe->vfcdr) { if (bindstg_(pe->vfmem) & b_purevirtual) pe->vfmem = cppsim.xpvfn; } return e; } /* assert: vta = (s_addrof type binder). */ /* vto is the offset into the virtual function table. */ /* (currently done in the order of left-most derivation, core and */ /* vbases) */ static Expr *vtab_init_1(TagBinder *cl, Expr *var, int32 off, Binder *vta, int32 *vto) { ClassMember *m = tagbindmems_(cl); Expr *e = NULL; if (debugging(DEBUG_BIND)) cc_msg("vtab($c+%ld, %ld)\n", cl, off, *vto); if (m == NULL) return e; if (attributes_(m) & (CB_CORE|CB_BASE)) { e = vtab_init_1(typespectagbind_(princtype(memtype_(m))), var, off, vta, vto); m = memcdr_(m); } { ClassMember *tmp = m; for (; tmp != NULL; tmp = memcdr_(tmp)) { if (attributes_(tmp) & CB_VTAB) { if (!(bindstg_(tmp) & bitofstg_(s_typedef))) { int32 off1 = off == OFFSET_UNSET || memwoff_(tmp) == OFFSET_UNSET ? OFFSET_UNSET : off + memwoff_(tmp); Expr *e1 = mk_expr2(s_assign, bindtype_(vta), mk_exprwdot(s_dot, bindtype_(vta), var, off1), mk_expr2(s_plus, bindtype_(vta), (Expr *)vta, mkintconst(te_int, TARGET_VTAB_ELTSIZE*(*vto), 0))); e = commacons(e, e1); } *vto += memvtablesize_(tmp); break; } } } for (; m != NULL; m = memcdr_(m)) { TypeExpr *t = princtype(memtype_(m)); if (!is_datamember_(m)) continue; if (attributes_(m) & (CB_VBASE|CB_BASE)) { int32 off1 = off == OFFSET_UNSET || memwoff_(m) == OFFSET_UNSET ? OFFSET_UNSET : off + memwoff_(m); if (!isclasstype_(t)) syserr("what sort of base $b is this?", m); e = commacons(e, vtab_init_1(typespectagbind_(t), var, off1, vta, vto)); } } return e; } static Binder *vtab_declare(Symstr *name) { DeclRhsList d; /* the 'decltype' values in the following are rather a lie... */ #ifndef TARGET_DATA_VTABLE TypeExprFnAux s; d.decltype = mkTypeExprfn(t_fnap, te_void, 0, 0, packTypeExprFnAux(s, 0, 0, 0, 0, 0)); /* NB: b_memfns forces a direct call instate_declaration_1() from */ /* instate_declaration_cpp(), with no further manging of name. */ d.declstg = bitofstg_(s_static) | b_undef | b_fnconst | b_memfns; /* soon to be COMMON,CODE on RISCOS. */ #else d.decltype = te_ulint; d.declstg = bitofstg_(s_static) | b_undef; #endif d.declname = name; declinit_(&d) = 0; return instate_declaration(&d, TOPLEVEL); } /* AM: I think the best way to organise this is to arrange each class */ /* which needs a vfntable (i.e. it, or one of its bases, has vfns) */ /* has a static member which is vtb below. */ Expr *vtab_init(TagBinder *cl, Expr *var) { Symstr *name; Binder *vtb, *vta; int32 vto = 0; Expr *evta; Expr *r; if (!(tagbindbits_(cl) & TB_HASVTABLE)) /* lift to callers? */ return 0; name = ovld_instance_name(vtabsym, tagbindtype_(cl)); vtb = bind_global_(name); /* nasty in this file! */ if (vtb == 0) vtb = vtab_declare(name); evta = mk_expr1(s_addrof, ptrtotype_(bindtype_(vtb)), (Expr *)vtb); vta = gentempbinder(type_(evta)); r = vtab_init_1(cl, var, 0, vta, &vto); if (r) r = mklet(vta, bindtype_(vta), commacons(mkbinary(s_assign, (Expr *)vta, evta), r)); if (vto == 0) syserr("empty vtable $c", cl); vg_note_vtable(cl, vto, bindsym_(vtb)); return r; } /* vbase_init_1() walks a class looking for virtual base pointer fields. */ /* On entry, 'var' is a side-effect-free object expression, which has */ /* a sub-object of class 'cl' at offset 'off'. 'e' points initially to */ /* the virtual base, but is extended to an assignment sequence: */ /* var.n1 = var.n2 = ... = var.nk = vbptr. */ /* On exit, e, now the augmented assignment sequence, is returned. */ /* Assert: At least one assignment MUST be generated by each call. */ static Expr *vbase_init_1(TagBinder *cl, Expr *var, int32 off, Expr *e) { ClassMember *m; for (m = tagbindmems_(cl); m != NULL; m = memcdr_(m)) { TypeExpr *t = princtype(memtype_(m)); if (!is_datamember_(m)) continue; /* @@@ beware: equivtype would fail for 'const' bases... */ if ((attributes_(m) & CB_VBPTR) && equivtype(t, type_(e))) { int32 off1 = off == OFFSET_UNSET || memwoff_(m) == OFFSET_UNSET ? OFFSET_UNSET : off + memwoff_(m); e = mk_expr2(s_assign, type_(e), mk_exprwdot(s_dot, type_(e), var, off1), e); } else if (attributes_(m) & (CB_CORE|CB_VBASE|CB_BASE) && isclasstype_(t)) { int32 off1 = off == OFFSET_UNSET || memwoff_(m) == OFFSET_UNSET ? OFFSET_UNSET : off + memwoff_(m); e = vbase_init_1(typespectagbind_(t), var, off1, e); } } return e; } /* On entry, 'var' is a side-effect-free expression (variable or content(e) */ /* with 'e' side-effect free) of class 'cl'. For each virtual base of */ /* 'cl' in turn, vbase_init() calls class vbase_init_1() to make a compound */ /* assignment expression initialising all pointers to that virtual base. */ /* If there is more than one virtual base, these compound assignments are */ /* collected via comma expressions to yield a single initialising Expr. */ Expr *vbase_init(TagBinder *cl, Expr *var) { Expr *e = NULL; ClassMember *m = tagbindmems_(cl); if (m != NULL && (attributes_(m) & CB_CORE)) { /* deal with vbase construction for each vbase pointer in turn */ for (m = memcdr_(m); m != NULL; m = memcdr_(m)) { if (!(attributes_(m) & CB_VBASE)) syserr("vbase_init($b, $r)", cl, memsv_(m)); e = commacons(e, vbase_init_1(cl, var, 0, mk_expr1(s_addrof, ptrtotype_(memtype_(m)), mk_exprwdot(s_dot, memtype_(m), var, memwoff_(m))))); } } return e; } #ifdef NEVER static Expr *virt_init_1(TagBinder *cl, Expr *var, int32 off) { /* Now scan for any non-base members (including non-base members */ /* of base members) which need initialising: */ Expr *e = 0; ClassMember *m; for (m = tagbindmems_(cl); m != NULL; m = memcdr_(m)) { TypeExpr *t = princtype(memtype_(m)); if (!is_datamember_(m)) continue; if (isclasstype_(t)) { TagBinder *cl2 = typespectagbind_(t); int32 off1 = off == OFFSET_UNSET || memwoff_(m) == OFFSET_UNSET ? OFFSET_UNSET : off + memwoff_(m); if (!(attributes_(m) & (CB_CORE|CB_VBASE|CB_BASE))) { Expr *v2 = mk_exprwdot(s_dot, t, var, off1); e = commacons(e, commacons(vbase_init(cl2, v2), vtab_init(cl2, v2))); } e = commacons(e, virt_init_1(cl2, var, off1)); } } return e; } static Expr *virt_init(TagBinder *cl, Expr *var) { return commacons(commacons(vbase_init(cl, var), vtab_init(cl, var)), virt_init_1(cl, var, 0)); } #endif extern bool typehasctor(TypeExpr *t) { t = princtype(t); if (isclasstype_(t) && (tagbindbits_(typespectagbind_(t)) & TB_NEEDSCTOR || (tagbindbits_(typespectagbind_(t)) & TB_TEMPLATE && findbinding(ctorsym, typespectagbind_(t), INCLASSONLY) != NULL))) return 1; return 0; } extern bool isarraytype(TypeExpr *t, TypeExpr ** elmtype) { bool isarray = NO; for (; h0_((t = princtype(t))) == t_subscript; t = typearg_(t)) isarray = YES; if (isarray && elmtype != NULL) *elmtype = t; return isarray; } /* returns the number of elements in a possibly multi-dimensional array */ /* as well as the element type. '[]' is taken as '[1]' */ extern int32 arraysize(TypeExpr *t, TypeExpr ** elmtype) /* @@@ should return size_t */ { size_t nelts = 1; for (; h0_((t = princtype(t))) == t_subscript; t = typearg_(t)) if (typesubsize_(t) != 0 && h0_(typesubsize_(t)) != s_binder) nelts *= evaluate(typesubsize_(t)); if (elmtype != NULL) *elmtype = t; return nelts; } Expr *array_of_class_map_expr(Expr *p, Expr *nelts, int32 stride, Expr *mapfn) { ExprList *l; if (mapfn == 0) return 0; l = mkExprList1(mapfn); l = mkExprList(l, mkintconst(te_int, stride, 0)); /* /* should be size_t? */ l = mkExprList(l, nelts); l = mkExprList(l, p); return mkfnap(cppsim.xmapvec1, l); } Expr *array_of_class_map(Expr *e, int32 nelts, int32 stride, bool up, Expr *mapfn, bool twoargmapfn) { if (mapfn == 0) return 0; { TypeExpr *fnargt = ptrtotype_(te_fntype(te_void, te_voidptr, twoargmapfn ? te_int : 0, 0, 0, 0)); Expr *limit; if (up) { limit = /* '(char*)e + nelts * stride' */ mkbinary(s_plus, mkcast(s_cast|s_qualified, e, te_charptr), mkintconst(te_size_t, nelts * stride, 0)); } else { /* We cast to unsigned long instead of the more obvious */ /* char* to avoid a subscript out-of-range warning */ /* /* Technically limit is a undefined pointer. */ limit = /* '(void*)((unsigned long)e - stride' */ mkcast(s_cast|s_qualified, mkbinary(s_minus, mkcast(s_cast|s_qualified, e, te_ulint), mkintconst(te_size_t, stride, 0)), te_voidptr); e = /* '(char*)e + (nelts - 1) * stride' */ mkbinary(s_plus, mkcast(s_cast|s_qualified, e, te_charptr), mkintconst(te_size_t, (nelts - 1) * stride, 0)); stride = -stride; } return mkfnap(twoargmapfn ? cppsim.xmapvec1ci : cppsim.xmapvec1c, mkExprList4(e, limit, mkintconst(te_int, stride, 0), mkcast(s_cast|s_qualified, mapfn, fnargt))); } } Expr *array_of_class_copy(Expr *to, Expr *fm, Expr *frmlimit, int32 stride, Binder *mapfn) { if (mapfn == 0) return 0; { ExprList *l; TypeExpr *fnargt = ptrtotype_(te_fntype(te_void, te_voidptr, te_voidptr, 0, 0, 0)); l = mkExprList1(mk_expr1(s_addrof, fnargt, (Expr *)mapfn)); l = mkExprList(l, mkintconst(te_size_t, stride, 0)); l = mkExprList(l, frmlimit); l = mkExprList(l, mkcast(s_cast, mkunary(s_addrof, fm), te_voidptr)); l = mkExprList(l, mkcast(s_cast, mkunary(s_addrof, to), te_voidptr)); return mkfnap(cppsim.xmapvec2, l); } } static Expr *mkctor_v_1(Expr *e, ExprList *init, bool init_without_ctor) { /* e is a side-effect-free lvalue, typically var or *var. */ TypeExpr *t = typeofexpr(e); Expr *r = 0; ExprList *l; /* don't even try if earlier serious error in argument construction */ for (l = init; l != 0; l = cdr_(l)) if (h0_(exprcar_(l)) == s_error) return errornode; if (recursing) { cc_err(sem_err_ctor_confused, t); --recursing; return errornode; } else ++recursing; t = princtype(t); if (isclasstype_(t)) { TagBinder *cla = typespectagbind_(t); r = mkopap(s_init, cla, e, init); if (r == 0 && (tagbindbits_(cla) & TB_NEEDSCTOR)) { cc_err(sem_err_no_ctor_at_type, cla); r = errornode; } } else if (h0_(t) == t_subscript) { TypeExpr *elmtype; size_t nelts = arraysize(t, &elmtype); if (isclasstype_(elmtype)) { TagBinder *tb = typespectagbind_(elmtype); Binder *ctorb = findbinding(ctorsym, tb, INCLASSONLY); /* @@@ Bjarne says we have to allow things like: */ /* struct T { T(int=99); }; */ /* void f() { T a[3]; T* p = new T[5]; } */ /* We don't yet */ if (ctorb != NULL) { Expr *ctorfn = ovld_picknullary(ctorb); if (ctorfn == NULL) { cc_err(syn_err_no_nullary_ctor, ctorb); return errornode; } /* lose const/volatile for dtor for e.g. const class A x[]; */ e = mkcast(s_cast|s_qualified, e, ptrtotype_(tagbindtype_(tb))); /* code gen will give error message for 'T a[];' */ r = array_of_class_map(e, nelts, sizeoftype(elmtype), YES, ctorfn, NO); } } } if (r == 0 && init_without_ctor && init != 0) { /* no constructor and init-val(s) */ if (cdr_(init) != 0) cc_rerr(sem_rerr_too_many_args, t); r = mkbinary(s_init, e, mkcast(s_new, /* not s_cast (no int("abc")). */ exprcar_(init), t)); } --recursing; return r; } Expr *mkctor_v(Expr *e, ExprList *init) { return mkctor_v_1(e, init, YES); } static Expr *mkctor_p(Expr *nw, ExprList *init) { TypeExpr *pt = typeofexpr(nw); Binder *b = gentempbinder(pt); Expr *ctor = mkctor_v(mkunary(s_content, (Expr *)b), init); /* Generate: "let (t *b) in (b = nw(), b?ctor():0, b)". */ /* Note that making ctors return their arg could optimise reg use? */ return ctor==0 ? nw : mklet(b, pt, /* mkinvisible? */ commacons(mkbinary(s_assign, (Expr *)b, nw), commacons(mkcond((Expr *)b, mkcast(s_new, ctor, te_void), mkintconst(te_void, 0, 0)), (Expr *)b))); } static Expr *mkctor_temp(TypeExpr *t, ExprList *l, int takeaddress) { Binder *b = genexprtemp(t); TypeExpr *pt = princtype(t); /* Maybe we should prefer a "to-end-of-expr" temp here insteam of */ /* the required "to-end-of-scope" temp for reference temps. */ Expr *e, *init; /* beware the following line -- two deficiencies: 1. too much at */ /* run-time and doesn't alwyas require init. */ attributes_(b) |= A_DYNINIT; if (isclasstype_(pt)) { bindtype_(b) = primtype2_( typespecmap_(pt) & ~bitoftype_(s_const), typespectagbind_(pt)); if (attributes_(b) & A_GLOBALSTORE) bindtype_(b) = globalize_typeexpr(bindtype_(b)); } init = mkctor_v((Expr *)b, l); if (h0_(init) == s_error) return errornode; e = takeaddress ? mkunary(s_addrof, (Expr *)b) : (Expr *)b; e = commacons(init, e); t = type_(e); return mkinvisible(t, mk_expr1(s_ctor, t, e), e); } Expr *mkctor_t(TypeExpr *t, ExprList *l) { return mkctor_temp(t, l, NO); } #if 0 static Expr *mkctor_r(TypeExpr *t, Expr *e) { return mkctor_temp(t, mkExprList1(e), YES); } #endif static Expr *mkdtor_v_1(Expr *e, Expr* do_op_dl) { /* e is a side-effect-free lvalue, typically var or *var. */ TypeExpr *t = princtype(typeofexpr(e)); if (isclasstype_(t)) { TagBinder *tb = typespectagbind_(t); ClassMember *dtormem = findbinding(dtorsym, tb, INCLASSONLY); if (dtormem != NULL) { /* lose const/volatile for dtor for e.g. const class A x; */ e = mkunary(s_content, mkcast(s_cast|s_qualified, mkunary(s_addrof, e), ptrtotype_(tagbindtype_(tb)))); return mkfnap(mkfieldselector(s_dot, e, dtormem), mkExprList1(do_op_dl)); } } else if (h0_(t) == t_subscript) { TypeExpr* elmtype; size_t nelts = arraysize(t, &elmtype); if (isclasstype_(elmtype)) { Binder *dtorb = findbinding(dtorsym, typespectagbind_(elmtype), INCLASSONLY); if (dtorb != NULL) { Expr* dtorfn = ovld_picknullary(dtorb); if (dtorfn == NULL) return errornode; /* /* syserr ? */ return array_of_class_map(e, nelts, sizeoftype(elmtype), NO, dtorfn, YES); } } } return 0; } Expr *mkdtor_v(Expr *e) { return mkdtor_v_1(e, lit_zero); } static Expr *mkdtor_p(Expr *e, Binder* delgeneric, bool forceglobal) { TypeExpr *te = princtype(typeofexpr(e)); /* Presumably 'everyone knows' arg is a t_content or a typedef to it. */ /* Check anyway. */ if (h0_(te) != t_content) syserr("mkdtor_p %ld", (long)h0_(te)); { TypeExpr *ncte = (typeptrmap_(te)) & bitoftype_(s_const) ? ptrtotype_(typearg_(te)) : te; Binder *b = gentempbinder(ncte); Expr *dtor = mkdtor_v_1(mkunary(s_content, (Expr *)b), forceglobal ? lit_zero : lit_one); if (dtor != 0) { Expr *dl = mkcast(s_delete, dtor, te_void); if (forceglobal) dl = commacons(dl, mkfnap((Expr*)delgeneric, mkExprList1((Expr*)b))); else { /* check access of operator delete() */ ExprList *delargs = 0; if (is_two_arg_delete(delgeneric)) delargs = mkExprList1(mkintconst(te_size_t, 0, 0)); delargs = mkExprList(delargs, (Expr*)b); (void)ovld_resolve(delgeneric, typeovldlist_(bindtype_(delgeneric)), delargs, delargs, NO); } /* Have to guard dtor calls and user operator deletes */ /* Generate: "let (t *b) in (b = e, b?b->dtor(), dl(b):0)". */ /* or: "let (t *b) in (b = e, b?b->dtor(), dl(b, size):0)". */ /* Note that making dtors return their arg could optimise reg use? */ e = mklet(b, te_void, /* mkinvisible? */ commacons(mkbinary(s_init, (Expr *)b, e), mkcond((Expr *)b, dl, mkintconst(te_void, 0, 0)))); } else /* Don't have to guard ::operator delete calls */ e = mkfnap((Expr*)delgeneric, mkExprList1((Expr*)e)); return e; } } Expr *mkdtor_v_list(SynBindList *bl) { Expr *edtor = 0; for (; bl != NULL; bl = bl->bindlistcdr) { Binder *b = bl->bindlistcar; if (!b) syserr("Bad syn scope member"); if (bindstg_(b) & (bitofstg_(s_auto)|bitofstg_(s_register))) /* what about b_globregvar? */ edtor = commacons(edtor, mkdtor_v((Expr *)b)); } return edtor; } /* calls __ex_pop(), to pop the top exception from the exception stack */ Cmd *mkexpop(FileLine fl) { Expr* e = mkfnap((Expr *)cppsim.x__ex_pop, 0); /*e = mk_expr1(s_throw, te_void, e);*/ return mk_cmd_e (s_semicolon, fl, e); } /* calls __ex_top(), to return the top entry on the exception stack */ Cmd *mkextop(FileLine fl) { Expr* e = mkfnap((Expr *)cppsim.x__ex_top, 0); /*e = mk_expr1(s_throw, te_charptr, e);*/ return mk_cmd_e (s_semicolon, fl, e); } /* calls __ex_push(), to create space for a new exception on the excep. stack*/ Expr *mkexpush(FileLine fl, Expr* typeid, Expr* size) { Expr* e = (mkfnap((Expr *)cppsim.x__ex_push, mkExprList2(typeid, size))); fl=fl; /*don't need this, huh?*/ /*need to cast this to void.*/ e = mkcast(s_cast, e, te_void); return e; /* mk_cmd_e (s_semicolon, fl, e);*/ } /* calls __ex_push, unless e==NULL; always calls __throw() */ Cmd *mkthrow(FileLine fl, Expr *e) { Expr* exprtree; if (!(e && h0_(e) != s_error)) { exprtree = mkfnap((Expr *)cppsim.x__throw, 0); } else { Expr *e2 = coerceunary_2(e, COERCE_COMMA); TypeExpr *t = typeofexpr(e2); TypeExpr *tstar = ptrtotype_(t); /*TypeExpr *ct = mkqualifiedtype(t, bitoftype_(s_const));*/ /*TypeExpr *reft = mk_typeexpr1(t_ref, ct, 0);*/ String *s = exception_name(t); /* We should use a 'placed' allocation instead of a mkcast auto temp. */ /* We should also pass multiple catch-names, e.g. int* => int*,void* to*/ /* cope with the rules on [ES,p359]. Note that COMMON data areas */ /* holding strings and linker unique remove much strcmp... */ /*Expr *oldarg2 = mkunary(s_addrof, mkcast(s_throw, e2, reft));*/ Expr *arg1 = (Expr *)s; int sizeofexception = 8; /*ignore base types for now.*/ Expr* arg2 = mkintconst (te_int, sizeofexception, 0); Binder *gen = gentempbinder(tstar); Expr* temp_tstar = cpp_mkbinaryorop(s_init, (Expr *)gen, mkcast(s_cast, mkfnap((Expr *)cppsim.x__ex_push,/*te_charptr*/ mkExprList2 (mkcast(s_cast, arg1, te_int), arg2)), tstar)); Expr* temp_t = mkunary(s_content, (Expr*) gen); Expr* assign = cpp_mkbinaryorop(s_assign, temp_t, mkcast(s_cast, e2, t)); Expr* bind_temp = mk_exprlet(s_let, tstar, mkSynBindList(0, gen), cpp_mkbinaryorop(s_comma, temp_tstar, assign)); Expr *throwcall = mkfnap((Expr *)cppsim.x__throw, 0); exprtree = cpp_mkbinaryorop(s_comma, bind_temp, throwcall); exprtree = optimise0 (exprtree); } exprtree = mk_expr1(s_throw, te_void, exprtree); return mk_cmd_e (s_semicolon, fl, exprtree); } /* /* #ifdef CPLUSPLUS -- to be merged with ensurelvalue... */ /* this works for refs before and after coerceunary to pointers. */ TypeExpr *lvalue_type(Expr *x) /* isaddressablelvalue?? */ { TypeExpr *tx, *t; if (h0_(x) == s_error) return 0; tx = typeofexpr(x); t = princtype(tx); if (isbitfield_type(t)) return 0; if (isclasstype_(t)) return t; /* N.B. hack -- see caller. */ if (h0_(t) == t_ref) return typearg_(t); for (;;) switch (h0_(x)) { case s_binder: { Binder *b = exb_(x); if (isenumconst_(b)) return 0; /* can't happen */ return tx; } /* constructors are an odd case: given class C { C(int); } we want */ /* C(3) not to be an l-value (i.e. &C(3) illegal -- check), but we */ /* need it to make a reference without a further temporary so that */ /* C x = C(3) works by first using C(int) then copy ctor C(const C&). */ /* @@@ argument now subsumed by all class fn results should be lvalues */ /* from the point of view of ref-taking (at least in copyctors!). */ case s_ctor: /* strings are probably OK: e.g. char (&v)[4] = "abc"; */ case_s_any_string case s_subscript: case s_arrow: case s_content: return tx; case s_dot: x = arg1_(x); break; case s_invisible: x = orig_(x); break; default: return 0; } } static Expr *mknewarray(TypeExpr* t, Expr* nelts, ExprList *placement, Binder *newgeneric) { int32 stride = sizeoftype(t); Expr *nw; Expr *eltsize = mkintconst(te_size_t, stride, 0); Binder *ctorb = findbinding(ctorsym, typespectagbind_(t), INCLASSONLY); /* @@@ Bjarne says we have to allow things like: */ /* struct T { T(int=99); }; */ /* void f() { T a[3]; T* p = new T[5]; } */ /* We don't yet */ Expr* ctorfn = 0; if (ctorb != NULL) { ctorfn = ovld_picknullary(ctorb); if (ctorfn != NULL) ctorfn = mkcast(s_cast, ctorfn, ptrtotype_(te_fntype(te_void, te_voidptr, 0, 0, 0, 0))); else { cc_err(syn_err_no_nullary_ctor, ctorb); return errornode; } } else ctorfn = lit_zero; /* @@@ need to handle T::operator new[] and ::operator new[] here */ if (placement == 0 && (tagbindbits_(typespectagbind_(princtype(t))) & TB_HASDTOR)) nw = mkfnap(cppsim.xnewvec, mkExprList4(lit_zero, /* /* useless arg */ nelts, eltsize, ctorfn)); else { if (ctorb != 0) { Binder *telts = gentempbinder(typeofexpr(nelts)); Binder *nwp = gentempbinder(te_voidptr); nw = mkletmany(te_voidptr, /* mkinvisible? */ mkcommalist( mkbinary(s_init, (Expr *)telts, nelts), mkbinary(s_init, (Expr *)nwp, mkfnap((Expr*)newgeneric, mkExprList(placement, mkbinary(s_times, (Expr*)telts, eltsize)))), mkcond((Expr *)nwp, array_of_class_map_expr((Expr*)nwp, (Expr*)telts, stride, ctorfn), mkintconst(te_void, 0, 0)), (Expr *)nwp, 0), nwp, telts, 0); } else nw = mkfnap((Expr*)newgeneric, mkExprList(placement, mkbinary(s_times, nelts, eltsize))); } return nw; } Expr *mknew(TypeExpr *newt, TypeExpr *t, Binder *newgeneric, Expr* nelts, ExprList* placement, ExprList* init, bool forceglobal) { Expr *nw = 0; /* Note that 'new' prefers class to global scope whereas, mkopap() */ /* may choose from either. */ if (t == 0) /* non-class, possibly array */ { nw = mkfnap((Expr*)newgeneric, mkExprList(placement, nelts)); nw = mkcast(s_cast, nw, ptrtotype_((h0_(newt) == t_subscript) ? typearg_(newt) : newt)); if (init && h0_(nw) != s_error) nw = mkctor_p(nw, init); } else if (nelts == 0) /* single class allocation */ { if (placement != 0 || forceglobal) { Expr *eltsize = mkintconst(te_size_t, sizeoftype(t), 0); nw = mkfnap((Expr*)newgeneric, mkExprList(placement, eltsize)); nw = mkctor_p(mkcast(s_cast, nw, ptrtotype_(newt)), init); } else { /* do allocation in ctor */ nw = mkctor_v_1(mk_expr1(s_content, t, lit_zero), init, NO); if (nw == 0) { /* no constructor & none needed */ nw = mkfnap((Expr*)newgeneric, mkExprList1(mkintconst(te_size_t, sizeoftype(t), 0))); nw = mkctor_p(mkcast(s_cast, nw, ptrtotype_(newt)), init); } else { /* check access and overloading of operator new(). */ /* Using '(size_t)0' instead of actual size avoids */ /* spuriously needing size (for opaque type). */ ExprList *sizearg = mkExprList1(mkintconst(te_size_t, 0, 0)); (void)ovld_resolve(newgeneric, typeovldlist_(princtype(bindtype_(newgeneric))), sizearg, sizearg, NO); } } } else /* array of class */ nw = mkcast(s_cast, mknewarray(t, nelts, placement, newgeneric), ptrtotype_(typearg_(newt))); return (h0_(nw) == s_error) ? errornode : nw; } Expr *mkdelete(Expr *e, TypeExpr *t, bool isarray, Binder *delgeneric, bool forceglobal) { /* Note that 'delete' prefers class to global scope whereas, mkopap() */ /* may choose from either. */ if (t != 0 && isarray) /* delete [] ptr-to-class; */ { Expr *eltsize = mkintconst(te_size_t, sizeoftype(t), 0); Binder *dtorb = findbinding(dtorsym, typespectagbind_(t), INCLASSONLY); /* @@@ need to handle T::operator delete[] and ::operator delete[] here */ if (dtorb != 0) { Binder *b = gentempbinder(typeofexpr(e)); /* there only one dtor but this checks access */ ExprList *zeroarg = mkExprList1(lit_zero); ExprList *args = mkExprList(zeroarg, (Expr*)b); Binder *dtorspecific = ovld_resolve(dtorb, typeovldlist_(princtype(bindtype_(dtorb))), zeroarg, args, NO); Expr *dtorfn = mkcast(s_cast, mkaddr((Expr*)realbinder_(dtorspecific)), /* Beware: this may later produce a */ /* pointer-to-memfn -> pointer-to-fn cast warning. */ ptrtotype_(te_fntype(te_void, te_voidptr, te_int, 0, 0, 0))); return /* mkinvisible? */ mklet(b, te_void, commacons(mkbinary(s_init, (Expr *)b, e), mkfnap(cppsim.xdelvec, mkExprList3(b, eltsize, dtorfn)))); } else return mkfnap((Expr*)delgeneric, mkExprList1(e)); } else { if (t == te_void) return mkfnap((Expr*)delgeneric, mkExprList1(e)); else return mkdtor_p(e, delgeneric, forceglobal); } /* Errors: 1. mkdtor_p() catches 'e' non-pointer. 2. __dl(void *) */ /* ensures that we cannot delete (const T *) pointers. */ } static bool call_dependency_type(TypeExpr *t, ScopeSaver tactuals) { #ifdef IMPLEMENTED_PARTIAL_BINDING TypeExpr *t2 = NULL; t = princtype(t); switch (h0_(t)) { case s_typespec: if (isprimtypein_(t, CLASSBITS) && tagactuals_(typespectagbind_(t)) != NULL) { ScopeSaver ss = tagactuals_(typespectagbind_(t)); ScopeSaver tt = tactuals; if (env_size(ss) != env_size(tt)) return NO; for (; ss; ss = bindcdr_(ss)) for (; tt; tt = bindcdr_(tt)) if (bindsym_(tt) == bindsym_(ss) && equivtype(bindtype_(tt), bindtype_(ss))) return YES; } else t2 = t; break; case t_coloncolon: if (call_dependency_type(bindtype_(typespecbind_(t)), tactuals) || call_dependency_type(typearg_(t), tactuals)) return YES; break; case t_unknown: t2 = t; break; case t_content: case t_ref: case t_subscript: return call_dependency_type(typearg_(t), tactuals); case t_fnap: { FormTypeList *ft = typefnargs_(t); for (; ft; ft = ft->ftcdr) if (call_dependency_type(ft->fttype, tactuals)) return YES; /* DWP Oct95 did not say anything about return type */ return NO; } default: syserr("call_dependency: unknown type %ld\n", (long)h0_(t)); } if (t2) for (; tactuals; tactuals = bindcdr_(tactuals)) { if (h0_(bindtype_(tactuals)) != s_typespec) continue; if (equivtype(t2, bindtype_(tactuals))) return YES; } return NO; #else IGNORE(t); IGNORE(tactuals); return YES; #endif } static bool call_dependency_val(Expr *e, ScopeSaver tactuals) { #ifdef IMPLEMENTED_PARTIAL_BINDING for (; tactuals; tactuals = bindcdr_(tactuals)) if (h0_(bindtype_(tactuals)) == s_typespec) { TypeExpr *t = princtype(typeofexpr(e)); TagBinder *cl = (isclasstype_(t)) ? typespectagbind_(t) : NULL; if (cl && class_has_conversion(cl, bindtype_(tactuals), YES)) return YES; } else if ((h0_(e) == s_binder) && (bindsym_(exb_(e)) == bindsym_(tactuals))) return YES; return NO; #else IGNORE(e); IGNORE(tactuals); return YES; #endif } static void fix_typevar_in(TypeExpr *f) { SET_BITMAP m; Binder *b; FormTypeList *ft; switch h0_(f) { case s_typespec: m = typespecmap_(f); switch (m & -m) /* LSB - unsigned/long etc. are higher */ { case bitoftype_(s_typedefname): /* The following allows fixup_template_arg_type() to be called on the same type repeatedly with the desired effect. It is an implicit assumption that the local scope is a Scope_TemplateArg. Effectively, it binds a typedef whose name can be found in scope. */ if ((b = findbinding(bindsym_(typespecbind_(f)), 0, FB_LOCALS|FB_THISSCOPE)) != NULL) typespecbind_(f) = b; default: return; } default: syserr("fix_typevar_in(%ld,%#lx)", (long)h0_(f), (long)typespecmap_(f)); case t_fnap: fix_typevar_in(typearg_(f)); for (ft = typefnargs_(f); ft; ft = ft->ftcdr) { fix_typevar_in(ft->fttype); if (!istypevar(ft->fttype)) ft->fttype = prunetype(ft->fttype); } return; case t_coloncolon: case t_subscript: case t_content: case t_ref: fix_typevar_in(typearg_(f)); if (!istypevar(typearg_(f))) typearg_(f) = prunetype(typearg_(f)); return; } } void fixup_template_arg_type(TypeExpr *f, ScopeSaver actuals) { int scope_level = push_var_scope(actuals, Scope_Ord); fix_typevar_in(f); pop_scope_no_check(scope_level); } /* Assume caller is for full explicit instantiation */ ScopeSaver globalize_template_arg_binders(ScopeSaver f, ExprList *a) { Binder *tp = NULL, *tq = NULL; for (; f; f = bindcdr_(f)) { Expr *e = (a && exprcar_(a)) ? exprcar_(a) : bindconst_(f); Binder *temp; TypeExpr *t = (e && h0_(e) == s_typespec) ? type_(e) : clone_typeexpr(bindtype_(f)); if (e && e == bindconst_(f) && h0_(e) == s_typespec && istypevar(type_(e))) { t = clone_typeexpr(type_(e)); fixup_template_arg_type(t, tp); } temp = global_mk_binder(0, bindsym_(f), bindstg_(f), globalize_typeexpr(t)); #if 0 /* rationale: template <class T, class U = T> */ if (istypevar(bindtype_(temp)) && isprimtype_(bindtype_(temp), s_typedefname) && tp) fixup_template_arg_type(bindtype_(temp), tp); #endif if (!tp) tp = tq = temp; else { bindcdr_(tq) = temp; tq = temp; } if (e && h0_(e) != s_typespec) { bindconst_(temp) = (h0_(e) == s_binder) ? e : globalize_expr(e); /* Rationale for the following line, considers, template <class T, T *p> struct X {}; And sharing destroyed by clone_typeexpr() above. */ fixup_template_arg_type(bindtype_(temp), tp); } if (a) a = cdr_(a); } return tp; } /* almost like a globalize_template_arg_binders(), more forgiving. */ ScopeSaver dup_env_actuals(ScopeSaver tformals, ExprList *a) { ScopeSaver temp = NULL; if (prefer_tmptfn(a)) a = NULL; for (; tformals; tformals = bindcdr_(tformals)) { Binder *b = mk_binder(bindsym_(tformals), bindstg_(tformals), bindtype_(tformals)); bindcdr_(b) = temp; if (a) { if (h0_(exprcar_(a)) == s_typespec) { bindtype_(b) = globalize_typeexpr(type_(exprcar_(a))); if (debugging(DEBUG_TEMPLATE)) cc_msg("assigned: $b -> $t\n", b, bindtype_(b)); } else bindconst_(b) = globalize_expr(exprcar_(a)); a = cdr_(a); } else if (bindconst_(tformals)) { if (h0_(bindconst_(tformals)) == s_typespec) bindtype_(b) = type_(bindconst_(tformals)); else bindconst_(b) = bindconst_(tformals); } temp = b; } return dreverse_binder(temp); } static TagBindList *typevars_tag_list; static bool is_in_typevars_tag_list(TagBinder *tb) { if (!typevars_tag_list) typevars_tag_list = (TagBindList *)mkBindList(NULL, tb); else { TagBindList *tbl = typevars_tag_list; for (; tbl; tbl = (TagBindList *)tbl->bindlistcdr) if ((TagBinder *)tbl->bindlistcar == tb) return YES; typevars_tag_list = (TagBindList *)mkBindList(typevars_tag_list, tb); } return NO; } static bool contains_typevars_0(TypeExpr *t, bool dependent) { if (istypevar(t)) { Binder *b; if (h0_(t) == t_unknown) return (dependent) ? NO : YES; /* It may not have been bounded! */ if (!isprimtype_(t, s_typedefname)) syserr("what sort of unknown type is this?"); b = findbinding(bindsym_(typespecbind_(t)), 0, ALLSCOPES); return (b && istypevar(bindtype_(b))); } t = princtype(t); switch (h0_(t)) { case s_typespec: { SET_BITMAP m = typespecmap_(t); switch (m & -m) { default: break; case bitoftype_(s_struct): case bitoftype_(s_class): case bitoftype_(s_union): { TagBinder *tb = typespectagbind_(t); if (tagbindbits_(tb) & TB_TEMPLATE) { if (dependent) { ScopeSaver formals = tagformals_(tb); for (; formals != NULL; formals = bindcdr_(formals)) if (is_template_arg_binder((Expr *)formals)) return YES; } else if (!is_in_typevars_tag_list(tb)) { ClassMember *m = tagbindmems_(tb); for (; m; m = memcdr_(m)) if (contains_typevars_0(memtype_(m), NO)) return YES; } } else if (tagactuals_(tb) != NULL) { ScopeSaver actuals = tagactuals_(tb); for (; actuals; actuals = bindcdr_(actuals)) if (contains_typevars_0(bindtype_(actuals), dependent)) return YES; } } } } break; case t_ref: case t_content: return contains_typevars_0(typearg_(t), dependent); case t_subscript: case t_coloncolon: if (contains_typevars_0(typearg_(t), dependent)) return YES; if (h0_(t) == t_coloncolon) return contains_typevars_0(tagbindtype_(typespectagbind_(t)), dependent); break; case t_fnap: if (contains_typevars_0(typearg_(t), dependent)) return YES; { FormTypeList *ft = typefnargs_(t); for (; ft; ft = ft->ftcdr) if (contains_typevars_0(ft->fttype, dependent)) return YES; } break; } return NO; } #define TYPE_DEDUCE_MASK (QUALIFIER_MASK|bitoftype_(s_unsigned)|bitoftype_(s_signed)) static void check_type_equivalence(TypeExpr *t1, TypeExpr *t2, bool silent, bool *failed) { *failed = !equivtype_4(t1, t2, TYPE_DEDUCE_MASK, TYPE_DEDUCE_MASK, NO); if (*failed && !silent) cc_err(sem_err_typededuce_disagree, t1, t2); } static void fix_target_type_1(Binder *tpltarg, TypeExpr *target, bool silent, bool *failed, bool convallowed, bool preserve) { if (!istypevar(bindtype_(tpltarg))) { TypeExpr *temp = princtype(bindtype_(tpltarg)); if (convallowed) { Binder *b = gentempbinder(target); if (isclasstype_(temp)) { if (!equivtype_4(temp, target, TYPE_DEDUCE_MASK, TYPE_DEDUCE_MASK, NO)) *failed = (class_has_ctor_1(typespectagbind_(temp), target, (Expr *)b, NO, YES) == NULL); } else { if (!(attributes_(tpltarg) & DEDUCED) && isarithtype_(temp) && isarithtype_(target)) ; else check_type_equivalence(temp, modify_formaltype(target), silent, failed); } } else check_type_equivalence(temp, target, silent, failed); } else { if (attributes_(tpltarg) & NON_CONFORMING) { /* strict equality here. */ if (bindtype_(tpltarg) != target) { *failed = YES; if (!silent) cc_err(sem_err_typededuce_disagree, bindtype_(tpltarg), target); } } else { attributes_(tpltarg) |= (istypevar(target)) ? NON_CONFORMING : DEDUCED; if (!preserve) { target = clone_typeexpr(princtype(target)); switch (h0_(target)) { case s_typespec: typespecmap_(target) &= ~CVBITS; break; case t_fnap: case t_ref: case t_content: typeptrmap_(target) &= ~CVBITS; break; } } bindtype_(tpltarg) = modify_formaltype(target); if (debugging(DEBUG_TEMPLATE)) cc_msg("deduced: $b -> $t\n", tpltarg, target); } } } static void fix_target_type(TypeExpr *t, TypeExpr *target, bool silent, bool *failed, bool convallowed, bool preserve) { Binder *b = NULL; if (!isprimtype_(t, s_typedefname) || !istypevar(t)) syserr("expecting typevar"); if (bindparent_(typespecbind_(t)) != NULL) { Binder *bb = typespecbind_(t); TagBinder *parent = bindparent_(bb), *curScope = NULL; TagBindList *scopes = NULL; for (; parent; parent = tagbindparent_(parent)) scopes = (TagBindList *)binder_cons2(scopes, parent); parent = (TagBinder *)scopes->bindlistcar; scopes = (TagBindList *)scopes->bindlistcdr; b = findbinding(bindsym_(parent), 0, FB_LOCALS|FB_THISSCOPE); if (b && isclasstype_(princtype(bindtype_(b)))) { curScope = typespectagbind_(princtype(bindtype_(b))); for (; curScope && scopes; scopes = (TagBindList *)scopes->bindlistcdr) curScope = findtagbinding(bindsym_((TagBinder *)scopes->bindlistcar), curScope, INCLASSONLY); } if (curScope && (bb = findbinding(bindsym_(bb), curScope, FB_LOCALS|FB_THISSCOPE)) != NULL) typespecbind_(t) = bb; else { if (!silent) cc_err(sem_err_typename_not_found, typespecbind_(t)); *failed = YES; } } else { b = findbinding(bindsym_(typespecbind_(t)), 0, FB_LOCALS|FB_THISSCOPE); if (!b) syserr("Odd template type arg $b", typespecbind_(t)); fix_target_type_1(b, target, silent, failed, convallowed, preserve); typespecbind_(t) = b; } } static void fixup_type_1(TypeExpr *t) { if (!isprimtype_(t, s_typedefname)) syserr("typevar expected, $t given", t); { Binder *b = findbinding(bindsym_(typespecbind_(t)), 0, FB_LOCALS|FB_THISSCOPE); if (!b) syserr("Odd template type arg $r", bindsym_(typespecbind_(t))); typespecbind_(t) = b; } } static TypeExpr *fixup_type(TypeExpr *t) { switch (h0_(t)) { case s_typespec: { SET_BITMAP m = typespecmap_(princtype(t)); TagBinder *tb; if (istypevar(t)) m = 0; /* T may have been qualified e.g. s_struct, ignored */ switch (m & -m) { default: if (istypevar(t)) fixup_type_1(t); break; case bitoftype_(s_struct): case bitoftype_(s_class): case bitoftype_(s_union): tb = typespectagbind_(princtype(t)); if (tagbindbits_(tb) & TB_TEMPLATE || !(tagbindbits_(tb) & TB_DEFD)) { tb = syn_implicit_instantiate_2(tb); t = tagbindtype_(tb); } } break; } /* Only t_content now? */ case t_subscript: typearg_(t) = fixup_type(typearg_(t)); break; case t_coloncolon: typearg_(t) = fixup_type(typearg_(t)); typespecbind_(t) = typespecbind_(fixup_type(tagbindtype_(typespectagbind_(t)))); break; case t_fnap: { FormTypeList *ft = typefnargs_(t); typearg_(t) = fixup_type(typearg_(t)); for (; ft; ft = ft->ftcdr) ft->fttype = fixup_type(ft->fttype); break; } default: syserr("type deduction failed: un-recognized type $t", t); } return t; } /* upto 32 params */ #define TYPEMEMOSIZE 32 static struct te_memo { TypeExpr *orig, *to; } local_prunetype_memo[TYPEMEMOSIZE]; #define EQtype_(t1,t2) ((t1)->h0==(t2)->h0 && typearg_(t1)==typearg_(t2) \ && typespecbind_(t1)==typespecbind_(t2)) static TypeExpr *prunetype_memo(TypeExpr *t) { struct te_memo *p; for (p = local_prunetype_memo; p->orig != NULL; p++) if (EQtype_(t, p->orig)) break; if (p->orig == NULL) { p->orig = t; p->to = prunetype(t); } return p->to; } /* This is a 3-result function. A result is that of a binding env that's free from typevars and all const binders are initialized in non-template scope. It also returns the deduced fntype as well as an indication if type deduction has failed. */ static TypeExpr *type_deduction_0(TypeExpr *fntype, ExprList *args, ExprList *actuals, ScopeSaver *tformals, bool silent, bool *failed, bool strict, bool preserve) { TypeExpr *temp = clone_typeexpr(fntype); FormTypeList *ft = typefnargs_(temp); int varlevel, nargs = length((List *)args); if (nargs > length((List *)ft) || minargs_(temp) > nargs) { *failed = YES; return temp; } *tformals = dup_env_actuals(*tformals, actuals); varlevel = push_var_scope(*tformals, Scope_TemplateArgs); memset(local_prunetype_memo, 0, sizeof local_prunetype_memo); for (; ft && args && !*failed; ft = ft->ftcdr, args = cdr_(args)) { TypeExpr *t = ft->fttype, *t2; SET_BITMAP qt2; Expr *e = exprcar_(args); /* First check that non-type arg has the same value as the default. Applicable to reduction purpose really. */ if (ft->ftdefault != NULL && h0_(ft->ftdefault) != s_binder && h0_(ft->ftdefault) != s_typespec && h0_(e) == s_binder && isgensym(bindsym_(exb_(e))) && bindconst_(exb_(e)) != NULL && ft->ftdefault != bindconst_(exb_(e))) { *failed = YES; break; } t2 = typeofexpr(e); qt2 = qualifiersoftype(t2); if (h0_(t) == t_content || h0_(t) == t_ref) { TypeExpr *tmp = princtype(t2); if (h0_(t) == t_content && h0_(tmp = princtype(typeofexpr(e = coerceunary_2(e, COERCE_ARG)))) == h0_(t)) { t2 = typearg_(tmp); preserve = YES; } else if (h0_(t) == t_ref && (h0_(tmp) == t_ref || lvalue_type(e) || qualifiersoftype(typearg_(t)) & bitoftype_(s_const))) { if (h0_(tmp) == t_ref) t2 = typearg_(tmp); preserve = YES; } else if (!istypevar(tmp)) { *failed = YES; if (!silent) cc_err(sem_err_typededuce_disagree, t, t2); continue; } t = typearg_(t); } t2 = prunetype_memo(t2); /* No princtype() on t yet because the name of an unknown type is needed. */ switch (h0_(t)) { case s_typespec: { SET_BITMAP m = typespecmap_(princtype(t)); TagBinder *tb, *tb2; if (istypevar(t)) m = 0; /* T may have been qualified by a eg. s_struct, ignored. */ switch (m & -m) { default: if (istypevar(t)) { if (is_template_arg_binder((Expr *)typespecbind_(t))) fix_target_type(t, t2, silent, failed, YES, preserve); /* /* do we need to do anything about typenames? */ } else if (strict) check_type_equivalence(t, t2, silent, failed); break; case bitoftype_(s_struct): case bitoftype_(s_class): case bitoftype_(s_union): t = princtype(t); tb = typespectagbind_(t); tb2 = (isclasstype_(t2)) ? typespectagbind_(t2) : NULL; /* There maybe a derivation relationship. */ if (tb2 != NULL) { ClassMember *m = tagbindmems_(tb2); for (; m != NULL; m = memcdr_(m)) { TagBinder *tmp = NULL; if (!(attributes_(m) & (CB_BASE|CB_VBASE))) continue; tmp = typespectagbind_(princtype(bindtype_(m))); if (tagprimary_(tmp) == tb || (tagprimary_(tmp) != NULL && tagprimary_(tmp) == tagprimary_(tb))) { tb2 = tmp; t2 = tagbindtype_(tb2); break; } } } if (tagformals_(tb) != NULL && tb2 != NULL && ((tagprimary_(tb2) != NULL && tagprimary_(tb) == tagprimary_(tb2)) || tagprimary_(tb2) == tb)) { ScopeSaver actuals, formals; Symstr *sv; actuals = tagactuals_(tb2); formals = (tagprimary_(tb2)==tb) ? tagformals_(tb) : tagactuals_(tb); if (env_size(actuals) != env_size(formals)) syserr("Odd specializations %c & %c", tb, tb2); if (qt2 > qualifiersoftype(t)) *failed = YES; else { for (; actuals && formals; actuals = bindcdr_(actuals), formals = bindcdr_(formals)) { Binder *b = NULL; bool istype = NO; if ((istype = istypevar(bindtype_(formals))) == YES) sv = (h0_(bindtype_(formals)) == t_unknown) ? bindsym_(formals) : bindsym_(typespecbind_(bindtype_(formals))); else if (bindconst_(formals) != NULL && h0_(bindconst_(formals)) == s_binder) sv = bindsym_(exb_(bindconst_(formals))); else sv = bindsym_(formals); b = findbinding(sv, 0, FB_LOCALS|FB_THISSCOPE); if (!b) syserr("Odd template type/no-type arg $r", sv); if (istype) fix_target_type_1(b, bindtype_(actuals), silent, failed, NO, preserve); else bindconst_(b) = globalize_expr(bindconst_(actuals)); } if (h0_(ft->fttype) == t_ref || h0_(ft->fttype) == t_content) { TypeExpr *clone = clone_typeexpr(ft->fttype); typearg_(clone) = mkqualifiedtype(t2, qualifiersoftype(typearg_(ft->fttype))); ft->fttype = clone; } else ft->fttype = t2; } } else { if (tb != NULL && tb2 == NULL && !istypevar(t2) && !contains_typevars(tagbindtype_(tb)) && class_has_ctor_1(tb, t2, e, NO, YES) != NULL) ; else if (strict) check_type_equivalence(t, t2, silent, failed); } } } break; case t_subscript: if (h0_(t2) == t_subscript) { if (istypevar(typearg_(t))) fix_target_type(typearg_(t), typearg_(t2), silent, failed, NO, preserve); if (h0_(typesubsize_(t)) == s_binder) { Binder *b = exb_(typesubsize_(t)); b = findbinding(bindsym_(b), 0, FB_LOCALS|FB_THISSCOPE); if (!b) syserr("Odd template non-type arg $r", bindsym_(b)); if (bindconst_(b) != NULL && evaluate(bindconst_(b)) != evaluate(typesubsize_(t2))) { if (!silent) cc_warn(sem_warn_typededuce_arraysize); /* *failed = YES; */ } typesubsize_(t) = bindconst_(b) = globalize_expr(typesubsize_(t2)); } } else if (strict) check_type_equivalence(t, t2, silent, failed); break; case t_coloncolon: if (h0_(t2) == t_coloncolon) { TypeExpr *dest = NULL, *target = NULL; bool needsupdate = NO; if (istypevar(tagbindtype_(typespectagbind_(t))) && equivtype(typearg_(t), typearg_(t2))) { dest = tagbindtype_(typespectagbind_(t)); target = tagbindtype_(typespectagbind_(t2)); needsupdate = YES; } else if (istypevar(typearg_(t)) && equivtype(tagbindtype_(typespectagbind_(t)), tagbindtype_(typespectagbind_(t2)))) { dest = typearg_(t); target = typearg_(t2); } if (dest != NULL) { Binder *b; if (!isprimtype_(dest, s_typedefname)) syserr("bare t_unknown"); b = findbinding(bindsym_(typespecbind_(dest)), 0, FB_LOCALS|FB_THISSCOPE); if (!b) syserr("Odd template type arg $r", bindsym_(typespecbind_(dest)) ); fix_target_type_1(b, target, silent, failed, NO, preserve); if (!*failed && !silent && needsupdate) typespectagbind_(t) = typespectagbind_(target); } } else if (strict) check_type_equivalence(t, t2, silent, failed); break; case t_fnap: if ((h0_(t2) == t_ovld && typeovldlist_(t2) != NULL) || h0_(t2) == t_fnap) { BindList *bl; int candidates = 0; TypeExpr *best = NULL; ScopeSaver best_env = NULL; int len = length((List *)typefnargs_(t)); bl = (h0_(t2) == t_fnap) ? binder_cons2(NULL, (h0_(skip_invisible(e)) == s_addrof) ? arg1_(e) : e) : typeovldlist_(t2); for (; bl; bl = bl->bindlistcdr) { Binder *b = bl->bindlistcar; FormTypeList *ft2; ExprList *args2 = NULL; bool local_failed = NO; ft2 = (h0_(t2) == t_fnap) ? typefnargs_(t2) : typefnargs_(bindtype_(b)); if (len != length((List *)ft2)) continue; for (; ft2; ft2 = ft2->ftcdr) args2 = mkExprList(args2, gentempbinder(ft2->fttype)); best_env = *tformals; best = type_deduction(t, dreverse(args2), NULL, &best_env, YES, &local_failed); if (!local_failed) { if (istypevar(typearg_(best))) fix_target_type(typearg_(best), typearg_(bindtype_(b)), silent, &local_failed, NO, preserve); else if (strict) check_type_equivalence(typearg_(best), typearg_(bindtype_(b)), silent, &local_failed); if (!local_failed) candidates++; } } if (candidates != 1 || !best) { *failed = YES; if (!silent) cc_err(sem_err_typededuce_ambiguous, candidates); /* recovered by picking up the latest best, if exists */ if (!best) best = te_int; } typearg_(ft->fttype) = best; for (; best_env; best_env = bindcdr_(best_env)) { Binder *b = findbinding(bindsym_(best_env), 0, FB_LOCALS|FB_THISSCOPE); if (!b) syserr("Odd template type arg $r", bindsym_(best_env)); if (!istypevar(bindtype_(best_env))) fix_target_type_1(b, bindtype_(best_env), silent, failed, NO, preserve); } } else if (strict) check_type_equivalence(t, t2, silent, failed); break; default: { if (!silent) cc_err(sem_err_typededuce_recognize, ft->fttype); *failed = YES; } } } if (*failed) { pop_scope_no_check(varlevel); return temp; } for (; ft; ft = ft->ftcdr) if (istypevar(ft->fttype)) fixup_type(ft->fttype); /* Fix up the result type */ { TypeExpr *t = typearg_(temp); /* Update in-situ, temp was a copy anyway. */ if (h0_(t) == t_ref || h0_(t) == t_content) typearg_(t) = fixup_type(typearg_(t)); else typearg_(temp) = fixup_type(t); } pop_scope_no_check(varlevel); if (!has_template_arg_scope()) { Binder *b = *tformals; for (; b && !*failed; b = bindcdr_(b)) if (bindstg_(b) & bitofstg_(s_typedef)) { if (istypevar(bindtype_(b))) { bindtype_(b) = te_void; if (!silent) cc_err(sem_err_typededuce_type, bindsym_(b)); *failed = YES; } } else if (bindconst_(b) == NULL) { if (!silent) cc_err(sem_err_typededuce_const, bindsym_(b)); *failed = YES; } } return temp; } TypeExpr *type_deduction(TypeExpr *fntype, ExprList *args, ExprList *actuals, ScopeSaver *tformals, bool silent, bool *failed) { return type_deduction_0(fntype, args, actuals, tformals, silent, failed, NO, NO); } static BindList *temp_candidates(BindList *temps, ExprList *l, ExprList *tactuals, bool silent) { BindList *res = NULL; for (; temps; temps = temps->bindlistcdr) { bool failed = NO; Binder *b = temps->bindlistcar; ScopeSaver env = bindenv_(b); (void) type_deduction_0(bindtype_(b), l, tactuals, &env, silent, &failed, YES, NO); if (!failed) res = binder_cons2(res, b); } return res; } static bool po_equivtype_0(TypeExpr *t1, TypeExpr *t2) { if (istypevar(t1) && istypevar(t2)) return qualifiersoftype(t1) == qualifiersoftype(t2); else switch (h0_(t1)) { case t_subscript: case t_ref: case t_content: return qualifiersoftype(t1) == qualifiersoftype(t2) && po_equivtype_0(typearg_(t1), typearg_(t2)); default: return (equivtype(t1, t2) == 2); } } static bool po_equivtype(TypeExpr *t1, TypeExpr *t2) { FormTypeList *ft1, *ft2; bool res = YES; if (h0_(t1) != s_fnap || h0_(t2) != s_fnap) syserr("po_equivtype: fntype expected"); ft1 = typefnargs_(t1), ft2 = typefnargs_(t2); for (; ft1 && ft2 && res; ft1 = ft1->ftcdr, ft2 = ft2->ftcdr) { t1 = ft1->fttype, t2 = ft2->fttype; switch (equivtype(t1, t2)) { case 2: res = YES; break; case 1: res = po_equivtype_0(t1, t2); break; default: res = NO; } } return (ft1 == ft2) && res; } BindList *temp_reduce(BindList *temps, ExprList *l, ExprList *tactuals, Binder *bgeneric) { Binder *cur_best_temp; int varlevel; bool silent; if (temps == NULL && bgeneric != NULL) { int len = length((List *) (tactuals = bindactuals_(bgeneric))); BindList *tmpts = bindftlist_(bgeneric), *tmpts2 = NULL; /* filtered through the candidates */ for (; tmpts != NULL; tmpts = tmpts->bindlistcdr) if (env_size(bindformals_(tmpts->bindlistcar)) >= len) tmpts2 = (BindList *) binder_cons2(tmpts2, tmpts->bindlistcar); temps = tmpts2; } silent = (length((List *)temps) > 1 || bgeneric == NULL || typeovldlist_(bindtype_(bgeneric)) || is_operator_name(bindsym_(bgeneric))); temps = temp_candidates(temps, l, tactuals, silent); if (temps == NULL) return NULL; if (length((List *)temps) == 1) { if (debugging(DEBUG_TEMPLATE)) cc_msg("best template $r\n", bindsym_(temps->bindlistcar)); return temps; } cur_best_temp = temps->bindlistcar; temps = temps->bindlistcdr; /* suppress type deduction moaning about t_unknown. */ varlevel = push_var_scope(NULL, Scope_TemplateArgs); for (; temps; temps = temps->bindlistcdr) { FormTypeList *ft; ExprList *args = NULL; bool local_failed = NO; TypeExpr *deduced; Binder *b = temps->bindlistcar; ScopeSaver env = bindenv_(b); bool best, cur; for (ft = typefnargs_(bindtype_(cur_best_temp)); ft; ft = ft->ftcdr) { Binder *tmp = gentempbinder(ft->fttype); bindconst_(tmp) = ft->ftdefault; args = mkExprList(args, tmp); } deduced = type_deduction_0(bindtype_(b), dreverse(args), tactuals, &env, YES, &local_failed, NO, YES); best = (!local_failed && po_equivtype(bindtype_(cur_best_temp), (fixup_template_arg_type(deduced, env), deduced))); for (args = NULL, ft = typefnargs_(bindtype_(b)); ft; ft = ft->ftcdr) { Binder *tmp = gentempbinder(ft->fttype); bindconst_(tmp) = ft->ftdefault; args = mkExprList(args, tmp); } env = bindenv_(cur_best_temp); local_failed = NO; deduced = type_deduction_0(bindtype_(cur_best_temp), dreverse(args), tactuals, &env, YES, &local_failed, NO, YES); cur = (!local_failed && po_equivtype(bindtype_(b), (fixup_template_arg_type(deduced, env), deduced))); if (best && !cur) /* best still the best */; else if (!best && cur) { if (debugging(DEBUG_TEMPLATE)) cc_msg("dropped template $r\n", bindsym_(cur_best_temp)); cur_best_temp = b; } else { ExprList *args2 = args; BindList *bl = binder_cons2(binder_cons2(NULL, cur_best_temp), b); Binder *b1; if (bindparent_(b) != NULL) { TypeExpr *pt = tagbindtype_(bindparent_(b)); Binder *tempb = gentempbinder(pt); Expr *thisptr = mk_expr1(s_addrof, ptrtotype_(pt), (Expr *)tempb); bindstg_(tempb) |= b_addrof|u_referenced; args2 = mkExprList(args2, thisptr); } if (bgeneric != NULL && (b1 = ovld_resolve(bgeneric, bl, args, args2, YES)) != NULL) if (h0_(b1) != s_error) { cur_best_temp = b1; continue; } if (tag_global_(bindsym_(cur_best_temp)) && tag_global_(bindsym_(b)) && tagprimary_(tag_global_(bindsym_(b))) != NULL && /* make sure its comparing non-null */ tagprimary_(tag_global_(bindsym_(b))) == tagprimary_(tag_global_(bindsym_(cur_best_temp)))) /* if we can't separate them and they're from the same parent, it's not an error. They are from the same generic type. Conspiring with class_template_reduce() to pick the primary. @@@ watch out for namespace scope though. */ ; else { if (debugging(DEBUG_TEMPLATE)) cc_msg("templates $r & $r are possible candidates\n", bindsym_(cur_best_temp), bindsym_(b)); cc_err(sem_err_template_ambiguous); cur_best_temp = NULL; } break; } } if (debugging(DEBUG_TEMPLATE) && cur_best_temp) cc_msg("best template $r\n", bindsym_(cur_best_temp)); pop_scope_no_check(varlevel); return (cur_best_temp != NULL) ? mkBindList(NULL, cur_best_temp) : NULL; } TagBinder *class_template_reduce(TagBinder *primary, TagBindList *instances, ScopeSaver tactuals) { int nargs; BindList *temps = NULL; TagBindList *ins; ExprList *args; ScopeSaver actuals; if (primary == NULL) syserr("no primary to reduce"); if (instances == NULL) return primary; for (args = NULL, actuals = tactuals; actuals; actuals = bindcdr_(actuals)) { Binder *tmp = gentempbinder(bindtype_(actuals)); bindconst_(tmp) = bindconst_(actuals); args = mkExprList(args, tmp); } args = (ExprList *)dreverse(args); nargs = env_size(tagformals_(primary)); for (ins = instances; ins; ins = (TagBindList *)ins->bindlistcdr) { Binder *b; TagBinder *tb = (TagBinder *)ins->bindlistcar; TypeExprFnAux s; TypeExpr *fntype; FormTypeList *fttype = NULL; ScopeSaver env = tagactuals_(tb); if (!(tagbindbits_(tb) & TB_DEFD) || tagbindsym_(primary) == tagbindsym_(tb)) continue; if (env_size(env) != nargs) syserr("wrong no. of actuals to $c", tb); for (; env; env = bindcdr_(env)) fttype = mkFormTypeList(fttype, NULL, bindtype_(env), bindconst_(env)); fntype = mkTypeExprfn(t_fnap, te_void, 0, (FormTypeList *)dreverse((List *)fttype), packTypeExprFnAux(s, nargs, nargs, 0, 0, 0)); b = mk_binder(tagbindsym_(tb), 0, fntype); bindenv_(b) = tagformals_(tb); temps = binder_cons2(temps, b); } temps = temp_reduce(temps, args, NULL, NULL); if (temps != NULL) { Binder *res = temps->bindlistcar; TagBinder *best = NULL; for (; instances; instances = (TagBindList *)instances->bindlistcdr) if (bindsym_(instances->bindlistcar) == bindsym_(res)) break; if (instances == NULL) syserr("unexpected null instance"); best = (TagBinder *)instances->bindlistcar; /* Make sure if it is a cloned, specialized instance, return the primary instead. */ return (tagtext_(best) < 0) ? primary : best; } else return primary; } void check_temp_arg_linkage(Expr *e) { AE_op op = h0_(e); switch (op) { case s_invisible: check_temp_arg_linkage(compl_(e)); break; case s_cast: check_temp_arg_linkage(arg1_(e)); break; case s_binder: { Binder *b = exb_(e); if (bindstg_(b) & (bitofstg_(s_static)|bitofstg_(s_auto))) cc_err(sem_err_non_type_arg_linkage, b); } break; case s_evalerror: case s_integer: case s_floatcon: break; default: if (ismonad_(op)) check_temp_arg_linkage(arg1_(e)); else if (isdiad_(op)) { check_temp_arg_linkage(arg1_(e)); check_temp_arg_linkage(arg2_(e)); } else if (op == s_cond) { check_temp_arg_linkage(arg1_(e)); check_temp_arg_linkage(arg2_(e)); check_temp_arg_linkage(arg3_(e)); } else cc_err(sem_err_non_type_arg_value, e); } } void check_temp_type_arg_linkage(TypeExpr *t) { if (t == NULL) return; switch (h0_(t)) { case t_subscript: case t_ref: case t_content: case t_coloncolon: check_temp_type_arg_linkage(typearg_(t)); break; default: /* the linkage attributes are in the tagbinder; access bits are in the typedef binder. */ if (isprimtype_(t, s_typedefname)) { SET_BITMAP attr = 0; if (isclassorenumtype_(bindtype_(typespecbind_(t)))) attr = attributes_(typespectagbind_(princtype(t))); else if (bindparent_(typespecbind_(t))) attr = attributes_(bindparent_(typespecbind_(t))); if (attr & (A_INTERN+A_NOLINKAGE)) cc_err(sem_err_template_arg_linkage, princtype(t)); } } } /* Attempt to generate a defn from a template for a specific which is not a specialization. */ static void sem_attempt_template_function(Binder *generic, Binder *specific) { BindList *bl; if ((bl = bindftlist_(generic)) == NULL) return; { FormTypeList *ft = typefnargs_(bindtype_(specific)); int len = length((List *)ft); ExprList *l = NULL; BindList *tmpts = NULL; for (; ft; ft = ft->ftcdr) l = mkExprList(l, (Expr *)gentempbinder(ft->fttype)); l = (ExprList *)dreverse(l); for (; bl; bl = bl->bindlistcdr) { Binder *ftemp = bl->bindlistcar; int len2 = length((List *)typefnargs_(bindtype_(ftemp))); if (bindstg_(ftemp) & b_undef || len != len2) continue; tmpts = binder_cons2(tmpts, ftemp); } if ((tmpts = temp_reduce(tmpts, l, NULL, generic)) != NULL) { Binder *ftemp = tmpts->bindlistcar; ScopeSaver env = bindenv_(ftemp); bool has_failed = NO; TypeExpr *t; BindList *bl = bindinstances_(ftemp); for (; bl; bl = bl->bindlistcdr) if (bl->bindlistcar == specific) return; if (currentfunction.symstr == bindsym_(ftemp)) return; t = type_deduction(bindtype_(ftemp), l, NULL, &env, YES, &has_failed); if (has_failed) syserr("type deduction failed, shouldn't happen."); /* Make sure its the type we want. */ if (!equivtype(t, bindtype_(specific))) return; for (bl = typeovldlist_(bindtype_(generic)); bl; bl = bl->bindlistcdr) if (equivtype(bindtype_(bl->bindlistcar), t)) return; t = globalize_typeexpr(t); env = globalize_env(env); fixup_template_arg_type(t, env); add_pendingfn(bindsym_(generic), ovld_tmptfn_instance_name(bindsym_(ftemp), env), t, (bindstg_(bindstg_(specific) & b_impl ? realbinder_(specific) : specific)&~b_undef), NULL, NULL, bindtext_(ftemp), env, YES); } } } bool is_comparable_specialization(TypeExpr *t1, TypeExpr *t2) { if (isclasstype_(t1) && isclasstype_(t2)) { TagBinder *tb1 = typespectagbind_(t1), *tb2 = typespectagbind_(t2); if (tagprimary_(tb1) != NULL && tagprimary_(tb1) == tagprimary_(tb2)) { ScopeSaver f1 = tagactuals_(tb1), f2 = tagactuals_(tb2); for (; f1 && f2; f1 = bindcdr_(f1), f2 = bindcdr_(f2)) if (!istypevar(bindtype_(f1)) && !istypevar(bindtype_(f2))) return NO; /* the equivalence case is tested elsewhere */ return YES; } /* Consider template <T> struct Y { struct X {}; }; and Y<whatever>::X, Y<T>::X == Y<whatever>::X. */ if (tagbindparent_(tb1) != NULL && tagbindparent_(tb2) != NULL && (tagprimary_(tagbindparent_(tb2)) == tagbindparent_(tb1) || tagprimary_(tagbindparent_(tb1)) == tagbindparent_(tb2))) { return YES; } } return NO; } bool is_an_instance(BindList *ins, Binder *b) { for (; ins; ins = ins->bindlistcdr) if (ins->bindlistcar == b) return YES; return NO; } bool has_template_parameter(ScopeSaver tformals) { for (; tformals; tformals = bindcdr_(tformals)) if (contains_typevars(bindtype_(tformals)) || (bindstg_(tformals) == 0 && !bindconst_(tformals))) return YES; return NO; } void add_instance(Binder *b, BindList **bl, bool bindstore) { BindList *l = *bl; Symstr *sv = bindsym_(b); for (; l != NULL; l = l->bindlistcdr) if (sv == bindsym_(l->bindlistcar)) return; *bl = global_cons2((bindstore)? SU_Bind : SU_Type, *bl, b); } bool contains_typevars(TypeExpr *t) { typevars_tag_list = NULL; return contains_typevars_0(t, NO); } bool is_dependent_type(TypeExpr *t) { return contains_typevars_0(t, YES); } bool comparable_templates(TagBinder *tb1, TagBinder *tb2) { ScopeSaver f1 = tagformals_(tb1), f2 = tagformals_(tb2); if (env_size(f1) != env_size(f2)) return NO; for (; f1 && f2; f1 = bindcdr_(f1), f2 = bindcdr_(f2)) if (!equivtype(bindtype_(f1), bindtype_(f2))) return NO; return (f1 == f2) ? YES : NO; } void merge_default_template_args(ScopeSaver new, TagBinder *tempclass, Binder *tempfn) { ScopeSaver old = (tempclass) ? tagformals_(tempclass) : bindformals_(tempfn); bool musthavedefault = NO; int argno = 1; if (env_size(new) != env_size(old)) { if (tempclass) cc_rerr(sem_rerr_template_formal_length_class, tempclass); else cc_rerr(sem_rerr_template_formal_length_function, tempfn); } else for(; new && old; new = bindcdr_(new), old = bindcdr_(old), argno++) { if (old != new && !equivtype(bindtype_(old), bindtype_(new))) cc_rerr(sem_rerr_template_formal_type, bindtype_(old), bindtype_(new)); if (bindconst_(old) != NULL || bindconst_(new) != NULL) { if (bindconst_(old) != NULL) bindconst_(new) = bindconst_(old); /* @@@ check if both exist and consistent */ musthavedefault = YES; } else if (musthavedefault) cc_rerr(sem_err_missing_default_value, argno, bindsym_(old)); } } /* End of xsem.c */
stardot/ncc
cfe/pp.c
<filename>cfe/pp.c /* * C pre-processor, cfe/pp.c * Copyright (C) Codemist Ltd., 1988-1992. * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Advanced RISC Machines Ltd., 1990-1992. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 167 * Checkin $Date$ * Revising $Author$ */ /* AM, july 90: fix pp recursion problem in macro args. */ /* AM: ansi ambiguities: */ /* #defines: i(x)=[x] a=( b=) does i(i a 3 b)->[[3]] or [i(3)]? */ /* AM: bugs: */ /* 1. #error/#ident/#pragma do not parse strings. */ /* 2. #define: j(x)=i(x) i(x)=h##x f=g+f then j(f) *should* be hg+f! */ /* AM: beware the different ANSI/PCC rules for PP_TOKSEP. */ /* AM: memo: rework/kill PP_NOEXPAND in favour of pp_noexpand. Also, */ /* does the use of pp_hashalive resolve ANSI ambiguities as we want? */ /* AM: memo: rework the pp_unrdch() call in pp_checkid(no '('). */ #undef ISO8859 #ifdef COMPILING_ON_ACORN_KIT # define ISO8859 1 #endif #ifdef COMPILING_ON_UNIX # define ISO8859 1 #endif /* The following hack supports ebcdic, pure ascii or iso8859. */ /* We could (more portably) turn each macro into a test on compiler */ /* (not preprocessor) character constants. */ #if 'A' == 193 /* nasty, ansi-non-guaranteed test for ebcdic */ # define legal_non_isprint(ch) 0 #else /* ascii-like presumed */ # ifdef ISO8859 # define legal_non_isprint(ch) ((ch) >= 128+32) # else /* Mac, PC, etc. */ # define legal_non_isprint(ch) ((ch) >= 128) # endif #endif /* * NOTE: This file will need adjustment for use with Pascal and Fortran. * For now, it is left almost unaltered, but with some conversions disabled * in a crude manner, contingent on #ifdef PASCAL, #ifdef FORTRAN, etc. */ /* N.B. This pre-processor conforms to the May 86 draft ANSI spec. */ /* However, there it was defined by example and the Oct 86 draft gave */ /* a more stringent definition by (more) examples! I doubt that it is */ /* up to the latter spec, but propose to do nothing about this until the */ /* next draft spec or standard as further changes are proposed. */ /* AM Jan 90: AM believes that the macro processing is very close to */ /* the latest (Dec 88) ANSI draft modulo ambiguities. */ /* 29-Dec-87: AM has put the profile_xxx stuff here while it is in flux */ /* so that he can try to understand them! In a separate file one day? */ /* Observation: the profile instrumentation fails (due to strcmp) if */ /* a file is included more than once or #line is used. */ /* Memo: chase out '@@@'s. Also abuf for non-essential uses. */ #include <stdio.h> #include <ctype.h> #include <stddef.h> #include <time.h> #ifdef __STDC__ # include <string.h> # include <stdlib.h> # define uint HIDE_HPs_uint # include <limits.h> /* for UCHAR_MAX */ # undef uint #else # define UCHAR_MAX 255 # include <strings.h> #endif #include "globals.h" #include "pp.h" #include "lex.h" #include "syn.h" #include "store.h" #include "errors.h" #include "mcdep.h" #include "dump.h" #include "compiler.h" #include "trackfil.h" #ifndef NO_INSTORE_FILES #include "headers.c" /* Tables for in-store headers */ #endif #ifdef CALLABLE_COMPILER #include "clbcomp.h" #endif #define NOT_A_CHARACTER (512) /* cannot be saved in a char */ /* only to be used in exprs */ #ifdef PASCAL # define PASCAL_OR_FORTRAN 1 # define COMMENT_START '(' # define COMMENT_END ')' #else # ifdef FORTRAN # define PASCAL_OR_FORTRAN 1 # define COMMENT_START NOT_A_CHARACTER /* this will NEVER be found! */ # define COMMENT_END NOT_A_CHARACTER /* this will NEVER be found! */ # else # define COMMENT_START '/' # define COMMENT_END '/' # endif #endif /* * Note that there is much nastiness (probably necessary in C) in the odd * interface of the pre-processor having a back-route into the parser * and HENCE back into itself!!! */ #define PP_HASHSIZE 259L #define PP_DIRLEN 16L /* * PP_DEFLEN is max number of significant chars in an identifier. * It must be LESS than min(PP_ABUFINITSIZ,PP_DBUFSIZ)-UNRDCHMAX. */ #define PP_DEFLEN 250L #define PP_UNRDCHMAX 16L /* see pp_checkid and #pragma force_top_level */ /* * PP_NOEXPAND is a pseudo character to inhibit re-expansion of the * following name (may change to preceding soon). It conspires with * the list pp_noexpand to inhibit recursive expansion. * Two mechanisms are needed in so that in #define i(x) x; #define f +f * the call i(f) causes arg f to re-write to +f(NOEXPAND) and the * re-scan of +f does not cause re-expansion to ++f. * Similarly, PP_TOKSEP is used to represent invisible space in * "M-- where #define M -" which need to be spaces to lex but vanish * in stringify. It also represents elided comments in pcc mode. * AM regards it as odd that the draft (dec 88) seems to say that * stringification (#s) of the above should yield "---" not "- --". * Changing PP_TOKSEP to ' ' in ANSI mode restores the more logical code. * * To avoid stealing characters from the source set, we use '\f' and '\v' * which are only quasi-illegal in ANSI input and which are converted early * (by pp_rdch1()) to '\n', when executing in ANSI mode. * * In -pcc mode, we use the same characters, but pp_rdch() uses '\b' as an * escape code, converting '\b', '\f' and '\v' to PP_ESC PP_ESC, PP_ESC '\t' * and PP_ESC ' ', respectively. The escape sequences are later undone by * pp_process(). BUT ONLY in -pcc mode. */ #define PP_ESC '\b' #define PP_NOEXPAND '\f' #define PP_TOKSEP '\v' #define PP_EOM 0 /* value 0 exploited by strcpy/'%s'. */ #define PP_MACSTART 1 #define PP_CIDCHAR 2 #define PP_WHITE 4 static char pp_ctype[UCHAR_MAX+1]; /* ch & 0xff used to be (unsigned char)ch in the macros below, but some compilers seem not to handle that correctly, and there seems no overwhelming reason for preferring one form to the other. */ #define pp_macstart(ch) (pp_ctype[ch & 0xff] & PP_MACSTART) #define pp_cidchar(ch) (pp_ctype[ch & 0xff] & PP_CIDCHAR) #define pp_white(ch) (pp_ctype[ch & 0xff] & PP_WHITE) #define pp_translation(ch) (pp_translate[ch & 0xff]) #define PP_EOLP(ch) ((ch) == '\n') #define HASH(hash, ch) (((hash * 39) + ch) & 0xffffff) #define PP_ARGLINES_WARN_VAL 10 /* warn after 10 lines of arguments */ #ifdef COMPILING_ON_MAC /* some Mac compilers admit that some high-bit set chars are printable */ /* and some others don't define isprint, etc. above 0x7f (which is non-ANSI) */ # define isdigit(c) ((c & ~0x7f) == 0 && (isdigit)(c)) # define isalpha(c) ((c & ~0x7f) == 0 && (isalpha)(c)) # define isalnum(c) ((c & ~0x7f) == 0 && (isalnum)(c)) # define isspace(c) ((c & ~0x7f) == 0 && (isspace)(c)) # define isprint(c) ((c & ~0x7f) == 0 && (isprint)(c)) #endif /* * structures - local to this file ... */ typedef struct arglist { char *argname; struct arglist *argchain; int32 argactual; /* now offset into pp_abufbase */ #define DUFF_OFFSET 0x01010101 /* beware: it is only our expansion strategy that allows us to use shallow binding of actual/formal correspondence. See later changes in pp_arg_link. */ } PP_ARGENTRY; #define pp_argname_(p) ((p)->argname) #define pp_argchain_(p) ((p)->argchain) #define pp_argactual_(p) ((p)->argactual) typedef union { uint32 w; struct { /* I limit the reference count to 16 bits so that there can not be any */ /* trouble on machines with sizeof(int)==2 */ unsigned int uses:16, /* incremented on reference */ /* ismagic is 14 bits so that this whole field is 32 bits wide */ ismagic:13,/* things like __TIME__ */ noifdef:1, /* 1 if not allowed to #ifdef xxx */ noargs:1, /* 1 if noargs */ alive:1; /* 0 => undef'd, 1 => def'd */ } b; } PP_HASHBITS; typedef struct hashentry { char *name; union { char const *s; int32 i; } body; /* #define text or magic (e.g PP__LINE) */ struct hashentry *chain; PP_HASHBITS u; struct hashentry *defchain; /* chain in definition order */ /* AM: the next two fields solely cope with ANSI inhibition of macro */ /* definitions during rescanning. It would be more space efficient */ /* to use a separate list (next/name/len). Moreover, this current */ /* structure requires a definition to be suppressed only once at any */ /* one time to work. This would seem to be the case, but consider */ /* #define f g(f); #define g(x) x; (@@@ seemingly ANSI ambiguity). */ /* We expand 'f' above to 'f', but there is a good case for the 'f(g)' */ /* interpretation too. */ struct hashentry *unchain; /* used to inhibit recursive expansion */ int32 sleepleft; /* ditto -- chars to read in ebuf. */ #define PP_NOARGHASHENTRY offsetof(PP_HASHENTRY,arglist) struct arglist *arglist; /* only if noargs==0 */ } PP_HASHENTRY; typedef PP_HASHENTRY *(PP_HASHTABLE[PP_HASHSIZE]); #define pp_hashname_(p) ((p)->name) #define pp_hasharglist_(p) ((p)->arglist) #define pp_hashbody_(p) ((p)->body.s) #define pp_hashmagic_(p) ((p)->body.i) #define pp_hashchain_(p) ((p)->chain) #define pp_hashnoargs_(p) ((p)->u.b.noargs) #define pp_hashalive_(p) ((p)->u.b.alive) #define pp_hashismagic_(p) ((p)->u.b.ismagic) #define pp_noifdef_(p) ((p)->u.b.noifdef) #define pp_hashuses_(p) ((p)->u.b.uses) #define pp_unchain_(p) ((p)->unchain) #define pp_sleepleft_(p) ((p)->sleepleft) #define pp_hashdefchain_(p) ((p)->defchain) /* The following constants really are ints, or maybe enums */ #define PP__LINE (-1) #define PP__FILE (-2) #define PP__DATE (-3) #define PP__TIME (-4) #define PP__ZERO (-6) #define PP__ONE (-7) typedef struct ifstack { struct ifstack *chain; bool seenelse; bool oldskip; bool skipelse; } PP_IFSTACK; #define pp_ifchain_(p) ((p)->chain) #define pp_ifseenelse_(p) ((p)->seenelse) #define pp_ifoldskip_(p) ((p)->oldskip) #define pp_ifskipelse_(p) ((p)->skipelse) typedef struct filestack { struct filestack *chain; FILE *stream; FileLine fl; #ifndef NO_LISTING_OUTPUT int32 propoint; int32 filenumber; #endif PP_IFSTACK *ifstart; char const *ifdefname; /* name of macro guarding this #include (if any) */ PP_IFSTACK *guard_ifndef; pp_uncompression_record *stringfile; } PP_FILESTACK; #define pp_filchain_(p) ((p)->chain) #define pp_filstream_(p) ((p)->stream) #define pp_fileline_(p) ((p)->fl) #define pp_propoint_(p) ((p)->propoint) #define pp_filenumber_(p) ((p)->filenumber) #define pp_stringfile_(p) ((p)->stringfile) int pp_inhashif; /*/*should this really belong to syn_hashif? */ static PP_HASHTABLE *pp_hashtable; static PP_HASHENTRY *pp_noexpand, *pp_hashfirst, *pp_hashlast, *pp_hashone, *pp_hashzero; static PP_IFSTACK *pp_ifstack, *pp_freeifstack; static PP_FILESTACK *pp_filestack, *pp_freefilestack; static int32 pp_nsubsts; static bool pp_skipping, pp_instring; typedef enum { NO_COMMENT, BALANCED_COMMENT, EOL_COMMENT } PP_CommentKind; static PP_CommentKind pp_incomment = NO_COMMENT; static bool seen_pp_token; static bool minus_e; static FILE *pp_cis; static FileLine *pp_fl; int32 pp_pragmavec['z'-'a'+1]; static char pp_datetime[26]; /* * Diagnostics and free store package... */ static VoidStar pp_alloc(int32 n) { return GlobAlloc(SU_PP, n); } /* * ACN's listing option code... */ #ifndef NO_LISTING_OUTPUT bool list_this_file; /* exported copy of MSB of pp_filenumber */ /* * @@@ This depends on the ARM-dependent output of _write_profile * and is read directly in binary. (Hmm). */ typedef struct XCount { unsigned32 count; unsigned line:16, filename:16; } XCount; static XCount *profile_data = NULL; /* profile data table */ static int32 profile_count = 0; /* size thereof (0 => no map) */ static char **profile_files = NULL; /* file name table */ static uint32 profile_nfiles = 0; /* size thereof */ static int32 profile_ptr = 0; /* profile_data index ( < profile_count) */ static uint32 pp_filenumber; /* profile_files index ( < profile_nfiles) */ /* also gets 0x80000000 bit set (>= 0 test) */ /* ... only used for listing on/off. */ static int Exec_Rec_Compare(ConstVoidStar a, ConstVoidStar b) { const XCount *aa = (const XCount *)a, *bb = (const XCount *)b; int32 k = (int32)aa->filename - (int32)bb->filename; if (k == 0) k = (int32)aa->line - (int32)bb->line; /* The following line ensures that I return an int value that makes sense */ /* even if plain int is 16 bits. This is needed if I am to use the built- */ /* in qsort sort procedure. */ return k == 0 ? 0 : k < 0 ? -1 : 1; } bool map_init(FILE *mapstream) { /* Data for annotation source listings to indicate how many times various */ /* lines of code is global to the compilation. */ uint32 w; XCount *data; char *namebodies; union map_filetable { int32 offset; char *addr; } *names; struct map_header { char magic[12]; uint32 namebytes, nfiles, ncounts; } h; profile_count = 0; /* To disable the option */ if (mapstream == NULL) return 1; if (fread(&h, sizeof(h), 1, mapstream) != 1 || memcmp("\xff*COUNTFILE*", h.magic, 12) != 0) return 0; w = h.namebytes + 4*h.nfiles + 8*h.ncounts; namebodies = (char *)PermAlloc(w); if (namebodies == NULL) return 0; names = (union map_filetable *)(namebodies + h.namebytes); data = (XCount *)(names + h.nfiles); if (fread(namebodies, 1, (size_t)h.namebytes, mapstream) != h.namebytes || fread(names, 4, (size_t)h.nfiles, mapstream) != h.nfiles || fread(data, 8, (size_t)h.ncounts, mapstream) != h.ncounts || fread(h.magic, 1, 12, mapstream) != 12 || memcmp("\xff*ENDCOUNT*\n", h.magic, 12) != 0) { return 0; } for (w = 0; w < h.nfiles; w++) names[w].addr = namebodies + names[w].offset; /* Now the data is read in - sort it by file name and line number so it */ /* will be easier to access later. */ qsort((VoidStar)data, (size_t)h.ncounts, sizeof(XCount), Exec_Rec_Compare); profile_data = data; profile_count = h.ncounts; profile_files = (char **)names; profile_nfiles = h.nfiles; return 1; } #define CHARS_FOR_COUNTS 16 static void listing_nextline(uint32 ll) { uint32 line = ll + 1; int pos = 0; while (profile_data[profile_ptr].line < line && profile_data[profile_ptr].filename == pp_filenumber && profile_ptr < profile_count) profile_ptr++; while (profile_data[profile_ptr].line == line && profile_data[profile_ptr].filename == pp_filenumber && profile_ptr < profile_count) (pos += fprintf(listingstream, "%lu ", profile_data[profile_ptr].count)), profile_ptr++; if (pos >= CHARS_FOR_COUNTS) fprintf(listingstream, "\n"), pos = 0; fprintf(listingstream, "%*s| ", (int)(CHARS_FOR_COUNTS-pos), ""); } static void profile_find(char const *fname) { unsigned i = 0; int32 p = 0; if (profile_count == 0) return; while (!StrEq(fname, profile_files[i]) && i < profile_nfiles) i++; /* syserr(dropping off the end) */ while (profile_data[p].filename != i && p < profile_count) p++; pp_filenumber = i; profile_ptr = p; } #endif /* NO_LISTING_OUTPUT */ /* * buffers: dbuf (defns) ebuf (expansions) abuf (args) * Maybe optimise later. */ #define PP_DBUFSIZ 1024L /* default chunk for definitions */ #define PP_ABUFINITSIZ 512L #define PP_EBUFINITSIZ 256L #define pp_new_(type) (pp_alloc(type)) static char *pp_dbufend, *pp_dbufseg, *pp_dbufptr; #define pp_stuffid_(ch) \ (pp_dbufptr==pp_dbufend ? pp_newdbuf(ch) : (*pp_dbufptr++ = (ch))) static int pp_newdbuf(int x) { char *dbufbase; unsigned32 size = pp_dbufptr-pp_dbufseg; /* size used in current dbuf */ unsigned32 allocsize = PP_DBUFSIZ; /* default size for new dbuf */ /* allocate 1024 for small requests, but 2048 for 512-1023, etc. */ while (size >= allocsize/2) allocsize *= 2; if (size > allocsize) syserr(syserr_newdbuf, (long)size, (long)allocsize); dbufbase = (char *)pp_alloc(allocsize); #ifdef ENABLE_PP /* spurious: deadcode elimination fixes */ if (debugging(DEBUG_PP)) cc_msg("new pp_dbuf(%ld)\n", (long)allocsize); #endif if (size != 0) memcpy(dbufbase, pp_dbufseg, (size_t)size); pp_dbufseg = dbufbase; pp_dbufptr = dbufbase+size; pp_dbufend = dbufbase+allocsize; return (*pp_dbufptr++ = x); } static char *pp_closeid(void) { char *result; pp_stuffid_(0); result = pp_dbufseg; pp_dbufseg = pp_dbufptr; return result; } static char *pp_ebufbase, *pp_ebufptr, *pp_ebuftop, *pp_ebufend; static char *pp_abufbase, *pp_abufoptr, *pp_abufptr, *pp_abufend; static int32 pp_scanidx, pp_expand_level; static void pp_abuf_ensure(int32 n) { while (pp_abufptr + n >= pp_abufend) { int32 k = pp_abufend - pp_abufbase; char *d = (char *)pp_alloc(2*k); #ifdef ENABLE_PP /* spurious: deadcode elimination fixes */ if (debugging(DEBUG_PP)) cc_msg("up pp_abuf to %ld\n", (long)(2*k)); #endif memcpy(d, pp_abufbase, (size_t)k); pp_abufend = d + 2*k; pp_abufptr = d + (pp_abufptr - pp_abufbase); pp_abufoptr = d + (pp_abufoptr - pp_abufbase); pp_abufbase = d; } } static void pp_wrch(int ch) { if (pp_abufptr >= pp_abufend) pp_abuf_ensure(1); *pp_abufptr++ = ch; } static void pp_wrbuf(void *buf, int32 len) { pp_abuf_ensure(len); pp_abufptr = (char *) memcpy(pp_abufptr, buf, (size_t)len) + len; } static void pp_ebuf_ensure(int32 n) { while (pp_ebuftop + n >= pp_ebufend) { int32 k = pp_ebufend - pp_ebufbase; char *d = (char *)pp_alloc(2*k); #ifdef ENABLE_PP /* spurious: deadcode elimination fixes */ if (debugging(DEBUG_PP)) cc_msg("up pp_ebuf to %ld\n", (long)(2*k)); #endif memcpy(d, pp_ebufbase, (size_t)k); pp_ebufend = d + 2*k; pp_ebuftop = d + (pp_ebuftop - pp_ebufbase); pp_ebufptr = d + (pp_ebufptr - pp_ebufbase); pp_ebufbase = d; } } static void pp_savch(int ch) { if (pp_ebuftop >= pp_ebufend) pp_ebuf_ensure(1); *pp_ebuftop++ = ch; } static void pp_savbuf(void const *buf, int32 len) { pp_ebuf_ensure(len); pp_ebuftop = (char *) memcpy(pp_ebuftop, buf, (size_t)len) + len; } #ifdef ENABLE_PP static void pp_showsleep(void) { PP_HASHENTRY *p; for (p = pp_noexpand; p != 0; p = pp_unchain_(p)) cc_msg("<sleeping %s %ld>", pp_hashname_(p), pp_sleepleft_(p)); } #else #define pp_showsleep() 0 #endif static void pp_addsleep(int32 n) { PP_HASHENTRY *p; for (p = pp_noexpand; p != 0; p = pp_unchain_(p)) pp_sleepleft_(p) += n; } static void pp_subsleep(int32 n) { PP_HASHENTRY *p; for (p = pp_noexpand; p != 0; p = pp_unchain_(p)) { pp_sleepleft_(p) -= n; if (debugging(DEBUG_PP) && pp_sleepleft_(p) < 0) cc_msg("<overslept %s %ld>\n", pp_hashname_(p), pp_sleepleft_(p)); } } static void pp_awaken_all(void) { /* Maybe this should be a syserr() one day if pp_noexpand != 0. */ while (pp_noexpand) { PP_HASHENTRY *p = pp_noexpand; pp_noexpand = pp_unchain_(p), pp_unchain_(p) = 0; pp_hashalive_(p) = 1; } } static void pp_sleep_name(PP_HASHENTRY *p, int32 n) { /* suppress recursive invocations in ANSI mode -- PCC loops! */ if (pp_unchain_(p)) syserr(syserr_pp_recursion, pp_hashname_(p)); pp_unchain_(p) = pp_noexpand; pp_sleepleft_(p) = 0; pp_hashalive_(p) = 0; pp_noexpand = p; pp_addsleep(n); if (debugging(DEBUG_PP)) cc_msg("<sleep name %s, result size %ld>\n", pp_hashname_(p), (long)n); } /* * Support for built-in header files */ static pp_uncompression_record *active_string_file = NO; struct pp_uncompression_record { uint8 stack[32]; uint8 const *pointer; uint8 compressed; uint32 height; uint16 const *compression_info; }; static int pp_fetch_string_char(pp_uncompression_record *ur) { int c, k; c = (ur->height == 0) ? *ur->pointer++ : ur->stack[--ur->height]; for (;;) { k = ur->compression_info[c]; if (k == c || ur->compressed == 0) return c; /* * When genhdrs is establishes the greatest possible depth needed in * this stack and arranges to define HDRSTACKDEPTH suitably - thus no * run-time check for stack overflow is needed. */ ur->stack[ur->height++] = k; c = k >> 8; } } FILE *new_compressed_header(FILE *f, pp_uncompression_record **urp) { uint32 stackdepth; uint32 size; pp_uncompression_record *ur; fread(&stackdepth, sizeof(uint32), 1, f); fread(&size, sizeof(uint32), 1, f); ur = (pp_uncompression_record *)GlobAlloc(SU_Other, sizeof(pp_uncompression_record) + 256 * sizeof(uint16) + size); { uint8 *b = (uint8 *)(ur + 1); fread(b, 1, 256 * sizeof(uint16) + (size_t)size, f); fclose(f); ur->compression_info = (uint16 *)b; ur->pointer = b + 256 * sizeof(uint16); ur->compressed = 1; ur->height = 0; *urp = ur; return stdin; } } #ifndef NO_INSTORE_FILES static pp_uncompression_record hdrfile; FILE *open_builtin_header(const char *name, pp_uncompression_record **urp) { int count; if ((feature & FEATURE_PCC) && StrEq(name, "strings.h")) name = "string.h"; for (count=0; builtin_headers[count].name != 0; count++) { if (StrEq(name, builtin_headers[count].name)) { *urp = &hdrfile; hdrfile.height = 0; hdrfile.compressed = 1; hdrfile.pointer = &string_data[builtin_headers[count].content]; hdrfile.compression_info = compression_info; /* * The result (which is of type FILE *) must be handed back as a non-zero * value since it is compared against zero to check for success here. But * when a string file has been opened the regular file pointer will never be * used, so the (non-zero) value returned is not very important. * The arbitrary use of 'stdin' is thus OK since ANSI say 'stdin' != NULL. */ return stdin; } } return NULL; } #endif /* * I/O routines, including ANSI trigraph routine. Built for speed. * * The idea we exploit here is that (i) only whole lines are interleaved by * #include and (ii) after a #included file has been processed, we continue * reading the NEXT line of the including file. By buffering whole lines, * we can reduce most overhead to once per line, rather than one per char. * As lines average 30-40 chars, this gives a major reduction in per-char * overhead. We also take the opportunity to unify in-store files with * regular files at this point. The only difference is that we don't copy * in-store files to the (partial) line buffer. The critical routines * are pp_fillbuf, pp_rdch1 and pp_rdch. pp_translate_1, pp_comment * and pp_comment_nl play supporting roles. The best order to read for * understanding is pp_rdch, pp_rdch1, pp_fillbuf, others. */ static int32 pp_rdcnt; /* the input buffer count */ static char *pp_rdptr; /* the input buffer pointer */ static char pp_linebuf[64]; /* the input line buffer */ static char pp_translate[256]; static int pp_rdch1nls, /* count of \<NL>s outstanding */ pp_rdch3nls; /* count of <NL>s in current comment */ static bool pp_in_directive; /* pend pp_rdch3nls after '#'. */ static void init_pp_fl(char const *filename) { pp_fl->f = filename; pp_fl->l = 1; pp_fl->column = 1; pp_fl->filepos = 0; /* ### morally right here ? */ pp_fl->p = 0; pp_rdcnt = 0; pp_rdptr = NULL; } /* After a call to pp_fillbuf(), pp_rdptr points to the tail of a line or */ /* part thereof, pp_rdcnt is the number of chars left in the buffer and */ /* the first character of the buffer (or EOF) is returned (we do this */ /* because EOF cannot be stored as a character). */ static int pp_fillbuf(void) { uint32 n; char *s; #ifdef NO_MLS_XDEVT_1823 /* * move the progress to cfe/rd_topdecl() to reduce overhead */ UpdateProgress(); #endif /* We now count \n when we read it (since file positions are now sampled * by lex at the start of each symbol). */ s = pp_linebuf; #ifndef NO_INSTORE_FILES if (active_string_file != NULL) /* If reading from a compressed, in-memory, string file then get the next */ /* line. Note that we know that lines are terminated by \n, that a \n */ /* precedes EOF, and that there are NO imbedded #includes. */ { int ch; for (n = 0; n < sizeof(pp_linebuf);) { ch = pp_fetch_string_char(active_string_file); if (ch == 0) break; s[n++] = ch; if (ch == '\n') break; } } else #endif #ifdef CALLABLE_COMPILER if (expr_string != NULL) { strncpy(s, expr_string, sizeof(pp_linebuf)); n = strlen(s); expr_string += n; } else #endif /* Reading from a real file. Here, pp_rdcnt == 0 OR pp_rdcnt == 1 and */ /* the last character in the buffer should be saved before reading more */ /* (it's either '\' or '?'). Any other value of pp_rdcnt is ignored. */ { FILE *cis = pp_cis; int ch; if ((n = pp_rdcnt) == 1) s[0] = pp_rdptr[-1]; else n = 0; /* Read until EOF OR buffer full OR end of line character found */ for (;;) { ch = getc(cis); if (feof(cis)) break; s[n++] = ch; if (ch == '\n' || ch == '\r' || n >= sizeof(pp_linebuf)) break; } if (ferror(cis)) cc_fatalerr(pp_fatalerr_readfail); if (n == 0) /* end of file */ { if (pp_rdptr != NULL && pp_rdptr[-1] != '\n') { #ifndef HOST_DOES_NOT_FORCE_TRAILING_NL if (feature & FEATURE_FUSSY) cc_pccwarn(pp_rerr_newline_eof); #endif s[n++] = '\n'; /* fake nl before EOF */ } } else if ((ch == '\n' || ch == '\r') && !pp_instring && !inputfromtty) { int nextch = getc(cis); /* This read-ahead is */ if ((ch + nextch) == ('\r' + '\n')) /* tough on cc -S - */ s[n-1] = '\n'; /* if the following */ else ungetc(nextch, cis); /* ungetc() happens.. */ } } #ifndef NO_LISTING_OUTPUT /* The following predicate is now once/line, rather than once/char. */ if (listingstream && (n > 0) && /* => NOT EOF */ !(pp_filenumber & 0x80000000) && (feature & FEATURE_UNEXPANDED_LISTING)) { fwrite(s, 1, (size_t)n, listingstream); /* we may be listing part of a line, so care with \n condition. */ if (s[n-1] == '\n') { listing_diagnostics(); if (profile_count) listing_nextline(pp_fl->l); fprintf(listingstream, "%6u ", pp_fl->l+1); } } #endif /* NO_LISTING_OUTPUT */ if (n == 0) { pp_rdcnt = 0; pp_rdptr = NULL; return PP_EOF; } else { pp_rdcnt = n-1; pp_rdptr = s+1; return (*s &0xff); } } static int pp_translate_1(int ch) { /* Translate COMMENT_START, '\n', ANSI tri-glyphs and \<nl>. Note that */ /* \<nl> can't occur in a tri-glyph, but ?? / can occur before \n... */ #ifdef PASCAL if (ch == '{') return ch; #endif if (ch == COMMENT_START) return ch; if (ch == '\n') { ++pp_fl->l; pp_fl->filepos += (int32) pp_fl->column; pp_fl->column = 1; if (pp_rdch1nls > 0) /* return a \n saved up from \<nl> */ { --pp_rdch1nls; /* one less to return next time... */ ++pp_rdcnt; /* and unget the pending '\n'... */ --pp_rdptr; } return ch; } #ifndef PASCAL else if (ch == '?') /* possible triglyph alert */ { int32 n = pp_rdcnt; /* NB - only in ANSI mode. */ char *s = pp_rdptr; if (n == 0 || n == 1 && s[0] == '?') { if (n == 0) ++pp_rdcnt; /* Seen '?' - copy to buffer */ pp_fillbuf(); /* skip 1st char of buffer */ if (n == 1) /* Seen ?? - point to second */ { ++pp_rdcnt; --pp_rdptr; /* '?'... either way, end up */ } /* pointing at 'x' of ?x... */ n = pp_rdcnt; if (n < 2) return '?'; s = pp_rdptr; } if (s[0] != '?') return '?'; /* If we really wanted to compile this code in an environment where */ /* 7 bit ascii chars were not available, then we have have to change */ /* the following character constants to their trigraph form too. */ switch(s[1]) { default: return '?'; case '=': ch = '#'; break; case '(': ch = '['; break; case '/': ch = '\\'; break; case ')': ch = ']'; break; case '\'': ch = '^'; break; case '<': ch = '{'; break; case '!': ch = '|'; break; case '>': ch = '}'; break; case '-': ch = '~'; break; } pp_rdcnt = n - 2; pp_rdptr = s + 2; pp_fl->column += 2; if (pp_incomment == NO_COMMENT) cc_warn(pp_warn_triglyph,(int)'?', (int)'?', (int)s[1], (int)ch); if (ch != '\\') return ch; /* else ch == '\\' so drop through in case next char is '\n' */ } if (ch == '\\') { int32 n = pp_rdcnt; if (n == 0) { ++pp_rdcnt; pp_fillbuf(); n = pp_rdcnt; if (n == 0) return '\\'; } if (pp_rdptr[0] != '\n') return '\\'; if (pp_incomment == EOL_COMMENT) cc_warn(pp_warn_continued_comment); ++pp_rdptr; pp_rdcnt = n - 1; ++pp_rdch1nls; return PP_EOF; } #endif /* In -pcc mode, can get here with ch == PP_TOKSEP - should not fault. */ /* Otherwise, this function never gets called in -pcc mode (see pp_init */ /* and how it sets pp_translate[] for an explanation). */ if (!(feature & FEATURE_PCC)) { if (pp_incomment != NO_COMMENT) cc_warn(pp_rerr_nonprint_char, ch); else { cc_rerr(pp_rerr_nonprint_char, ch); return PP_EOF; } } return ch; } static int pp_rdch1(void) { int ch, trch; /* This function embodies much critical per-character overhead so we work */ /* hard to make it fast in the common cases, even at the cost of making */ /* uncommon cases (such as '\n', '?', '\\' and EOF) slower. The idea is that */ /* exception (PP_TOKSEP) entries in a translate table flag complex cases. */ for (;;) { if (--pp_rdcnt >= 0) { ch = *pp_rdptr++; ++pp_fl->column; } else { ch = pp_fillbuf(); if (ch == PP_EOF) return ch; } if ((trch = pp_translation(ch)) != PP_TOKSEP) return trch; /* In -pcc mode, we only get here if ch == PP_TOKSEP, literally. */ trch = pp_translate_1(ch); if (trch != PP_EOF) return trch; } } static int pp_comment(int ch) /* After recognising a comment start, this function is called to read the */ /* remainder of it. We do this to save per-character overhead in pp_rdch(), */ /* which is, otherwise, burdened with this monster's procedure prologue... */ { int comment_nest = 1; if (feature & FEATURE_PPCOMMENT) { /* Assert: ch == '{' || ch == '*' */ /* N.B. output to stdout BY DEFINITION of cc -C. Similarly below */ if (ch != '{') putc(COMMENT_START, stdout); putc(ch, stdout); } pp_incomment = BALANCED_COMMENT; ch = pp_rdch1(); for (;;) { if (ch != PP_EOF && feature & FEATURE_PPCOMMENT) putc(ch, stdout); switch (ch) { case PP_EOF: cc_err(pp_err_eof_comment); return PP_EOF; case '\n': if (!(feature & FEATURE_PPCOMMENT)) ++pp_rdch3nls; break; default: break; #ifdef PASCAL case '}': case '{': if (ch == '{') { cc_warn(pp_warn_nested_comment); } else { --comment_nest; if (comment_nest == 0) { if (feature & FEATURE_PPCOMMENT) putc(ch, stdout); return ' '; } } break; #endif case COMMENT_START: ch = pp_rdch1(); if (ch == '*') { if (!(feature & FEATURE_PCC)) cc_warn(pp_warn_nested_comment, "/*"); } continue; case '*': ch = pp_rdch1(); if (ch == COMMENT_END) --comment_nest; if (comment_nest == 0) { if (feature & FEATURE_PPCOMMENT) putc(ch, stdout); if (feature & (FEATURE_PCC | FEATURE_PPCOMMENT)) return PP_TOKSEP; /* comments vanish but have */ else /* separating value... */ return ' '; /* comments -> single space */ } continue; } ch = pp_rdch1(); } pp_incomment = NO_COMMENT; } /* * pp_rdch() selects the next character from one of two buffers (during * macro expansion) or reads the next character from the input stream * (notionally pp_rdch1()). If it takes a character from the input stream, * its job is also to reduce comments to single spaces (ANSI) or PP_TOKSEP * (pcc mode). This is the most critical function called once per character * and its implementation is slightly twisted to save cycles. */ static int pp_rdch_la = 0; static int pp_rdch(void) { int ch, trch; if ((ch = pp_rdch_la) != 0) { pp_rdch_la = 0; return ch; } /* AM: perform special case code if we are rescanning: */ if (!(pp_scanidx < 0 && pp_ebufptr==pp_ebuftop)) { PP_HASHENTRY *p; /* AM: note that we rely on PP_TOKSEP at end of expansions to stop */ /* read-ahead for more isalnum's reading via pp_rdch() and so */ /* defeating recursion trapping in #define f f. */ /* Note pp_unchain/pp_sleepleft comment re stack nature of sleep. */ if (pp_noexpand) { /* move following code to pp_subsleep? Beware pp_argexpand(). */ while (pp_noexpand && pp_sleepleft_(pp_noexpand) <= 0) { p = pp_noexpand; pp_noexpand = pp_unchain_(p), pp_unchain_(p) = 0; pp_hashalive_(p) = 1; } pp_subsleep(1); } return (pp_scanidx >= 0) ? pp_abufbase[pp_scanidx++] : *pp_ebufptr++; } /* pp_noexpand is notionally 0 here -- insert syserr() soon? */ /* For the time being leave the nice safe code: */ if (pp_noexpand) pp_awaken_all(); /* And now we drop through into the remnants of pp_rdch3()... */ if (pp_rdch3nls > 0 && !pp_in_directive) { /* output saved nls from within comments, but wait until end */ /* of '#' directive before doing so. */ --pp_rdch3nls; return '\n'; } if (pp_rdcnt > 0) /* The usual case - the line buffer is non-empty... */ { ch = *pp_rdptr; if ((trch = pp_translation(ch)) != PP_TOKSEP) /* The usual case of a non-exceptional character, so take the short cut. */ /* (i.e. not '\n', '\\', COMMENT_START, EOF, or, in ANSI mode, '?'). */ { ++pp_rdptr; --pp_rdcnt; ++pp_fl->column; return trch; } } ch = pp_rdch1(); /* In ANSI mode, the following code is never executed: PP_TOKSEP and */ /* PP_NOEXPAND have been mapped to '\n' and PP_ESC has been faulted */ /* and ignored. In -pcc mode, the literal chars are mapped to escape */ /* sequences and later mapped back by pp_process(). */ if (ch == PP_ESC || ch == PP_TOKSEP || ch == PP_NOEXPAND) { pp_rdch_la = ch == PP_ESC ? PP_ESC : ch == PP_TOKSEP ? ' ' : '\t'; return PP_ESC; } if ((ch != COMMENT_START #ifdef PASCAL && ch != '{' #endif ) || pp_instring) return ch; #ifdef PASCAL if (ch != '{') #endif { ch = pp_rdch1(); if (LanguageIsCPlusPlus || !(feature & FEATURE_FUSSY)) if (ch == '/') { pp_incomment = EOL_COMMENT; if (feature & FEATURE_PPCOMMENT) { putc('/', stdout); putc(ch, stdout); } for (;;) { if ((ch = pp_rdch1()) == '\n' || ch == PP_EOF) { pp_incomment = NO_COMMENT; if ((feature & FEATURE_PPCOMMENT) && ch == '\n') putc(ch, stdout); return ch; } else if (feature & FEATURE_PPCOMMENT) putc(ch, stdout); } } if (ch != '*') /* unget ch... */ { ++pp_rdcnt; /* which is */ --pp_rdptr; /* always safe */ --pp_fl->column; if (ch == '\n') --pp_fl->l; /* pp_fl->column is zero but not for long */ return COMMENT_START; } } return pp_comment(ch); } /* Do not call pp_unrdch() more than UNRDCHMAX times. */ /* Jun 90: pp_unrdch probably shouldn't write to pp_abufbase[] */ /* following fix to "fnlikemacro <non lparen>", but leave for now. */ static void pp_unrdch(int ch) { if (ch == PP_EOF); /* safety when input from file */ else if (pp_scanidx > 0) { pp_addsleep(1); pp_abufbase[--pp_scanidx] = ch; } else { pp_addsleep(1); *--pp_ebufptr = ch; } } static int pp_skipb0(void) { int ch; do {ch = pp_rdch();} while (ch != PP_EOF && pp_white(ch)); return ch; } static int pp_skipb1(int ch) { while (ch != PP_EOF && pp_white(ch)) ch = pp_rdch(); return ch; } /* Note the following (required by ANSI draft of Dec 88) causes the */ /* text "0xee+getchar()" NOT to expand getchar. */ /* The routine pp_number corresponds to ANSI pp-number save that */ /* the caller has already passed on any leading '.'. The pp_ch arg */ /* is presumed to satisfy 'isdigit'. */ /* In PCC mode we allow characters after E+/e- to be expanded (note */ /* this allows X to be expanded both in 0xee+X and 3.4e+X). */ static void pp_number(int pp_ch) { while (isdigit(pp_ch) || pp_cidchar(pp_ch) || pp_ch == '.') { int c = pp_ch; if (!pp_skipping) pp_wrch(pp_ch); pp_ch = pp_rdch(); if ((c == 'e' || c == 'E') && (pp_ch == '+' || pp_ch == '-') && !(feature & FEATURE_PCC)) { if (!pp_skipping) pp_wrch(pp_ch); pp_ch = pp_rdch(); } } pp_unrdch(pp_ch); } static int32 pp_savnumber(char const *p) /* p is a buffer holding a number in text form. Return offset beyond it */ /* and copy into expansion buffer. */ /* Only used from pp_argexpand (and hence in ANSI mode). */ { int32 i = 0; int ch = p[i++]; while (isdigit(ch) || pp_cidchar(ch) || ch == '.') { int c = ch; ch = p[i++]; if ((c == 'e' || c == 'E') && (ch == '+' || ch == '-')) ch = p[i++]; } i--; /* because 'i' is now one beyond first non-digit. */ pp_savbuf(p, i); return i; } #define pp_widestrbeg(a,b) ((a) == 'L' && ((b) == '"' || (b) == '\'')) /* pp_copystring notionally returns type void, but so that things like */ /* ... "nonterminated string <nl>#define ..." can be recognised it */ /* returns a suitable char for pp_process to use as pp_lastch. */ static int pp_copystring(int quote) { int pp_ch; pp_instring = 1; if (!pp_skipping) pp_wrch(quote); while ((pp_ch = pp_rdch()) != quote) { switch (pp_ch) { case PP_EOF: cc_err(pp_err_eof_string); goto out; case '\n': --pp_fl->l; /* correct line numbers in following msgs */ if (feature & FEATURE_PCC) quote = 0; else if (pp_skipping && !(feature & FEATURE_FUSSY)) { cc_warn(pp_warn_eol_string_skipped, (int)quote); quote = 0; } else cc_err(pp_err_eol_string, (int)quote); ++pp_fl->l; goto out; default: if (!pp_skipping) pp_wrch(pp_ch); break; #ifndef PASCAL case '\\': if (!pp_skipping) pp_wrch('\\'); switch (pp_ch = pp_rdch()) { case PP_EOF: cc_err(pp_err_eof_escape); goto out; case '\n': pp_wrch(pp_ch); break; default: if (!pp_skipping) pp_wrch(pp_ch); break; } #endif } } out: if (!pp_skipping && (quote != 0)) pp_wrch(quote); if (pp_ch == '\n') pp_wrch(pp_ch); pp_instring = 0; return pp_ch; } static void pp_stuffstring(int quote, bool dequote, bool discard) /* dequote = 0: leave quotes alone; dequote = 1: remove " for #include. */ /* For #include we treat \ escapes specially for msdos file specs. */ /* [ANSI says escapes in #include/#line are undefined.] */ /* We arrange that #include both "a:\\foo\\baz" and "a:\foo\baz" work */ /* by collapsing \\ to \ but \a to \a if dequote == 1. (Of course, */ /* things like ...include "abc\<nl>def"... will be glued earlier.) */ /* For filenames (dequote true) we also discard all whitespace. This is */ /* to be kind to #include < stdio . h > in case (for instance) it */ /* has been created via macro-expansion where stray whitespace may be */ /* hard to control and understand. */ { int pp_ch; bool err = 0; pp_instring = 1; if (!dequote & !discard) pp_stuffid_(quote); while ((pp_ch = pp_rdch()) != quote) { switch (pp_ch) { case PP_EOF: case '\n': err = 1; goto out; default: if (!discard #ifndef ALLOW_WHITESPACE_IN_FILENAMES && (!dequote || !isspace(pp_ch)) #endif ) pp_stuffid_(pp_ch); break; #ifndef PASCAL /*ECN*/ case '\\': if (!discard) pp_stuffid_('\\'); switch (pp_ch = pp_rdch()) { case PP_EOF: case '\n': err = 1; goto out; case '\\': if (dequote) break; /* drop through */ default: if (!discard) pp_stuffid_(pp_ch); break; } #endif } } out: if (err) pp_unrdch(pp_ch), cc_err(pp_err_missing_quote, (int)quote); if (!dequote && !discard) pp_stuffid_(quote); pp_instring = 0; } static int32 pp_savstring(char const *p) /* p is a buffer holding a string in text form. Copy into expansion */ /* buffer and return length copied. */ { int quote = *p; int32 i = 0; for (;;) { int ch = p[++i]; if (ch == quote) { ++i; break; } if (ch == 0) break; /* really malformed */ #ifndef PASCAL if (ch == '\\') if (p[++i] == 0) break; /* really malformed */ #endif } pp_savbuf(p, i); return i; } static bool pp_eqname(char const *s, char const *v, int32 n) /* like strcmp but 2nd arg is base/length format */ { while (n-- > 0) if (*s++ != *v++) return 0; if (*s != 0) return 0; return 1; } static char *pp_special(int32 n, char *s) { switch (n) { default: syserr(syserr_pp_special, (long)n); return ""; case PP__LINE: sprintf(s, "%d", pp_fl->l); return s; case PP__FILE: /* double '\' from msdos file names for lex.c: */ /* escape '"' to '\"' to keep sane too. */ /* notionally: sprintf(s, "\"%s\"", pp_fl->f); */ { char *p = s; char const *q = pp_fl->f; int ch; *p++ = '\"'; while ((ch = *q++) != 0) { if (ch == '\\' || ch == '"') *p++ = '\\'; *p++ = ch; } *p++ = '\"'; *p++ = 0; return s; } /* see the spec of asctime for the following numbers */ case PP__DATE: sprintf(s, "\"%.7s%.4s\"", pp_datetime+4, pp_datetime+20); return s; case PP__TIME: sprintf(s, "\"%.8s\"", pp_datetime+11); return s; case PP__ZERO: return "0"; case PP__ONE: return "1"; } } /* Some re-ordering of routines desirable... */ static bool pp_checkid(int ch); static PP_ARGENTRY *pp_findarg(PP_ARGENTRY *a, char const *id, int32 n); #ifdef ENABLE_PP static void pp_show_buffers(char const *msg) { char *s; cc_msg("%s: %*s(ebuf = '", msg, (int)pp_expand_level*2, ""); for (s = pp_ebufbase+PP_UNRDCHMAX; s != pp_ebufptr; ++s) cc_msg("%c", *s); cc_msg("!"); for (;s != pp_ebuftop; ++s) cc_msg("%c", *s); cc_msg("', abuf = '"); for (s = pp_abufbase; s != pp_abufptr; ++s) cc_msg("%c", *s); cc_msg("')\n"); } #else #define pp_show_buffers(x) #endif static void pp_argexpand(int32 ap) { /* arg (ap) is an offset into abuf, pp_scanidx>=0 iff rescanning. */ /* result is put into ebuf. */ /* AM: (ANSI ambiguity) it is not clear whether expansion should be */ /* depth-first or breadth-first: consider a(b) where a=f b=) f(x)=3. */ /* We now do depth-first to match top-level. */ /* N.b. there is scope for re-organising buffer (ap) reuse. */ int32 scanidx = pp_scanidx; int32 doneseg = 0; for (;;) /* retry until no more macros expand. */ { int32 sav_ebuftop = pp_ebuftop - pp_ebufbase; int32 sav_abufptr = pp_abufptr - pp_abufbase; int32 apsleepbase = ap + doneseg; if (debugging(DEBUG_PP)) cc_msg("pp_argexpand('%s'+%lu) %lu ", pp_abufbase+ap, doneseg, ap), pp_showsleep(), cc_msg("\n"); /* copy previously substituted text in arg: */ if (doneseg != 0) /* test technically spurious */ { pp_savbuf(pp_abufbase+ap, doneseg), ap += doneseg; } /* copy tokens literally, but stopping after first substitution: */ /* @@@ nastiness: the direct use of pp_abufbase[] instead of pp_rdch() */ /* is an efficiency hack beyond its sense. It causes the miserable */ /* pp_subsleep(...apsleepbase...) calls. */ for (;;) { int ch = pp_abufbase[ap]; if (ch == PP_EOM) /* no expansions this time round. */ { pp_subsleep(ap-apsleepbase); /* OK, but ignored by caller. */ pp_abufptr = pp_abufbase + sav_abufptr; pp_scanidx = scanidx; return; } else if (pp_macstart(ch) || ch == PP_NOEXPAND) { bool changes; doneseg = (pp_ebuftop - pp_ebufbase) - sav_ebuftop; pp_subsleep(ap+1 - apsleepbase); pp_scanidx = ap+1; changes = pp_checkid(ch); ap = pp_scanidx; apsleepbase = ap; /* copy chars after any macro substitution and rescan. */ if (changes) { int32 n = strlen(pp_abufbase+ap); pp_savbuf(pp_abufbase+ap, n+1); break; } } else if (isdigit(ch)) ap += pp_savnumber(pp_abufbase+ap); else if (ch == '"' || ch == '\'') ap += pp_savstring(pp_abufbase+ap); else pp_savch(ch), ++ap; } pp_abufptr = pp_abufbase + sav_abufptr; /* reset 'ap' to result of ebuf expansion and repeat. */ ap = pp_abufptr - pp_abufbase; pp_wrbuf(pp_ebufbase + sav_ebuftop, pp_ebuftop - (pp_ebufbase + sav_ebuftop)); pp_ebuftop = pp_ebufbase + sav_ebuftop; pp_wrch(PP_EOM); } } /* pp_expand expands a macro whose args are in abuf into ebuf. */ static void pp_expand(PP_HASHENTRY *p, int32 nlsinargs) { int dch; int hashflag = 0; /* always 0 in PCC mode. */ int in_string = 0; /* always 0 in ANSI mode */ char const *dp; char specialbuf[256]; int32 aftercallchars = pp_ebuftop-pp_ebufptr; /* n.b. at top level (scanidx==-1), aftercall chars are the '+asd' */ /* caused after expanding f with #define f x+asd; #define x <whatever>. */ /* When in pp_argexpand this can include both pre- and post- call chars */ int32 sav_abufptr = pp_abufptr-pp_abufbase; /* aftercallchars' home */ pp_hashuses_(p)++; if (debugging(DEBUG_PP)) { if (aftercallchars != 0) cc_msg("aftercallchars(idx %ld) = '%.*s' at %d\n", (long)pp_scanidx, (int)aftercallchars, pp_ebufptr, pp_ebufptr-pp_ebufbase); } if (pp_scanidx < 0) { /* first copy stuff in ebuf after the macro call to after last actual */ pp_wrbuf(pp_ebufptr, aftercallchars); pp_ebufptr = pp_ebuftop = pp_ebufbase + PP_UNRDCHMAX; } dp = pp_hashismagic_(p) ? pp_special(pp_hashmagic_(p), specialbuf) : pp_hashbody_(p); #ifdef ENABLE_PP /* spurious: deadcode elimination fixes */ if (debugging(DEBUG_PP)) { cc_msg("pp_expand(%s) = '%s'\n", pp_hashname_(p), dp); pp_show_buffers("e1"); } ++pp_expand_level; #endif if (!(feature & FEATURE_PCC)) pp_savch(PP_TOKSEP); /* no glueing */ while ((dch = *dp) != 0) switch (dch) { case '%': if (feature & FEATURE_PCC || dp[1] != ':') goto defaultcase; if (dp[2] == '%' && dp[3] == ':') { hashflag |= 2; dp += 4; } else if (pp_hashnoargs_(p)) { goto defaultcase; } else { hashflag |= 1; dp += 2; } while (*dp == ' ') dp++; /* whitespace ANSI normalised. */ break; case '#': if ((feature & FEATURE_PCC) || (pp_hashnoargs_(p) && dp[1] != '#')) goto defaultcase; /* no '#' operators in pcc-mode macro-expansion... */ /* or inside non-function macros */ /* consider cases like f(a,b) == a ## # b. */ ++dp; if (*dp == '#') {hashflag |= 2; ++dp;} else hashflag |= 1; while (*dp == ' ') dp++; /* whitespace ANSI normalised. */ break; case '\'': case '"': if (!(feature & FEATURE_PCC)) { dp += pp_savstring(dp); hashflag = 0; break; } if (dch == in_string && dp[-1] != '\\') in_string = 0; else if (in_string == 0) in_string = dch; /* if in pcc mode then fall through to default case */ defaultcase: default: if (pp_macstart(dch)) { int32 i = 0; PP_ARGENTRY *a; do i++, dp++; while (pp_cidchar(*dp)); a = pp_hashnoargs_(p) ? 0 : pp_findarg(pp_hasharglist_(p), dp-i, i); if (hashflag == 0 && /* not # or ## prefixed, maybe suffixed */ !(feature & FEATURE_PCC)) { char const *s = dp; while (*s == ' ') ++s; /* whitespace ANSI normalised. */ if ((s[0] == '#' && s[1] == '#') || (s[0] == '%' && s[1] == ':' && s[2] == '%' && s[3] == ':')) hashflag = 2; } if (hashflag & 1) pp_savch('"'); if (a == 0) pp_savbuf(dp-i, i); /* not an arg */ else { /* an arg 'a' to include/expand */ int32 ap = pp_argactual_(a); if (in_string) { cc_warn(pp_warn_macro_arg_exp_in_string, pp_argname_(a), pp_hashname_(p), in_string, in_string); } if (hashflag == 0 && !(feature & FEATURE_PCC)) { PP_HASHENTRY *oldsleepers = pp_noexpand; pp_noexpand = 0; pp_savch(PP_TOKSEP); /* no glueing */ pp_argexpand(ap); pp_savch(PP_TOKSEP); /* no glueing */ pp_awaken_all(); pp_noexpand = oldsleepers; if (debugging(DEBUG_PP)) { cc_msg("pp_argexpanded(%s)\n", pp_abufbase+ap); pp_show_buffers("r1"); } } else { int ch, lastch = 0, in_string = 0; while ((ch = pp_abufbase[ap++]) != 0) /* PP_EOM */ { if (!in_string) { if (ch == '"' || ch == '\'') in_string = ch; } else if (lastch != '\\' && ch == in_string) in_string = 256; if ((hashflag & 1) && in_string && (ch == '"' || ch == '\\')) /* Note hashflag == 0 in PCC mode. */ /* When stringising escape '"' and '\' so that */ /* stringise('\"') and stringise(\) work. */ pp_savch('\\'); /* @@@ bug: next line is wrong removing all PP_NOEXPAND: see file head. */ if (!(hashflag & 2 && ch == PP_NOEXPAND || hashflag & 1 && ch == PP_TOKSEP)) pp_savch(ch); lastch = ch; if (in_string == 256) in_string = 0; } } } if (hashflag & 1) pp_savch('"'); } else /* i.e. any char but "'# */ { /* note: dch cannot be PP_TOKSEP in ANSI mode. */ if (dch != PP_TOKSEP) pp_savch(*dp); ++dp; } /* The next line rests on ANSI whitespace normalisation. */ if (dp[0] == ' ' && ((dp[1] == '#' && dp[2] == '#') || (dp[1] == '%' && dp[2] == ':' && dp[3] == '%' && dp[4] == ':')) && !(feature & FEATURE_PCC)) dp++; hashflag = 0; break; } if (!(feature & FEATURE_PCC)) pp_savch(PP_TOKSEP); /* no glueing */ if (!pp_hashnoargs_(p)) { PP_ARGENTRY *a; for (a = pp_hasharglist_(p); a != 0; a = pp_argchain_(a)) { int32 i = pp_argactual_(a); pp_argactual_(a) = *((int32 *)(pp_abufbase+i-sizeof(int32))); } } if (pp_scanidx < 0) { while (nlsinargs-- > 0) pp_savch('\n'); /* save up the NL's in args */ if (!(feature & FEATURE_PCC)) /* suppress recursive invocations in ANSI mode -- PCC loops! */ pp_sleep_name(p, pp_ebuftop - (pp_ebufbase + PP_UNRDCHMAX)); if (debugging(DEBUG_PP)) cc_msg("restore aftercall(%.*s)\n", (int)aftercallchars, pp_abufbase+sav_abufptr); pp_savbuf(pp_abufbase+sav_abufptr, aftercallchars); pp_abufptr = pp_abufbase; /* clear for (top level) rescan */ } else if (!(feature & FEATURE_PCC)) /* suppress recursive invocations in ANSI mode -- PCC loops! */ pp_sleep_name(p, pp_ebuftop - (pp_ebufbase + PP_UNRDCHMAX) - aftercallchars); pp_nsubsts++; #ifdef ENABLE_PP /* spurious: deadcode elimination fixes */ --pp_expand_level; if (debugging(DEBUG_PP)) pp_show_buffers("e2"); #endif } static PP_HASHENTRY *pp_lookup(char const *name, int32 hash) { PP_HASHENTRY *p; for (p = (*pp_hashtable)[hash % PP_HASHSIZE]; p != 0; p = pp_hashchain_(p)) if (pp_hashalive_(p) && StrEq(pp_hashname_(p),name)) break; return p; } static PP_HASHENTRY *pp_lookup_name(char const *name) { int32 i = 0, hash = 0; for (;;) { int ch = name[i]; if (!pp_cidchar(ch)) break; if (i < PP_DEFLEN) hash = HASH(hash, ch); ++i; } return pp_lookup(name, hash); } /* The following routines are just used by pp_checkid: */ static void pp_arg_align(void) { while ((IPtr)pp_abufptr & (sizeof(IPtr)-1)) pp_wrch(0); pp_abufptr += sizeof(int32); /* IPtr? */ } static void pp_arg_link(PP_ARGENTRY *a, int32 arg) { *((int32 *)(pp_abufbase + arg - sizeof(int32))) = pp_argactual_(a); pp_argactual_(a) = arg; } /* AM Jan 90: These routines hopefully preserve previous PCC behaviour */ /* but maybe ought to be reviewed as sysV PCC seems to differ. */ static void pp_trimarg(char *abufarg) { while (pp_abufptr != abufarg && (pp_abufptr[-1] == ' ' || pp_abufptr[-1] == PP_TOKSEP)) pp_abufptr--; /* trim off trailing spaces/token separators. */ } static void pp_spacearg(int ch) { /* Adds a space to the end of an argument, but keeps it in normal */ /* form (at most one space or PP_TOKSEP at end). */ /* A space takes priority over PP_TOKSEP due to ANSI rules. */ /* Caller ensures pp_abufptr[-1] valid. ch is space or PP_TOKSEP. */ if (pp_abufptr[-1] == PP_TOKSEP) pp_abufptr--; if (pp_abufptr[-1] != ' ') pp_wrch(ch); } static void pp_rd_args(PP_HASHENTRY *p, int32 uselinect) { int32 sav_abufptr = pp_abufptr - pp_abufbase; PP_ARGENTRY *a = pp_hasharglist_(p); /* macro with parameters */ int32 parcnt = 0, arglinect = 0; int32 abufarg; /* now offset into pp_abufbase */ int ch; int lastch = 0; pp_arg_align(); abufarg = pp_abufptr - pp_abufbase; for (ch = pp_rdch();;) /* read args */ { int thisch = ch; switch (ch) { case PP_EOM: /* e.g. i(f) where i(x)=x and f=i(. */ /* maybe the following line should pp_unrdch()? */ if (pp_scanidx > 0) pp_scanidx--; case PP_EOF: cc_err(pp_err_rpar_eof, pp_hashname_(p), (long)uselinect); while (parcnt-- > 0) pp_wrch(')'); goto endofargs; case '\n': ++arglinect; if (pp_in_directive && !(feature & FEATURE_PCC)) /* This helps to force a diagnostic in #if f(1,<nl>2) as required by */ /* the ANSI C standard. Constraint: #if ... occupies only one line. */ { pp_wrch(ch); break; } if (arglinect == PP_ARGLINES_WARN_VAL) cc_warn(pp_warn_many_arglines, arglinect); /* drop through - treat nl in arg as space */ case '\t': ch = ' '; /* drop through - treat tab in arg as space */ case ' ': /* Ignore leading or multiple spaces within an arg. */ /* (Only visible via ansi stringify (#) so PCC mode ok) */ ansitoksep: if (pp_abufptr != pp_abufbase+abufarg) pp_spacearg(ch); break; case '%': if (PP_EOLP(lastch)) { ch = pp_rdch(); if (ch == ':') cc_warn(pp_warn_directive_in_args); pp_wrch('%'); lastch = '%'; continue; } else { pp_wrch(ch); break; } case '#': if (PP_EOLP(lastch)) cc_warn(pp_warn_directive_in_args); /* drop through to default case */ default: /* NB: we do not need to use pp_number here. */ if (ch == PP_TOKSEP) { if (!(feature & FEATURE_PCC)) goto ansitoksep; /* else for PCC ignore PP_TOKSEP in args. Why? */ } else pp_wrch(ch); break; case '\'': case '"': (void)pp_copystring(ch); break; case '(': parcnt++; pp_wrch(ch); break; case ',': if (parcnt > 0) { pp_wrch(ch); break; } pp_trimarg(pp_abufbase+abufarg); pp_wrch(0); if (a != 0) pp_arg_link(a, abufarg), pp_arg_align(), abufarg = pp_abufptr - pp_abufbase, a = pp_argchain_(a); if (a == 0) { cc_err(pp_err_many_args, pp_hashname_(p), (long)uselinect); pp_abufptr = pp_abufbase + sav_abufptr; return; } break; case ')': if (parcnt-- > 0) { pp_wrch(ch); break; } endofargs: pp_trimarg(pp_abufbase+abufarg); if (a == 0 && pp_abufptr != pp_abufbase+abufarg) { /* no tokens allowed as arg in calls of #define f() ... */ cc_err(pp_err_many_args, pp_hashname_(p), (long)uselinect); pp_abufptr = pp_abufbase + sav_abufptr; } pp_wrch(0); if (a != 0) pp_arg_link(a, abufarg), a = pp_argchain_(a); if (a != 0) { cc_err(pp_err_few_args, pp_hashname_(p), (long)uselinect); while (a != 0) { /* default missing arguments to "" */ pp_arg_align(); abufarg = pp_abufptr - pp_abufbase; pp_wrch(0); pp_arg_link(a, abufarg); a = pp_argchain_(a); } } return; } if (thisch == '\n' || ch != ' ') lastch = thisch; ch = pp_rdch(); } } /* pp_checkid reads in a source id to see if it is a macro name, either outputting it unchanged or expanding it. BEWARE - reuse of abuf. It notionally expands into ebuf, but there is a special case for speed (and to inhibit infinitely repeatedly trying to expand) for identifiers when the output is to abuf for pp_process(). */ static bool pp_checkid(int pp_ch) { PP_HASHENTRY *p; int32 i = 0, hash = 0; int32 uselinect; int whitech; bool noexpandflag = 0; /* @@@ currently pp_checkid() removes all PP_NOEXPAND chars, and adds */ /* them again if we are argexpanding. Is this what we want? */ if (pp_ch == PP_NOEXPAND) noexpandflag = 1, pp_ch = pp_rdch(); /* @@@ do/while below optimistic/buggy! */ pp_abuf_ensure(PP_DEFLEN+1); do { if (i<PP_DEFLEN) { hash = HASH(hash, pp_ch); pp_abufptr[i++] = pp_ch; } do pp_ch = pp_rdch(); while (pp_ch == PP_NOEXPAND); } while pp_cidchar(pp_ch); pp_abufptr[i] = 0; #ifdef ENABLE_PP /* spurious: deadcode elimination fixes */ if (debugging(DEBUG_PP)) cc_msg("pp_checkid(%s%s)", pp_abufptr, noexpandflag ? "/noexpand":""), pp_showsleep(), cc_msg("\n"); #endif if (i == 1 && pp_widestrbeg(pp_abufptr[0], pp_ch) && !(feature & FEATURE_PCC)) noexpandflag = 1; p = noexpandflag ? NULL : pp_lookup(pp_abufptr, hash); if (p == NULL) { if (!(pp_inhashif && StrEq("defined",pp_abufptr))) { if (pp_scanidx < 0) /* The following line is notionally pp_wrbuf() but is so */ /* written for efficiency (main loop). */ pp_abufptr += i; /* leave chars in output buffer */ else { /* the following line looks a little odd, but currently */ /* we put a NOEXPAND quote around every id not expanded as */ /* part of a macro-arg so that IF it was suppressed then it */ /* will not get expanded for the body rescan of an outermore */ /* macro. See comment at top of file. */ pp_savch(PP_NOEXPAND); pp_savbuf(pp_abufptr, i); } pp_unrdch(pp_ch); } else /* poxy "defined id" or "defined(id)" in #if */ { bool parens = 0; pp_ch = pp_skipb1(pp_ch); if (pp_ch == '(') { parens = 1; pp_ch = pp_skipb0(); } if (!pp_macstart(pp_ch)) cc_err(pp_err_if_defined); else { i = 0, hash = 0; pp_abuf_ensure(PP_DEFLEN+1); do { if (i<PP_DEFLEN) hash = HASH(hash, pp_ch), pp_abufptr[i++] = pp_ch; pp_ch = pp_rdch(); } while pp_cidchar(pp_ch); pp_abufptr[i] = 0; p = pp_lookup(pp_abufptr, hash); if (parens) { pp_ch = pp_skipb1(pp_ch); if (pp_ch == ')'); /* nothing to do */ else cc_err(pp_err_if_defined1); } else pp_unrdch(pp_ch); } pp_expand(p != 0 ? pp_hashone : pp_hashzero, 0); } return 0; } if (pp_hashnoargs_(p)) /* macro with no parameters */ { pp_unrdch(pp_ch); pp_expand(p,0); return 1; } uselinect = pp_fl->l; /* AM, Jun 90: ensure ensure whitech sufficiently accurate so that */ /* calls to unrdch() work when pp_argexpanding. */ whitech = 0; if (pp_white(pp_ch)) whitech = pp_ch, pp_ch = pp_skipb0(); /* We have to be rather careful here with fn-like macros with no */ /* following parens, especially since they may be followed by a #-line. */ /* The draft isn't especially clear, but since '(' is required to be */ /* the next pp-token if it is present the draft seems unambiguous. */ /* Consider examples like "f(getchar <nl>#whatever <nl> )". */ /* Note the related "f(getchar( <nl>#whatever <nl> ))" is undefined. */ if (!pp_in_directive) while (pp_ch == '\n') whitech = '\n', pp_ch = pp_skipb0(); if (pp_ch != '(') /* ANSI says ignore if no '(' present */ { if (debugging(DEBUG_PP)) cc_msg("pp_checkid(%s%c/%.2x not '(')\n", pp_abufptr, pp_ch, pp_ch); if (pp_scanidx < 0) pp_abufptr += i; /* leave chars in output buffer */ else pp_savbuf(pp_abufptr, i); pp_unrdch(pp_ch); /* hence PP_UNRDCHMAX>=2 */ if (whitech) pp_unrdch(whitech); /* don't lose poss. whitespace */ return 0; } else { /* @@@ later improve store efficiency by save/restore of pp_abufptr */ pp_rd_args(p, uselinect); pp_expand(p, pp_fl->l-uselinect); return 1; } } static PP_ARGENTRY *pp_addtoarglist(char *id, PP_ARGENTRY *a); static PP_HASHENTRY *pp_predefine2(char const *s, int n) { PP_HASHENTRY *p; int32 i = 0, hash = 0; int ch; while (ch = *s++, n<0 ? ch!=0 : pp_cidchar(ch)) { if (i<PP_DEFLEN) { hash = HASH(hash, ch); pp_stuffid_(ch); } } { char *name = pp_closeid(); if (ch != '(') p = (PP_HASHENTRY *) pp_new_(PP_NOARGHASHENTRY), pp_hashnoargs_(p) = 1; else { char const *sarg = s; int32 params = 0; p = (PP_HASHENTRY *) pp_new_(sizeof(PP_HASHENTRY)); pp_hashnoargs_(p) = 0; pp_hasharglist_(p) = 0; do { ch = *sarg++;; if (!pp_macstart(ch)) { if (ch == ')' && params == 0) break; goto illopt; } do { pp_stuffid_(ch); ch = *sarg++; } while (pp_cidchar(ch)); pp_hasharglist_(p) = pp_addtoarglist(pp_closeid(), pp_hasharglist_(p)); params++; } while (ch == ','); if (ch != ')') goto illopt; s = sarg; ch = *s++; } illopt: pp_hashname_(p) = name; } pp_hashuses_(p) = 0; pp_hashalive_(p) = 1; pp_hashismagic_(p) = n < 0; /* @@@ LDS - because of #define __STDC__ 0 chaos, it may be useful to set */ /* pp_noifdef_(p) to 1 for some pre-defines. Should depend on -f?. */ pp_noifdef_(p) = 0; if (n < 0) pp_hashmagic_(p) = n; else pp_hashbody_(p) = "1"; pp_hashdefchain_(p) = 0; pp_unchain_(p) = 0, pp_sleepleft_(p) = 0; /* (init only to check) */ switch (ch) { default: if (n >= 0) cc_rerr(pp_rerr_illegal_option, pp_hashname_(p), s-1); /* drop through */ case 0: break; case '=': pp_hashbody_(p) = s; break; } pp_hashchain_(p) = (*pp_hashtable)[hash % PP_HASHSIZE]; (*pp_hashtable)[hash % PP_HASHSIZE] = p; if (pp_hashfirst == 0) pp_hashfirst = pp_hashlast = p; else pp_hashdefchain_(pp_hashlast) = p, pp_hashlast = p; if (usrdbg(DBG_PP) && !pp_hashismagic_(p)) { if (pp_hashnoargs_(p)) dbg_define(pp_hashname_(p), YES, pp_hashbody_(p), NULL, curlex.fl); else dbg_define(pp_hashname_(p), NO, pp_hashbody_(p), (dbg_ArgList *)pp_hasharglist_(p), curlex.fl); } return p; } static PP_ARGENTRY *pp_addtoarglist(char *id, PP_ARGENTRY *a) { PP_ARGENTRY *p, *q; bool seen = 0; for ((p = a, q = 0); p != 0; (q = p, p = pp_argchain_(p))) if (StrEq(pp_argname_(p),id) && !seen) seen = 1, cc_rerr(pp_rerr_nonunique_formal, id); p = (PP_ARGENTRY *)pp_new_(sizeof(PP_ARGENTRY)); pp_argchain_(p) = 0; pp_argname_(p) = id; pp_argactual_(p) = DUFF_OFFSET; return q==0 ? p : (pp_argchain_(q) = p, a); } static bool pp_eqarglist(PP_ARGENTRY *p, PP_ARGENTRY *q) { for (; p && q; p = pp_argchain_(p), q = pp_argchain_(q)) if (!StrEq(pp_argname_(p), pp_argname_(q))) return 0; return (p == q); } static PP_ARGENTRY *pp_findarg(PP_ARGENTRY *a, char const *id, int32 n) { for (; a; a = pp_argchain_(a)) if (pp_eqname(pp_argname_(a), id, n)) return a; return 0; } /* @@@ re-order next routine */ static void pp_skip_linetokens(int pp_ch) { for (;;) switch (pp_ch) { case '\n': case PP_EOF: pp_unrdch(pp_ch); return; case '\'': case '"': pp_stuffstring(pp_ch,0,1); /* drop through */ default: pp_ch = pp_rdch(); break; } } /* * One routine per pre-processor command... */ static void pp_define(int pp_ch, bool noifdef) { int32 i = 0, hash = 0; FileLine saved_fl; if (usrdbg(DBG_PP)) { saved_fl = *pp_fl; saved_fl.p = dbg_notefileline(saved_fl); } if (!pp_macstart(pp_ch)) { cc_err(pp_err_missing_identifier); pp_skip_linetokens(pp_ch); return; } if (pp_skipping) { /* This code is untidy, but corresponds to the ANSI rationale */ /* that PP only needs to check for the name of a directive. */ /* However, improve on this behaviour one day!!! */ pp_skip_linetokens(pp_ch); return; } do { if (i<PP_DEFLEN) { hash = HASH(hash, pp_ch); pp_stuffid_(pp_ch); i++; } pp_ch = pp_rdch(); } while (pp_cidchar(pp_ch)); { char *name = pp_closeid(); PP_HASHENTRY *p; PP_ARGENTRY *arglist = 0; enum { FIRST_TOKEN, NORMAL, SEEN_HASH, SEEN_HASHHASH } state = FIRST_TOKEN; int32 feature_comment = feature & FEATURE_PPCOMMENT; feature &= ~FEATURE_PPCOMMENT; if (pp_ch != '(') p = (PP_HASHENTRY *) pp_new_(PP_NOARGHASHENTRY), pp_hashnoargs_(p) = 1; else { int32 params = 0; p = (PP_HASHENTRY *) pp_new_(sizeof(PP_HASHENTRY)); pp_hashnoargs_(p) = 0; pp_hasharglist_(p) = 0; do { pp_ch = pp_skipb0(); if (!pp_macstart(pp_ch)) { if (pp_ch == ')' && params == 0) break; cc_err(pp_err_missing_parameter, name); pp_skip_linetokens(pp_ch); feature |= feature_comment; return; } do { pp_stuffid_(pp_ch); pp_ch = pp_rdch(); } while (pp_cidchar(pp_ch)); pp_hasharglist_(p) = arglist = pp_addtoarglist(pp_closeid(), pp_hasharglist_(p)); params++; pp_ch = pp_skipb1(pp_ch); } while (pp_ch == ','); if (pp_ch != ')') { cc_err(pp_err_missing_comma, name); pp_skip_linetokens(pp_ch); feature |= feature_comment; return; } pp_ch = pp_rdch(); } pp_noifdef_(p) = noifdef; pp_hashalive_(p) = 1; pp_hashismagic_(p) = 0; pp_hashuses_(p) = 0; pp_hashdefchain_(p) = 0; pp_unchain_(p) = 0, pp_sleepleft_(p) = 0; /* (init only to check) */ pp_hashname_(p) = name; pp_ch = pp_skipb1(pp_ch); for (;;) { /* Turn multiple spaces (or tabs) to one space, lose trailing spaces. */ /* Initial spaces have already been removed and comments are now space. */ /* Beware warnings for differing white space in pcc-mode (like Reiser?) */ if ((pp_ch == ' ' || pp_ch == '\t') && !(feature & FEATURE_PCC)) { pp_ch = pp_skipb1(pp_ch); if (!(pp_ch == '\n' || pp_ch == PP_EOF)) pp_stuffid_(' '); } if (state == SEEN_HASH && !pp_macstart(pp_ch)) state = NORMAL, cc_rerr(pp_rerr_define_hash_arg); switch (pp_ch) { default: if (pp_macstart(pp_ch)) { int32 n = 0; do n++, pp_stuffid_(pp_ch), pp_ch = pp_rdch(); while (pp_cidchar(pp_ch)); if (state == SEEN_HASH && !pp_findarg(arglist, pp_dbufptr-n, n)) cc_rerr(pp_rerr_define_hash_arg); state = NORMAL; continue; } defolt: pp_stuffid_(pp_ch); break; case '\'': case '"': pp_stuffstring(pp_ch,0,0); break; case '%': if (feature & FEATURE_PCC) goto defolt; pp_ch = pp_rdch(); pp_stuffid_('%'); if (pp_ch != ':') { state = NORMAL; continue; } pp_stuffid_(':'); pp_ch = pp_rdch(); if (pp_ch != '%') state = pp_hashnoargs_(p) ? NORMAL : SEEN_HASH; else { pp_ch = pp_rdch(); pp_stuffid_('%'); if (pp_ch != ':') { cc_rerr(pp_rerr_define_hash_arg); state = NORMAL; } else { if (state == FIRST_TOKEN) cc_rerr(pp_rerr_define_hashhash); pp_stuffid_(':'); pp_ch = pp_rdch(); state = SEEN_HASHHASH; } } continue; case '#': if (feature & FEATURE_PCC) goto defolt; pp_ch = pp_rdch(); pp_stuffid_('#'); if (pp_ch != '#') state = pp_hashnoargs_(p) ? NORMAL : SEEN_HASH; else { if (state == FIRST_TOKEN) cc_rerr(pp_rerr_define_hashhash); pp_stuffid_('#'); pp_ch = pp_rdch(); state = SEEN_HASHHASH; } continue; case '\n': case PP_EOF: if (state == SEEN_HASHHASH) cc_rerr(pp_rerr_define_hashhash); pp_hashbody_(p) = pp_closeid(); { PP_HASHENTRY *q = pp_lookup(pp_hashname_(p), hash); if (q) { if (usrdbg(DBG_PP)) dbg_undef(pp_hashname_(q), saved_fl); pp_hashalive_(q) = 0; /* omit for a #define def. stack */ if (pp_hashismagic_(q) /* union => must be first test */ || !StrEq(pp_hashbody_(p), pp_hashbody_(q)) || pp_hashnoargs_(p) != pp_hashnoargs_(q) || (!pp_hashnoargs_(p) && !pp_eqarglist(pp_hasharglist_(p),pp_hasharglist_(q)))) { if (suppress & D_MPWCOMPATIBLE) cc_warn(pp_rerr_redefinition, pp_hashname_(p)); else cc_pccwarn(pp_rerr_redefinition, pp_hashname_(p)); } else if (feature & (FEATURE_FUSSY|FEATURE_PREDECLARE)) cc_warn(pp_warn_redefinition, pp_hashname_(p)); } } if (usrdbg(DBG_PP)) { if (pp_hashnoargs_(p)) dbg_define(pp_hashname_(p), YES, pp_hashbody_(p), NULL, saved_fl); else dbg_define(pp_hashname_(p), NO, pp_hashbody_(p), (dbg_ArgList *)pp_hasharglist_(p), saved_fl); } pp_hashchain_(p) = (*pp_hashtable)[hash % PP_HASHSIZE]; (*pp_hashtable)[hash % PP_HASHSIZE] = p; if (pp_hashfirst == 0) pp_hashfirst = pp_hashlast = p; else pp_hashdefchain_(pp_hashlast) = p, pp_hashlast = p; pp_unrdch(pp_ch); feature |= feature_comment; return; /* gasp */ } state = NORMAL; pp_ch = pp_rdch(); } } } static void pp_undef(int pp_ch) { int32 i = 0, hash = 0; if (!pp_macstart(pp_ch)) { cc_err(pp_err_undef); pp_skip_linetokens(pp_ch); return; } /* Assumption on ABUFSIZE implies pp_abuf_ensure(PP_DEFLEN+1) OK. */ do { if (i<PP_DEFLEN) { hash = HASH(hash, pp_ch); pp_abufbase[i++] = pp_ch; } pp_ch = pp_rdch(); } while (pp_cidchar(pp_ch)); pp_unrdch(pp_ch); pp_abufbase[i++] = 0; if (!pp_skipping) { PP_HASHENTRY *p = pp_lookup(pp_abufbase, hash); if (p) { pp_hashalive_(p) = 0; if (usrdbg(DBG_PP)) { (void)dbg_notefileline(*pp_fl); dbg_undef(pp_hashname_(p), *pp_fl); } } } } static void pp_addconditional(bool skipelsepart) { PP_IFSTACK *q = pp_freeifstack; if (q) pp_freeifstack = pp_ifchain_(q); else q = (PP_IFSTACK *) pp_new_(sizeof(PP_IFSTACK)); pp_ifchain_(q) = pp_ifstack; pp_ifseenelse_(q) = 0; pp_ifoldskip_(q) = pp_skipping; /* caller pp_skipping */ pp_ifskipelse_(q) = pp_skipping || skipelsepart; /* 'else' part */ pp_ifstack = q; pp_skipping = pp_skipping || !skipelsepart; /* 'then' part */ } static char *static_copy(const char *s) { return strcpy((char *)pp_alloc(strlen(s)+1L), s); } static void pp_h_ifdef(int pp_ch, bool skipelsepart) { PP_HASHENTRY *p; int32 i = 0, hash = 0; if (pp_macstart(pp_ch)) { /* Assumption on ABUFSIZE implies pp_abuf_ensure(PP_DEFLEN+1) OK. */ do { if (i<PP_DEFLEN) { hash = HASH(hash, pp_ch); pp_abufbase[i++] = pp_ch; } pp_ch = pp_rdch(); } while (pp_cidchar(pp_ch)); pp_unrdch(pp_ch); pp_abufbase[i++] = 0; p = pp_lookup(pp_abufbase, hash); if (!skipelsepart && /* #ifndef ... */ !seen_pp_token && /* no tokens before #ifndef */ pp_filestack != 0 && /* an included file... */ pp_filestack->ifdefname == 0) /* ifdefname not yet set */ { pp_filestack->ifdefname = static_copy(pp_abufbase); pp_filestack->guard_ifndef = pp_ifstack; seen_pp_token = 1; } #ifdef MACH_EXTNS if (p != 0 && pp_noifdef_(p)) cc_warn(pp_warn_ifvaldef, pp_abufbase); #endif } else { p = NULL; if (feature & FEATURE_PCC) cc_warn(pp_err_ifdef); /* @@@ is this really suppressible? */ else cc_err(pp_err_ifdef); pp_skip_linetokens(pp_ch); } if (p != 0 && !pp_skipping) pp_hashuses_(p)++; pp_addconditional((p != 0) == skipelsepart); } static void pp_h_if(int pp_ch) { bool b = YES; /* YES/NO is arbitrary */ if (pp_skipping) pp_skip_linetokens(pp_ch); else { pp_unrdch(pp_ch); pp_inhashif = YES; b = syn_hashif(); pp_inhashif = NO; } pp_addconditional(b); /* Assert: after syn_hashif(), at end of line or at end of file */ } static void pp_h_else(int pp_ch) { if (pp_ifstack == 0 || pp_ifseenelse_(pp_ifstack)) cc_rerr(pp_rerr_spurious_else); else { pp_skipping = pp_ifskipelse_(pp_ifstack); pp_ifseenelse_(pp_ifstack) = 1;} pp_unrdch(pp_ch); } static void pp_h_elif(int pp_ch) { if (pp_ifstack == 0 || pp_ifseenelse_(pp_ifstack)) { cc_rerr(pp_rerr_spurious_elif); pp_skip_linetokens(pp_ch); } else if (pp_ifskipelse_(pp_ifstack)) { pp_skipping = YES; pp_skip_linetokens(pp_ch); } else { bool b; pp_unrdch(pp_ch); pp_skipping = NO; pp_inhashif = YES; b = syn_hashif(); pp_inhashif = NO; if (b) pp_ifskipelse_(pp_ifstack) = YES; else pp_skipping = YES; /* Assert: after syn_hashif(), at end of line or at end of file */ } } static void pp_h_endif(int pp_ch) { if (pp_ifstack == 0) cc_rerr(pp_rerr_spurious_endif); else { pp_skipping = pp_ifoldskip_(pp_ifstack); { PP_IFSTACK *q = pp_ifchain_(pp_ifstack); /* discard old */ pp_ifchain_(pp_ifstack) = pp_freeifstack, pp_freeifstack = pp_ifstack; pp_ifstack = q; if (pp_filestack != NULL && q == pp_filestack->guard_ifndef) { seen_pp_token = 0; /* reset after matching #endif */ pp_filestack->guard_ifndef = (PP_IFSTACK *)DUFF_ADDR; } /* inspect (pp_process) at EOF */ } } pp_unrdch(pp_ch); } static int pp_directive_expand(int ch) { pp_abufptr = pp_abufbase; while (pp_macstart(ch)) { pp_checkid(ch); if (pp_abufptr != pp_abufbase) { /* This means an identifier did not expand (see pp_checkid) */ /* undo the special treatment in pp_checkid(). */ pp_abufptr = pp_abufbase; return PP_NOEXPAND; /* sufficient for giving error. */ } ch = pp_skipb0(); } return ch; } static void pp_h_line(int pp_ch) { if (pp_skipping) { pp_skip_linetokens(pp_ch); return; } pp_ch = pp_directive_expand(pp_ch); if (isdigit(pp_ch)) { int n = 0; while (isdigit(pp_ch)) n = n*10 + pp_ch-'0', pp_ch = pp_rdch(); pp_ch = pp_skipb1(pp_ch); pp_ch = pp_directive_expand(pp_ch); if (pp_ch == '"') { pp_stuffstring('"',1,pp_skipping); pp_fl->f = pp_closeid(); /* ensure done always */ pp_ch = pp_directive_expand(pp_skipb0()); } /* Oh dear... this conditional is the price we pay to centralise the */ /* diagnosis of trailing junk in pp_directive(). Really, that should */ /* be pulled out of pp_directive and called from each pp_h_thing(). */ /* See also the "Oh woe" comment at the end of pp_directive(). */ pp_fl->l = (pp_ch == '\n') ? n : n-1; pp_unrdch(pp_ch); } else { cc_rerr(pp_rerr_hash_line); pp_skip_linetokens(pp_ch); } } /* Code in flux -- move typedef to top or merge with pp_filestack? */ typedef struct file_name_list { struct file_name_list *cdr; char const *ifdefname; bool stringfile; char fname[1]; } file_name_list; static file_name_list *seen_before = NULL; static int fnameEQ(char const *s, char const *t) { int chs, cht; for (;;) { chs = *s++; cht = *t++; #ifndef COMPILING_ON_UNIX /* host file names are case INsensitive... */ chs = safe_tolower(chs); cht = safe_tolower(cht); #endif if (chs != cht) return 0; if (chs == 0) return 1; } } static void include_only_once(char const *fname, char const *ifdefname, pp_uncompression_record *stringfile) { file_name_list *p; for (p = seen_before; p != NULL; p = p->cdr) if (p->stringfile == (stringfile != NULL) && fnameEQ(p->fname, fname)) return; p = (file_name_list *)pp_alloc((int32)offsetof(file_name_list, fname) + (int32)strlen(fname) + 1); p->cdr = seen_before; strcpy(p->fname, fname); p->ifdefname = ifdefname; p->stringfile = (stringfile != NULL); seen_before = p; if (debugging(DEBUG_FILES)) { if (ifdefname == NULL) cc_msg("include_only_once '%s'\n", fname); else cc_msg("file '%s' guarded by '#ifndef %s'\n", fname, ifdefname); } } void pp_push_include(char const *fname, int lquote, FileLine fl) { FILE *fp; int rquote = (lquote == '<' ? '>' : lquote); char const *hostname; if (lquote == '<' && !(feature & FEATURE_PCC || suppress & D_PPNOSYSINCLUDECHECK)) { static char const * const ansiheaders[] = { "assert.h", "ctype.h", "errno.h", "float.h", "iso646.h", "limits.h", "locale.h", "math.h", "setjmp.h", "signal.h", "stdarg.h", "stddef.h", "stdio.h", "stdlib.h", "string.h", "time.h" }; bool found = 0; unsigned i; for (i = 0; i < sizeof(ansiheaders)/sizeof(*ansiheaders); i++) if (StrEq(fname, ansiheaders[i])) { found = 1; break; } #ifndef TARGET_IS_ALPHA /* * When using some other vendor's header files it is common for * (eg) stdio.h to include some other <sys/xxx.h> files, and these * cause moans from here. What I really want, I think, is to have * this warning disabled if I am already inside some header file * that has been picked out of the standard place. Meanwhile I will * put an improper target specific test here to cause Alan or somebody * to do something better! ACN. */ if (!found) cc_warn(pp_warn_nonansi_header, fname); #endif } /* * Here a null name is checked for specially lest sticking bits of a * search path onto it lead #include "" into getting treated as (for * instance) #include "./", where one could imagine the current directory * being opened for reading and the (binary?) junk in it leading to * large numbers of odd error messages. If somebody thinks of a good idea * for a USEFUL meaning for #include "" or #include <> here is where it * could be hooked in. I probably vote against any such magic! */ { pp_uncompression_record *ur = NULL; if (fname[0] != 0 && (fp = pp_inclopen(fname, lquote=='<', &ur, &hostname, fl)) != NULL) { /* the following block is notionally a recursive call to pp_process() but that would mean a co-routine structure if used with the cc. */ PP_FILESTACK *fs; file_name_list *p; for (p = seen_before; p != NULL; p = p->cdr) { if (!fnameEQ(p->fname, hostname)) continue; if (p->ifdefname != 0) { PP_HASHENTRY *h = pp_lookup_name(p->ifdefname); if (h == NULL || !pp_hashalive_(h)) break; } else if (p->stringfile != (ur != NULL)) break; if (ur == NULL) trackfile_close(fp); if (debugging(DEBUG_FILES)) { if (p->ifdefname == 0) cc_msg("Not including '%s' again\n", hostname); else cc_msg("Not including '%s' again, guard '%s' is #defined\n", hostname, p->ifdefname); } pp_wrch('\n'); pp_inclclose(*pp_fl); return; } if (var_cc_private_flags & 0x1000000) include_only_once(hostname, NULL, active_string_file); fs = pp_freefilestack; if (fs != NULL) pp_freefilestack = pp_filchain_(fs); else fs = (PP_FILESTACK *) pp_new_(sizeof(PP_FILESTACK)); pp_filchain_(fs) = pp_filestack; pp_filestack = fs; pp_filstream_(fs) = pp_cis; pp_cis = fp; pp_fileline_(fs) = *pp_fl; pp_stringfile_(fs) = active_string_file; active_string_file = ur; init_pp_fl(hostname); fs->ifstart = pp_ifstack; fs->ifdefname = 0; fs->guard_ifndef = (PP_IFSTACK *)DUFF_ADDR; seen_pp_token = 0; #ifndef NO_LISTING_OUTPUT pp_filenumber_(fs) = pp_filenumber; /* NB profile_find() sets profile_ptr & pp_filenumber */ pp_propoint_(fs) = profile_ptr; profile_find(fname); /* Set MSB of pp_filenumber if listing is not wanted at this level */ if (!((lquote != '<' && (feature & FEATURE_USERINCLUDE_LISTING)) || (feature & FEATURE_SYSINCLUDE_LISTING))) { pp_filenumber |= 0x80000000; list_this_file = 0; } else list_this_file = 1; #endif /* NO_LISTING_OUTPUT */ } else cc_err(pp_err_include_file, (int)lquote,fname,(int)rquote); } } static void pp_include(int pp_ch) { /* AM: pp_include() now reads up to and including its terminating NL. */ int lquote, rquote; char *fname; FileLine saved_fl; if (!pp_skipping) { if (usrdbg(DBG_PP)) { saved_fl = *pp_fl; saved_fl.p = dbg_notefileline(saved_fl); } pp_ch = pp_directive_expand(pp_ch); } switch (lquote = pp_ch) { case '"': rquote = '"'; break; case '<': rquote = '>'; break; default: if (!pp_skipping) cc_err(pp_err_include_quote); pp_skip_linetokens(pp_ch); return; } pp_stuffstring(rquote,1,pp_skipping); fname = pp_closeid(); /* ensure done always */ pp_ch = pp_directive_expand(pp_skipb0()); if (!PP_EOLP(pp_ch) && pp_ch != PP_EOF) { if (!pp_skipping) cc_err(pp_err_include_junk, (int)lquote, fname, (int)rquote); pp_skip_linetokens(pp_ch); (void)pp_rdch(); } if (pp_skipping) pp_wrch('\n'); else pp_push_include(fname, lquote, saved_fl); } /* Pragmas: syntax allowed (we can argue more later) is: * "#pragma -<letter><optional digit> Argument_List -<letter><optional digit>". * The effect of "#pragma -<letter>" is to set pp_pragmavec[letter-a] to -1 * and "#pragma -<letter><digit>" to set pp_pragmavec[letter-a] to <digit>-0. * For the majority of these options a long-winded spelt out word can also * be given, as in * "#pragma no_warn_deprecated no_warn_implicit_fns" * where the particular words that are recognised and their expansions into * the more primitive -xn form are given in a table here. * (note: does anybody want to change these names? 21 March 89 is ACN's * first bash at such a list and is probably in need of further refinement) */ static PragmaSpelling const pragma_words[] = { #ifdef FORTRAN /* * The FORTRAN pragmas are treated a bit specially since they represent * bits in just two flag words - see where they are set somewhere below * for how #pragma auto and #pragma no_auto (say) set and clear the 0x100 * bit. */ {"double_complex", 'x', 0x1}, {"hinteger", 'x', 0x2}, {"case_fold", 'x', 0x4}, {"lc_keywords", 'x', 0x8}, {"lc_ids", 'x', 0x10}, {"free_format", 'x', 0x20}, {"imp_undef", 'x', 0x40}, {"recursion", 'x', 0x80}, {"auto", 'x', 0x100}, {"hollerith", 'x', 0x200}, {"top_express", 'x', 0x400}, {"f66", 'x', 0x800}, {"mixed_common", 'x', 0x1000}, {"vms_chars", 'x', 0x2000}, {"vms_casts", 'x', 0x4000}, {"vms_io", 'x', 0x8000}, {"vms_types", 'x', 0x10000}, {"static_locals", 'x', 0x100000}, {"all_hinteger", 'x', 0x200000}, {"all_double", 'x', 0x400000}, {"all_undefined", 'x', 0x800000}, {"check_subscripts", 'x', 0x1000000}, {"noargalias", 'x', 0x2000000}, {"long_lines", 'x', 0x4000000}, {"f66_onetrip", 'w', 1}, {"f66_iosublist", 'w', 2}, {"f66_intrinsgo", 'w', 4}, #endif { "warn_implicit_fn_decls", 'a', 1}, { "check_memory_accesses", 'c', 1}, { "warn_deprecated", 'd', 1}, { "continue_after_hash_error", 'e', 1}, { "include_only_once", 'i', 1}, /* @@@ freeze soon! */ { "once", 'i', 1}, /* common with other compilers */ { "optimise_crossjump", 'j', 1}, #ifdef TARGET_IS_ARM_OR_THUMB { "optimise_multiple_loads", 'm', 1}, #endif { "disable_tailcalls", 'n', 1}, /* ECN: for pSOS, generically useful? */ { "profile", 'p', 1}, { "profile_statements", 'p', 2}, #ifdef TARGET_IS_ARM_OR_THUMB { "check_stack", 's', 0}, #endif { "force_top_level", 't', 1}, /* @@@ freeze soon! */ { "pcrel_vtables", 'u', 1}, { "check_printf_formats", 'v', 1}, { "check_scanf_formats", 'v', 2}, { "__compiler_msg_format_check", 'v', 3}, /* not for public use */ { "side_effects", 'y', 0}, { "optimise_cse", 'z', 1} }; #define NPRAGMAS (sizeof(pragma_words)/sizeof(PragmaSpelling)) PragmaSpelling const *keyword_pragma(char const *name, bool *negp) { Uint p; if (name[0] == 'n' && name[1] == 'o') { name += 2; if (name[0] == '_') name++; *negp = YES; } else *negp = NO; /* For the small number of available options linear search seems OK */ for (p = 0; p < NPRAGMAS; p++) if (StrEq(pragma_words[p].name, name)) return &pragma_words[p]; return NULL; } /* In the medium term the following routine is moving to compiler.c */ /* Precondition: 'pragchar' is a lower case letter. */ static void main_pragma_set(int pragchar, int32 pragval) { #ifdef FORTRAN /* * For FORTRAN purposes I need to be able to set and clear bits in * a single word, at least via wordy pragmas. */ if (pragchar == 'x' || pragchar == 'w') { if (pragval == 0) pp_pragmavec[pragchar - 'a'] = -1; else if (pragval > 0) pp_pragmavec[pragchar - 'a'] |= pragval; else pp_pragmavec[pragchar - 'a'] &= pragval; } else #endif pp_pragmavec[pragchar - 'a'] = pragval; #ifdef INMOSC /* Support for obsolete Norcroft C error suppression pragmas: */ switch (pragchar) { case 'b': if (pragval) suppress &= ~D_IMPLICITCAST; else { if (!(suppress & D_IMPLICITCAST)) cc_warn(pp_warn_pragma_suppress); suppress |= D_IMPLICITCAST; } break; } #endif } static int pp_pragmardch(void) { int ch = pp_rdch(); if (minus_e) fputc(ch, stdout); return ch; } static void pp_pragma(int pp_ch) { /* note that ANSI say it is NOT an error to fail to parse a #pragma */ /* that does not stop us warning on syntax we fail to recognise */ if (pp_skipping) { pp_skip_linetokens(pp_ch); return; } if (minus_e) { fputs("#pragma ", stdout); fputc(pp_ch, stdout); } for (;;) { int pragchar; int32 pragval; while (pp_ch != PP_EOF && pp_white(pp_ch)) pp_ch = pp_pragmardch(); switch (pp_ch) { default: { char pragma_name[32]; unsigned p = 0; PragmaSpelling const *prag; bool negate; /* * Read a word starting with whatever non-blank character happens, but * following on through alphanumeric characters plus _ (plus maybe $). * Case fold the word that is read, and truncate it to 30 characters. */ do { if (p<30) pragma_name[p++] = safe_tolower(pp_ch); pp_ch = pp_pragmardch(); } while (pp_cidchar(pp_ch)); pragma_name[p] = 0; prag = keyword_pragma(pragma_name, &negate); if (prag != NULL) { pragval = prag->value; if (negate) { #ifdef FORTRAN if (pragchar == 'x' || pragchar == 'w') pragval = ~pragval; else #endif pragval = !pragval; } pragchar = prag->code; main_pragma_set(pragchar, pragval); continue; /* try for more pragmas on line */ } cc_warn(pp_warn_bad_pragma); break; } case '\n': break; case '-': { int32 n = 0; bool seen = 0; pp_ch = pp_pragmardch(); if (isalpha(pp_ch)) pragchar = safe_tolower(pp_ch); else { cc_warn(pp_warn_bad_pragma1, (int)pp_ch); break; } pp_ch = pp_pragmardch(); while (isdigit(pp_ch)) seen = 1, n = n*10 + (int)(pp_ch - '0'), pp_ch = pp_pragmardch(); pragval = seen ? n : -1; main_pragma_set(pragchar, pragval); continue; /* try for more pragmas on line */ } } pp_skip_linetokens(pp_ch); break; } /* * #pragma force_top_level * inserts the token ___toplevel into the input stream (and in the * process puts a constraint on UNRDCHMAX), which symbol is supposed * to tell the parser to moan if it is within any nested construction. * This is done this way since it seems nicer to publish that a #pragma * can be used to assert top-level-ness, but pp.c is not aware of * just where we are in a program, so must pass the checking on to syn.c. * The main intended use is to put #pragma force_top_level as the first * line of all standard header files so that * junk * #include <stdio.h> * can be handled better than was previously possible. * The insertion is now handled at the end of pp_directive to avoid line * number problems. */ /* * #pragma include_only_once * indicate that the current file should not be included again. The * name is taken as pp_fl->f (which does not have quote marks or <> * around it). Expected to be good for speed in some cases. * Note for those concerned with ANSI small print - the files names found * within "" and <> here are treated in an implementation defined manner * and that means that #pragma can change the interpretation - I deem * the include_only_once option to change the mapping to direct some * file names onto a notional empty file the second time around. */ if (var_include_once > 0) { include_only_once(pp_fl->f, NULL, active_string_file); if (pp_filestack) pp_filestack->ifdefname = (char *)DUFF_ADDR; var_include_once = 0; } } static void pp_h_error_ident(int pp_ch, bool iserror) { int32 n = 0; char msg[256]; while (pp_ch != '\n' && pp_ch != PP_EOF) { if (n < 255) msg[n++] = pp_ch == '\t' ? ' ' : pp_ch; pp_ch = pp_rdch(); } /* fill in terminator, and continue if last char was space */ do msg[n] = 0; while (--n >= 0 && msg[n] == ' '); /* the next line treats sysV #ident as a never moaning #error. */ if (iserror && !pp_skipping) { /* Groan: the ANSI rationale recommends that #error terminates */ /* compilation, but provides no way of fixup and continue. */ /* The following (hopefully) temporary fix provides #pragma -e */ /* to continue. */ if (pp_pragmavec['e'-'a'] > 0) cc_rerr(pp_rerr_hash_error, msg); else cc_fatalerr(pp_fatalerr_hash_error, msg); } pp_skip_linetokens(pp_ch); /* @@@ why? already at newline. */ } static void pp_h_error(int pp_ch) { pp_h_error_ident(pp_ch,1); } #ifdef EXTENSION_SYSV static void pp_h_ident(int pp_ch) { /* should we inhibit this when in a system include file? */ #ifdef NEVER if (!(feature & FEATURE_PCC)) cc_rerr(pp_rerr_hash_ident); #endif pp_h_error_ident(pp_ch,0); } #endif static void pp_directive(void) { int32 i=0; int pp_ch, cpp_allows_junk=0; char v[PP_DIRLEN+1]; bool old_seen = seen_pp_token; pp_in_directive = 1; seen_pp_token = 1; pp_ch = pp_skipb0(); for (i=0; isalpha(pp_ch); ) { if (i<PP_DIRLEN) v[i++] = pp_ch; pp_ch = pp_rdch(); } v[i] = 0; pp_ch = pp_skipb1(pp_ch); if (StrEq(v, "include")) { pp_include(pp_ch); pp_in_directive = 0; /* Note re cc -E only: it is arguable that we should set pp_rdch3nls=0 */ /* here so NL's in comments are not output after the "#line" from */ /* pp_inclopen(). But then it would be wrong if file didn't open. */ return; } else if (StrEq(v, "define")) pp_define(pp_ch, 0); #ifdef MACH_EXTNS else if (StrEq(v, "defineval")) pp_define(pp_ch, 1); #endif else if (StrEq(v, "undef")) pp_undef(pp_ch), cpp_allows_junk=1; else if (StrEq(v, "if")) { pp_h_if(pp_ch); /* Assert: after pp_h_if(), at end of line or at end of file */ pp_in_directive = 0; return; } else if (StrEq(v, "ifdef")) pp_h_ifdef(pp_ch, 1); else if (StrEq(v, "ifndef")) seen_pp_token = old_seen, pp_h_ifdef(pp_ch, 0); else if (StrEq(v, "else")) pp_h_else(pp_ch), cpp_allows_junk=1; else if (StrEq(v, "elif")) { pp_h_elif(pp_ch); /* Assert: after pp_h_elif(), at end of line or at end of file */ pp_in_directive = 0; return; } else if (StrEq(v, "endif")) pp_h_endif(pp_ch), cpp_allows_junk=1; else if (StrEq(v, "line")) pp_h_line(pp_ch); else if (StrEq(v, "pragma")) pp_pragma(pp_ch); else if (StrEq(v, "error")) pp_h_error(pp_ch); #ifdef EXTENSION_SYSV else if (StrEq(v, "ident")) pp_h_ident(pp_ch); /* non-ansi */ #endif else if (StrEq(v, "")) { /* If chars left assume a #line (but only in pcc mode). */ /* Oughtn't we to discourage #<number> in f77? PCC mode? */ if (!PP_EOLP(pp_ch) #ifndef FORTRAN && (feature & FEATURE_PCC) #endif ) pp_h_line(pp_ch); else pp_unrdch(pp_ch); } else { /* AM: @@@ ANSI ambiguity. Is #if 0; #wombat; #endif ok? */ if (!pp_skipping) cc_err(pp_err_unknown_directive, v); else if (feature & FEATURE_PREDECLARE) /* tick off the user anyway if (s)he asked for it! */ cc_warn(pp_err_unknown_directive, v); pp_skip_linetokens(pp_ch); } pp_ch = pp_skipb0(); if (!PP_EOLP(pp_ch) && pp_ch != PP_EOF) { if (!(cpp_allows_junk && (feature & (FEATURE_PCC | FEATURE_LIMITED_PCC) || suppress & D_PPALLOWJUNK))) cc_rerr(pp_rerr_junk_eol, v); pp_skip_linetokens(pp_ch); } else pp_unrdch(pp_ch); pp_in_directive = 0; /* It is woeful we need to do this here instead of in pp_pragma() */ /* but it needs to be done after the above checks. The earlier */ /* alterative involved fiddling with pp_fl->l, and was broken. */ if (var_force_top_level > 0 #ifdef FOR_ACORN && !cplusplus_preprocessing() #endif ) { pp_wrbuf("___toplevel", 11L); var_force_top_level = 0; } } #ifdef FORTRAN /* * F77 INCLUDEs require *currently* sticky EOFs, or statement assembly * becomes screwed up. * The sticky condition is cleared (for one read) by pp_pop_include(). */ static int pp_stick_at_eof; void pp_pop_include(void) { pp_stick_at_eof = 0; } #endif /* pp_process() behaves like _filbuf in stdio. Analogously it could collect larger bits of text before returning. But beware the interaction via recursive calls via #if. */ /* pp_lastch really keeps a record of a preceding newline (or file start) */ /* for #<directive>. Note that it is not updated on <space> or <tab>. */ static int pp_lastch; /* perhaps could be done via unrdch(). */ static int pp_process(void) { int pp_ch; pp_abufptr = pp_abufbase; while (pp_abufptr == pp_abufbase) /* do {} while really. */ { pp_ch = pp_rdch(); switch (pp_ch) { case PP_EOF: if (pp_filestack != 0 && pp_filestack->ifdefname != DUFF_ADDR) { if (!seen_pp_token && pp_filestack->ifdefname != 0) { PP_HASHENTRY* h = pp_lookup_name(pp_filestack->ifdefname); include_only_once(pp_fl->f, pp_filestack->ifdefname, active_string_file); if (h == NULL || !pp_hashalive_(h)) cc_warn(pp_warn_guard_not_defined, pp_filestack->ifdefname); } else if (!(suppress & D_GUARDEDINCLUDE) && !fnameEQ(pp_fl->f, "assert.h")) cc_warn(pp_warn_not_guarded); } if (active_string_file == NULL && pp_cis != NULL) trackfile_close(pp_cis); /* see pp_include() */ /* @@@ ANSI do not specify whether #if's must match in a #include file. */ /* hence only check all #if's closed on real EOF. */ if (pp_filestack == 0) { if (pp_ifstack != 0) cc_err(pp_err_endif_eof); return PP_EOF; } else if (pp_filestack->ifstart != pp_ifstack) cc_warn(pp_warn_unbalanced); #ifdef FORTRAN if (pp_stick_at_eof) return PP_EOF; pp_stick_at_eof = 1; #endif pp_cis = pp_filstream_(pp_filestack); *pp_fl = pp_fileline_(pp_filestack); #ifndef NO_LISTING_OUTPUT profile_ptr = pp_propoint_(pp_filestack); pp_filenumber = pp_filenumber_(pp_filestack); list_this_file = !(pp_filenumber & 0x80000000); active_string_file = pp_stringfile_(pp_filestack); #endif /* NO_LISTING_OUTPUT */ { PP_FILESTACK *q = pp_filchain_(pp_filestack); /* discard old */ pp_filchain_(pp_filestack) = pp_freefilestack, pp_freefilestack = pp_filestack; pp_filestack = q; } /* there is an #include in the file we've just popped to */ seen_pp_token = 1; pp_rdptr = NULL; pp_rdcnt = 0; pp_ch = '\n'; /* to set pp_lastch later... */ /* The next line resets the (BSD-style) -I list in compiler.c */ pp_inclclose(*pp_fl); break; case '#': if (PP_EOLP(pp_lastch)) { pp_directive(); pp_ch = '\n'; } else if (!pp_skipping) pp_wrch(pp_ch); break; case ' ': case '\t':if (!pp_skipping) pp_wrch(pp_ch); #ifndef PASCAL_OR_FORTRAN if (!(feature & FEATURE_PCC)) #endif /* spaces may precede '#' only in ANSI C */ pp_ch = pp_lastch; break; case '\n':pp_wrch(pp_ch); break; /* output nl even if skipping */ #ifndef FORTRAN case '\'': case '"': pp_ch = pp_copystring(pp_ch); break; /* The following line is not needed to make pp_number work. */ /* case '.': if (!pp_skipping) pp_wrch(pp_ch); break; */ #endif case '%': if (PP_EOLP(pp_lastch)) { int nextch = pp_rdch(); if (nextch == ':') { pp_directive(); pp_ch = '\n'; break; } else { if (!pp_skipping) pp_wrch('%'); pp_unrdch(nextch); break; } } /* otherwise, fall through */ default: if (!pp_skipping) { #ifndef FORTRAN if (pp_macstart(pp_ch) || pp_ch == PP_NOEXPAND) pp_checkid(pp_ch); else if(isdigit( (unsigned char)pp_ch )) pp_number(pp_ch); else #endif if (pp_ch == PP_TOKSEP) { if (!(feature & FEATURE_PCC)) pp_wrch(' '); /* else lose it in PCC mode. */ } else pp_wrch(pp_ch); } } pp_lastch = pp_ch; if (!isspace(pp_ch)) seen_pp_token = 1; /* significant token */ } pp_abufoptr = pp_abufbase; return *pp_abufoptr++; } #ifndef NO_LISTING_OUTPUT static int pp_listchar(int ch) { /* AM: merge this code with other FEATURE_UNEXPANDED... code above? */ if (!(pp_filenumber & 0x80000000) && !(feature & FEATURE_UNEXPANDED_LISTING)) { if (ch != PP_EOF) { putc(ch, listingstream); if (ch == '\n') { listing_diagnostics(); if (profile_count) listing_nextline(pp_fl->l); fprintf(listingstream, "%6u ", pp_fl->l + 1); } } else putc('\n', listingstream); } return ch; } #endif /* * Exported things ... */ int pp_nextchar(void) { int ch; /* pp_process() cannot do the PP_NOEXPAND/PP_ESC removal, because */ /* these are embedded within pp tokens, not just between them. */ do { ch = ((pp_abufoptr < pp_abufptr) ? *pp_abufoptr++ : pp_process()); } while (ch == PP_NOEXPAND); if (ch == PP_ESC) { ch = ((pp_abufoptr < pp_abufptr) ? *pp_abufoptr++ : pp_process()); if (ch == ' ') ch = PP_TOKSEP; else if (ch == '\t') ch = PP_NOEXPAND; } #ifndef NO_LISTING_OUTPUT /* AM presumes that pp_listchar is an identity fn to help regalloc */ /* compile this routine into fast code? Hmm. */ if (listingstream) return pp_listchar(ch); #endif /* NO_LISTING_OUTPUT */ return ch; } void pp_predefine(char *s) { (void)pp_predefine2(s, 1); } void pp_preundefine(char *s) { int32 i = 0, hash = 0; /* Assumption on ABUFSIZE implies pp_abuf_ensure(PP_DEFLEN+1) OK. */ for (;;) { int ch = *s++; if (!pp_cidchar(ch)) break; if (i < PP_DEFLEN) hash = HASH(hash, ch), pp_abufbase[i++] = ch; } pp_abufbase[i] = 0; if (!pp_skipping) /* @@@ duh? */ { PP_HASHENTRY *p = pp_lookup(pp_abufbase, hash); if (p) { pp_hashalive_(p) = 0; if (usrdbg(DBG_PP)) dbg_undef(pp_hashname_(p), curlex.fl); } } } #ifndef NO_DUMP_STATE void PP_LoadState(FILE *f) { for (;;) { file_name_list *p; uint16 fnamelen, ifdeflen; uint8 stringfile; fread(&fnamelen, sizeof(uint16), 1, f); if (fnamelen == 0) break; fread(&ifdeflen, sizeof(uint16), 1, f); p = (file_name_list *)pp_alloc((int32)sizeof(file_name_list)+fnamelen+ifdeflen+1); fread(&stringfile, sizeof(uint8), 1, f); p->stringfile = stringfile; Dump_LoadString(p->fname, fnamelen, f); if (ifdeflen == 0) p->ifdefname = NULL; else { char *ifdefname = &p->fname[fnamelen+1]; p->ifdefname = ifdefname; Dump_LoadString(ifdefname, ifdeflen, f); } cdr_(p) = seen_before; seen_before = p; } pp_hashfirst = pp_hashlast = NULL; for (;;) { uint16 nlen; int32 bodylen; PP_HASHENTRY *h; uint32 hash = 0; unsigned i; char *name; fread(&nlen, sizeof(uint16), 1, f); if (nlen == 0) break; fread(&bodylen, sizeof(int32), 1, f); { PP_HASHBITS u; uint32 size; fread(&u.w, sizeof(uint32), 1, f); size = u.b.noargs ? PP_NOARGHASHENTRY : sizeof(PP_HASHENTRY); h = (PP_HASHENTRY *)pp_alloc(u.b.ismagic ? size+nlen+1 : size+nlen+bodylen+2); pp_hashname_(h) = name = (char *)h + size; pp_unchain_(h) = NULL; pp_sleepleft_(h) = 0; pp_hashdefchain_(h) = NULL; h->u.w = u.w; if (pp_hashlast == NULL) pp_hashfirst = h; else pp_hashdefchain_(pp_hashlast) = h; pp_hashlast = h; Dump_LoadString(name, nlen, f); if (!pp_hashismagic_(h)) { char *hashbody = &name[nlen+1]; pp_hashbody_(h) = hashbody; Dump_LoadString(hashbody, (size_t)bodylen, f); } else pp_hashmagic_(h) = bodylen; } for (i = 0; i < nlen; i++) hash = HASH(hash, name[i]); if (!pp_hashnoargs_(h)) { PP_ARGENTRY *a, **ap = &pp_hasharglist_(h); pp_hasharglist_(h) = NULL; for (;; ap = &pp_argchain_(a)) { fread(&nlen, sizeof(uint16), 1, f); if (nlen == 0) break; a = (PP_ARGENTRY *)pp_alloc((int32)sizeof(PP_ARGENTRY)+nlen+1); pp_argname_(a) = (char *)(a+1); pp_argchain_(a) = NULL; pp_argactual_(a) = DUFF_OFFSET; *ap = a; Dump_LoadString(pp_argname_(a), nlen, f); } } { PP_HASHENTRY *q = pp_lookup(name, hash); if (q) pp_hashalive_(q) = 0; pp_hashchain_(h) = (*pp_hashtable)[hash % PP_HASHSIZE]; (*pp_hashtable)[hash % PP_HASHSIZE] = h; } } } void PP_DumpState(FILE *f) { { file_name_list *p; uint16 fnamelen; for (p = seen_before; p != NULL; p = cdr_(p)) { uint16 ifdeflen = 0; uint8 stringfile = (uint8)p->stringfile; fnamelen = (uint16)strlen(p->fname); if (p->ifdefname != NULL) ifdeflen = (uint16)strlen(p->ifdefname); fwrite(&fnamelen, sizeof(uint16), 1, f); fwrite(&ifdeflen, sizeof(uint16), 1, f); fwrite(&stringfile, sizeof(uint8), 1, f); fwrite(p->fname, 1, fnamelen, f); if (ifdeflen > 0) fwrite(p->ifdefname, 1, ifdeflen, f); } fnamelen = 0; fwrite(&fnamelen, sizeof(uint16), 1, f); } { PP_HASHENTRY *h = pp_hashfirst; uint16 nlen; for (; h != NULL; h = h->defchain) { int32 bodylen = pp_hashismagic_(h) ? pp_hashmagic_(h) : strlen(pp_hashbody_(h)); nlen = (uint16)strlen(pp_hashname_(h)); fwrite(&nlen, sizeof(uint16), 1, f); fwrite(&bodylen, sizeof(int32), 1, f); fwrite(&h->u.w, sizeof(uint32), 1, f); fwrite(pp_hashname_(h), 1, nlen, f); if (!pp_hashismagic_(h)) fwrite(pp_hashbody_(h), 1, (size_t)bodylen, f); if (!pp_hashnoargs_(h)) { PP_ARGENTRY *a = pp_hasharglist_(h); for (; a != NULL; a = pp_argchain_(a)) { nlen = strlen(pp_argname_(a)); fwrite(&nlen, sizeof(uint16), 1, f); fwrite(pp_argname_(a), 1, nlen, f); } nlen = 0; fwrite(&nlen, sizeof(uint16), 1, f); } } nlen = 0; fwrite(&nlen, sizeof(uint16), 1, f); } } #endif /* NO_DUMP_STATE */ void pp_tidyup(void) { PP_HASHENTRY *p; if (feature & FEATURE_PPNOUSE) for (p = pp_hashfirst; p != 0; p = pp_hashdefchain_(p)) { if (pp_hashuses_(p) == 0) cc_warn(pp_warn_unused_macro, pp_hashname_(p)); } #ifndef NO_LISTING_OUTPUT /* This next line must happen after all diagnostics have been produced */ if (listingstream != NULL) { listing_diagnostics(); if (profile_count != 0) putc('\n', listingstream); } #endif #ifdef ENABLE_PP /* spurious: deadcode elimination fixes */ if (debugging(DEBUG_PP)) { int32 i, argcnt; PP_ARGENTRY *a; cc_msg("%ld substitutions\n", (long)pp_nsubsts); cc_msg("Hash table:\n"); for (i=0; i<PP_HASHSIZE; i++) for (p = (*pp_hashtable)[i]; p != 0; p = pp_hashchain_(p)) { cc_msg("%ld: %s", (long)i, pp_hashname_(p)); if (!pp_hashnoargs_(p)) { cc_msg("("); for (a = pp_hasharglist_(p), argcnt=0; a != 0; a=pp_argchain_(a)) cc_msg("%s%s", (argcnt++ == 0 ? "" : ","), pp_argname_(a)); cc_msg(")"); } cc_msg(" '%s'%s uses %ld\n", (pp_hashismagic_(p) ? "<magic>" : pp_hashbody_(p)), (pp_hashalive_(p) ? "" : " (undef'd)"), (long)pp_hashuses_(p)); } } #endif } void pp_copy(void) { int ch; minus_e = YES; while ((ch = pp_nextchar()) != PP_EOF) fputc(ch, stdout); } void pp_init(FileLine *fl) { time_t t0 = time(0); minus_e = FALSE; strncpy(pp_datetime, ctime(&t0), 26-1); /* be cautious */ pp_fl = fl; pp_hashtable = (PP_HASHTABLE *)pp_alloc(sizeof(*pp_hashtable)); ClearToNull((void **)pp_hashtable, sizeof(*pp_hashtable)/sizeof(void **)); pp_hashfirst = pp_hashlast = pp_noexpand = 0; pp_dbufend = pp_dbufseg = pp_dbufptr = 0; pp_ebufbase = (char *)pp_alloc(PP_EBUFINITSIZ); pp_ebufptr = pp_ebuftop = pp_ebufbase + PP_UNRDCHMAX; pp_ebufend = pp_ebufbase + PP_EBUFINITSIZ; pp_abufptr = pp_abufoptr = pp_abufbase = (char *)pp_alloc(PP_ABUFINITSIZ); pp_abufend = pp_abufbase + PP_ABUFINITSIZ; pp_scanidx = -1; pp_nsubsts = 0; pp_instring = 0; pp_inhashif = NO; pp_expand_level = 0; pp_ifstack = 0; pp_freeifstack = 0; pp_skipping = 0; pp_filestack = 0; pp_freefilestack = 0; #ifdef FORTRAN pp_stick_at_eof = 1; #endif seen_before = NULL; { int ch; for (ch = 0; ch <= UCHAR_MAX; ch++) { int i = 0; if (isalpha(ch) || ch == '_') i = PP_MACSTART + PP_CIDCHAR; if (isalnum(ch)) i |= PP_CIDCHAR; pp_ctype[ch] = i; } } pp_ctype[' '] = PP_WHITE; pp_ctype['\t'] = PP_WHITE; pp_ctype[PP_TOKSEP & 0xff] = PP_WHITE; /* args, options... */ { int i; /* @@@ AM migrated to mip/compiler.c, going again... */ for (i=0; i <= 'z'-'a'; i++) pp_pragmavec[i] = -1; } active_string_file = NULL; if (usrdbg(DBG_PP)) (void)dbg_notefileline(curlex.fl); (void)pp_predefine2("__LINE__", PP__LINE); (void)pp_predefine2("__FILE__", PP__FILE); (void)pp_predefine2("__DATE__", PP__DATE); (void)pp_predefine2("__TIME__", PP__TIME); /* __STDC__ gets set up after -zi command line pre-include file! */ pp_hashone = pp_predefine2("!!ONE!!", PP__ONE); /* for #if defined(...) */ pp_hashzero = pp_predefine2("!!ZERO!!", PP__ZERO); } static void pp_init2(FILE *stream, bool preinclude) { int ch; IGNORE(stream); /* The strange order here has to do with the definedness of conversions */ /* between int and signed/unsigned char. See early comment re RARE_char.*/ for (ch = 0; ch <= UCHAR_MAX; ++ch) { int tch; if (isprint(ch) || /* most common case */ (feature & FEATURE_PCC) || /* no more conversion */ ch == '\t' || /* allowable space ch */ legal_non_isprint(ch)) tch = ch; else if (isspace(ch)) /* convert all other end-of-line chars to '\n' */ tch = '\n'; else tch = PP_TOKSEP; pp_translate[ch] = tch; } #ifdef PASCAL pp_translate['\\'] = '\\'; #else pp_translate['\\'] = PP_TOKSEP; #endif pp_translate['\n'] = PP_TOKSEP; #ifndef FORTRAN pp_translate[COMMENT_START] = PP_TOKSEP; #endif #ifdef PASCAL pp_translate['{'] = PP_TOKSEP; #endif if (feature & FEATURE_PCC) { pp_ctype['$'] = PP_MACSTART + PP_CIDCHAR; pp_translate[PP_TOKSEP] = PP_TOKSEP; pp_translate[PP_NOEXPAND] = PP_TOKSEP; pp_translate[PP_ESC] = PP_TOKSEP; } else { if (!preinclude) { #ifdef PASCAL (void)pp_predefine2("__ISO__", PP__ONE); #else (void)pp_predefine2("__STDC__", PP__ONE); #endif if (LanguageIsCPlusPlus) /* [ES] requires the following to be set, note that __STDC__ is too!. */ { (void)pp_predefine2("__cplusplus", PP__ONE); if (feature & FEATURE_CFRONT) (void)pp_predefine2("__CFRONT_LIKE", PP__ONE); } } #ifndef PASCAL_OR_FORTRAN pp_translate['?'] = PP_TOKSEP; /* translate triglyphs */ #endif } pp_lastch = '\n'; pp_rdch1nls = pp_rdch3nls = pp_rdch_la = 0; pp_in_directive = 0; seen_pp_token = 0; } /* Perhaps better another external function than partial init on */ /* notesource (which sounds innocent) */ #ifdef INMOSC void pp_notesource(char const *filename) /* preserve interface */ { FILE *stream = stdin; #else void pp_notesource(char const *filename, FILE *stream, bool preinclude) { #endif init_pp_fl(filename); pp_cis = stream; pp_init2(stream, preinclude); if (preinclude) return; /* pre-include case.. */ #ifndef NO_LISTING_OUTPUT profile_find(filename); /* sets profile_ptr, pp_filenumber */ #endif } /* end of pp.c */
stardot/ncc
mip/driver.c
<reponame>stardot/ncc /* * driver.c - driver for Codemist compiler (RISC OS, DOS, Mac/MPW, Unix) * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Codemist Ltd., 1988-1992. * Copyright (C) Advanced RISC Machines Limited, 1990-1992. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 186 * Checkin $Date$ * Revising $Author$ */ /* AM memo: we should look at a getenv() variable to find alternative */ /* path names to /usr/include etc: This would greatly facilitate */ /* installing as an alternative C compiler and reduce the shambles */ /* (which is being tidied) in env = 2; below. */ /* AM notes that DEC's version of MIPS C compiler uses env variables */ /* COMP_HOST_ROOT and COMP_TARGET_ROOT for this. */ /* AM, Jul 89: COMPILING and TARGET flag tests have been reviewed. */ /* The effect is than running a RISCOS compiler on UNIX looks like a */ /* unix compiler (i.e. -S not -s) except for target-specific flags. */ /* Beware the TARGET_IS_HELIOS flags as not rationalised. */ /* AM: This file should more properly be called unixdriv.c: the */ /* rationale is that it munges the command line and repeatedly calls */ /* the compiler and possibly the linker just like the unix 'cc' cmd. */ /* It is target-independent, but rather host dependent. Accordingly */ /* it needs not to be used on machines like the ibm370 under MVS etc., */ /* where the file munging done is totally inappropriate. */ /* We need a HOST_ or COMPILING_ON_ test whether to include this file. */ /* Further, we would like to suppress the LINK option unless the */ /* host and target are have compatible object format. */ /* Host dependencies: 1. use of getenv("c$libroot"). 2. file name munging. 3. The HELP text in drivhelp.h More? */ #include <stddef.h> #ifdef __STDC__ # include <stdlib.h> # include <string.h> #else # include <strings.h> extern void exit(); extern char *getenv(); extern int system(); #endif #include <ctype.h> #include <stdio.h> #define uint HIDE_HPs_uint #include <signal.h> #undef uint #include <setjmp.h> #include "globals.h" #include "errors.h" #include "compiler.h" #include "store.h" #include "fname.h" #include "version.h" #include "drivhelp.h" #include "mcdep.h" #include "prgname.h" #include "pp.h" #ifdef FOR_ACORN #include "dde.h" #endif #include "toolenv2.h" #include "tooledit.h" #include "toolbox.h" #include "toolver.h" #include "trackfil.h" BackChatHandler backchat; static jmp_buf exitbuf; /*************************************************************/ /* */ /* Set up default compilation options (Arthur,Msdos,Unix) */ /* */ /*************************************************************/ /* The meaning of the bits in the user's number n in '-On' */ #define MINO_CSE 0x1 #define MINO_NAO 0x2 #define MINO_MAX 0x3 /* sum of above */ #define SMALL_COMMAND 128 #define INCLUDE_BUFLEN 64 /* initial size of include buffer */ #define MAX_TEXT 256 /* The longest filename I can handle */ /* #define BSD_CC "/usr/ucb/cc" */ #define KEY_NEXT 1L #define KEY_HOST_LIB 0x0000002L #define KEY_HELP 0x0000004L #define KEY_LINK 0x0000008L #define KEY_LISTING 0x0000010L #define KEY_PCC 0x0000020L #define KEY_CONFIG 0x0000040L #define KEY_COMMENT 0x0000080L #define KEY_ASM_OUT 0x0000100L #define KEY_XPROFILE 0x0000200L #define KEY_MAKEFILE 0x0000400L #define KEY_PREPROCESS 0x0000800L #define KEY_PROFILE 0x0001000L #define KEY_RENAME 0x0002000L #define KEY_MD 0x0008000L #define KEY_READONLY 0x0010000L #define KEY_STDIN 0x0020000L #define KEY_COUNTS 0x0040000L #ifdef RISCiX113 /* LDS 31-July-92 @@@ */ # define KEY_RIX120 0x0080000L /* Sad history; retire soon? */ # define KEY_NOSYSINCLUDES 0x0000000L /* Avoid spurious #ifdef RISCiX113 */ #else # define KEY_NOSYSINCLUDES 0x0080000L #endif #define KEY_ERRORSTREAM 0x00400000L #define KEY_VIAFILE 0x00800000L #define KEY_VERIFY 0x01000000L # define KEY_CFRONT 0x02000000L #define KEY_DEBUG 0x08000000L #ifndef FORTRAN /* IDJ 25-Mar-94: re-use FORTRAN flags for DDE purposes */ #define KEY_THROWBACK 0x10000000L #define KEY_DESKTOP 0x20000000L #define KEY_DEPEND 0x40000000L #define KEY_CFRONTPREPROCESS 0x80000000L #else #define KEY_F66 0x10000000L #define KEY_ONETRIP 0x20000000L #define KEY_UPPER 0x40000000L #define KEY_LONGLINES 0x80000000L /* The following are duplicated from ffe/feint.h. This is a temporary bodge. */ #define EXT_DOUBLECOMPLEX 1L #define EXT_HINTEGER 2L #define EXT_CASEFOLD 4L #define EXT_LCKEYWORDS 8L #define EXT_LCIDS 0x10L #define EXT_FREEFORMAT 0x20L #define EXT_IMPUNDEFINED 0x40L #define EXT_RECURSION 0x80L #define EXT_AUTO 0x100L #define EXT_HOLLERITH 0x200L #define EXT_TOPEXPRESS 0x400L #define EXT_F66 0x800L #define EXT_MIXEDCOMM 0x1000L #define EXT_VMSCHARS 0x2000L #define EXT_VMSCASTS 0x4000L #define EXT_VMSIO 0x8000L #define EXT_VMSTYPES 0x10000L #define OPT_STATICLOCALS 0x100000L #define OPT_DEFHINTEGER 0x200000L #define OPT_DEFDOUBLE 0x400000L #define OPT_IMPUNDEFINED 0x800000L #define OPT_CHECKSUB 0x1000000L #define OPT_NOARGALIAS 0x2000000L #define OPT_LONGLINES 0x4000000L #define FFEOPTS 0xfff00000L #define F66_ONETRIP 1L #define F66_IOSUBLIST 2L #define F66_INTRINSGO 4L #endif /* FORTRAN */ /*************************************************************/ /* */ /* Define the environment information structure */ /* */ /*************************************************************/ #ifdef FORTRAN # define RISCIX_FORTRAN_PRAGMAX \ (EXT_DOUBLECOMPLEX | EXT_HINTEGER | EXT_CASEFOLD | EXT_LCKEYWORDS |\ EXT_FREEFORMAT | EXT_IMPUNDEFINED | EXT_RECURSION | EXT_AUTO |\ EXT_HOLLERITH | EXT_TOPEXPRESS | EXT_F66 | EXT_MIXEDCOMM |\ EXT_VMSCHARS | EXT_VMSCASTS | EXT_VMSIO | EXT_VMSTYPES |\ OPT_STATICLOCALS | OPT_NOARGALIAS) #endif static char *driver_options[] = DRIVER_OPTIONS; static struct EnvTable { int unused; int32 initial_flags; int32 initial_pragmax; const char *include_ansi_path, *include_pcc_path, *include_pas_path; const char *lib_dir; char *lib_root, *pas_lib_root; const char *list; const char *assembler_cmd; const char *link_cmd; /* 'output_file' is also used for non-link outputs. */ /* This unix convenience just causes pain here. */ char *output_file; const char *link_ext; const char *link_startup, *profile_startup, *profile_g_startup; const char *default_lib, *host_lib, *profile_lib, *fort_lib, *fort_profile_lib, *pas_lib; } const initSetupenv = #ifdef DRIVER_ENV DRIVER_ENV #else # ifdef COMPILING_ON_ARM # ifdef COMPILING_ON_RISC_OS # ifdef FOR_ACORN { /*/* IDJ hack: 06-Jun-94 to make it work for DDE. Needs sorting out! */ 0, (KEY_LINK), 0, /* /* Perhaps $.clib, $.plib etc should be called $.lib */ "$.clib", "$.clib", "$.plib", "", "$.clib.", "$.plib", "l", "ObjAsm -quit -stamp", "CHAIN:link", NULL, "", "", "", "", "o.stubs", "o.hostlib", "o.ansilib", "o.fortlib", "o.fortlib", "o.plib" } # else { 0, (KEY_LINK), 0, /* /* Perhaps $.clib, $.plib etc should be called $.lib */ "$.clib", "$.clib", "$.plib", ".", "$.clib", "$.plib", "l", "ObjAsm", "CHAIN:link", NULL, "", "", "", "", "o.ansilib", "o.hostlib", "o.ansilib", "o.fortlib", "o.fortlib", "o.plib" } # endif # endif # ifdef COMPILING_ON_UNIX { # ifdef FORTRAN 0, (KEY_LINK), RISCIX_FORTRAN_PRAGMAX, # else 0, (KEY_PCC | KEY_LINK), 0, # endif # ifdef RISCiX113 "/usr/include/ansi", # else "/usr/include", # endif "/usr/include", "/usr/include/iso", "/", "", "", "lst", "as", "/usr/bin/ld", "a.out", "", # ifdef RISCiX113 "/lib/crt0.o", "/lib/mcrt0.o", "/lib/gcrt0.o", # else "/usr/lib/crt0.o", "/usr/lib/mcrt0.o", "/usr/lib/gcrt0.o", # endif "-lc", "", "-lc_p", # ifdef FORTRAN_NCLIB "-lnfc", "-lnfc_p", # else "-lF66,-lF77,-lI77,-lU77,-lm", "-lF66_p,-lF77_p,-lI77_p,-lU77_p,-lm_p", # endif "-lpc" } # endif /* COMPILING_ON_UNIX */ # else /* COMPILING_ON_ARM */ # ifdef COMPILING_ON_MSDOS /* Zortech / WatCom / VC++ on MSDOS */ { 0, (KEY_LINK), 0, "\\arm\\lib", "\\arm\\lib", "", "\\", "\\arm\\lib", "", "lst", "armasm", "armlink", NULL, "", "", "", "", "armlib.o", "hostlib.o", "armlib.o", "", "", "" } # else # ifdef COMPILING_ON_MACINTOSH /* arm_targetted cross_compilation : fortran & pascal not supported */ /* no default places (no root without knowing volume name) */ { #ifndef HOST_CANNOT_INVOKE_LINKER 0, (KEY_LINK), 0, #else 0, 0, 0, #endif "", "", "", ":", "", "", "lst", "armasm", "armlink", NULL, "", "", "", "", "armlib.o", "hostlib.o", "armlib.o", "", "", "" } # else # ifdef TARGET_IS_ARM /* arm_targetted cross_compilation : fortran & pascal not supported */ { 0, KEY_LINK, 0, "/usr/local/lib/arm", "/usr/local/lib/arm", "", "/", "/usr/local/lib/arm", "", "lst", "armasm", "armlink", NULL, "", "", "", "", "armlib.o", "hostlib.o", "armlib.o", "", "", "" } # else # error "No proper DRIVER_ENV information" # endif /* TARGET_IS_ARM */ # endif /* COMPILING_ON_MACINTOSH */ # endif /* COMPILING_ON_MSDOS */ # endif /* COMPILING_ON_ARM */ #endif /* DRIVER_ENV */ ; static struct EnvTable setupenv; char const Tool_Name[] = TOOLFILENAME; #ifdef COMPLING_ON_UNIX # define Compiling_On_Unix 1 #else # define Compiling_On_Unix 0 #endif #if defined(PASCAL) # define LanguageIsPascal 1 # define LanguageIsFortran 0 #elif defined(FORTRAN) # define LanguageIsPascal 0 # define LanguageIsFortran 1 #else # define LanguageIsPascal 0 # define LanguageIsFortran 0 #endif typedef struct { char const **v; Uint sz; Uint n; } ArgV; static ArgV cc_arg, cc_fil; static ArgV ld_arg, ld_fil; static int cmd_error_count, main_error_count; static int32 driver_flags; #ifdef FORTRAN static int32 pragmax_flags; #endif #ifdef HOST_OBJECT_INCLUDES_SOURCE_EXTN # define OBJ_EXTN LANG_EXTN_STRING ".o" # define ASM_EXTN LANG_EXTN_STRING ".s" #else #ifndef OBJ_EXTN # define OBJ_EXTN "o" #endif #ifndef ASM_EXTN # define ASM_EXTN "s" #endif #endif static int compiler_exit_status; void compiler_exit(int status) { compiler_exit_status = status; #ifdef NLS msg_close(NULL); #endif trackfile_finalise(); alloc_finalise(); #ifdef COMPILING_ON_MSDOS (void) signal(SIGTERM, SIG_DFL); #endif if (errors != NULL) fclose(errors); longjmp(exitbuf, 1); } /* * Join two path names and return the result. */ static const char *join_path(const char *root, const char *dir, const char *name) { if (root[0] != '\0' && name[0] != '\0') { size_t rootlen = strlen(root), dirlen = strlen(dir), namelen = strlen(name); char *new_name = (char *)PermAlloc((int32)rootlen+(int32)dirlen+(int32)namelen+1); memcpy(new_name, root, rootlen); memcpy(new_name+rootlen, dir, dirlen); memcpy(new_name+rootlen+dirlen, name, namelen+1); return new_name; } return name; } #define modifiablecopy(s) join_strs(s, "") #define PermString(s) modifiablecopy(s) static char *join_strs(const char *s1, const char *s2) { size_t s1len = strlen(s1), s2len = strlen(s2); char *s = (char *)PermAlloc((int32)s1len + (int32)s2len + 1); memcpy(s, s1, s1len); memcpy(s+s1len, s2, s2len+1); return s; } static void AddArg(ArgV *p, char const *arg) { if (p->n >= p->sz) { void *newv = PermAlloc(sizeof(char **) * 2 * p->sz); memcpy(newv, p->v, p->sz * sizeof(char **)); p->v = (char const **)newv; p->sz *= 2; } p->v[p->n++] = arg; } static char *copy_unparse(UnparsedName *unparse, const char *extn) { char *new_name; size_t n; UnparsedName u; /* A NULL extn means use the UnparsedName as-is. A non-NULL extn means */ /* use the extn given and kill any leading path segment. In this case */ /* we modify a local copy of the UnparsedName rather than unparse. */ if (extn) { u = *unparse; u.elen = strlen(extn); if (u.elen == 0) extn = NULL; u.extn = extn; #ifndef HOST_OBJECT_INCLUDES_SOURCE_EXTN u.path = NULL; u.plen = 0; u.vol = NULL; u.vlen = 0; u.type &= ~FNAME_ROOTED; #endif unparse = &u; } /* Allocate space for the returned copy of the name. Allow some spare */ /* for ^ -> .. (several times) + up to 2 extra path separators + a NUL. */ n = unparse->vlen + unparse->plen + unparse->rlen + unparse->elen + 10; new_name = (char *)PermAlloc(n); if (fname_unparse(unparse, FNAME_AS_NAME, new_name, n) < 0) driver_abort("internal fault in \"copy_unparse\""); /* @@@ syserr? */ return new_name; } /* * Get the value of an external environment variable */ static char *pathfromenv(char *var, char *ifnull) { char *def = var==NULL ? NULL : getenv(var); if (def == NULL) return ifnull; else { def = modifiablecopy(def); if (Compiling_On_Unix) { char *s = def; for (; *s != 0; s++) if (*s == ':') *s = ','; } return def; } } #ifndef C_INC_VAR # ifdef COMPILING_ON_RISC_OS # define C_INC_VAR "c$libroot" # define C_LIB_VAR "c$libroot" # define P_INC_VAR "p$libroot" # define P_LIB_VAR "p$libroot" # else # if defined(COMPILING_ON_UNIX) && defined(RELEASE_VSN) # define C_INC_VAR NULL # define C_LIB_VAR NULL # define P_INC_VAR NULL # define P_LIB_VAR NULL # else # define C_INC_VAR "NCC_INCLUDE_PATH" # define C_LIB_VAR "NCC_LIBRARY_PATH" # define P_INC_VAR "NPC_INCLUDE_PATH" # define P_LIB_VAR "NPC_LIBRARY_PATH" # endif # endif #endif static void get_external_environment(void) { char *root = pathfromenv(C_INC_VAR, ""); setupenv = initSetupenv; if (root[0] != 0) setupenv.include_ansi_path = setupenv.include_pcc_path = root; root = pathfromenv(C_LIB_VAR, setupenv.lib_root); if (root[0] != 0) { /* Moreover the 'isalpha' is essential a file-is-rooted test. */ /* similarly 'lib_dir' is just the (host) directory-separator. */ #define lib_fixupname(path) \ if (!Compiling_On_Unix || isalpha(path[0])) \ path = join_path(root, setupenv.lib_dir, path) lib_fixupname(setupenv.default_lib); lib_fixupname(setupenv.host_lib); lib_fixupname(setupenv.profile_lib); lib_fixupname(setupenv.fort_lib); lib_fixupname(setupenv.fort_profile_lib); lib_fixupname(setupenv.link_startup); lib_fixupname(setupenv.profile_startup); lib_fixupname(setupenv.profile_g_startup); } #ifdef PASCAL root = pathfromenv(P_INC_VAR, ""); if (root[0] != 0) setupenv.include_pas_path = root; root = pathfromenv(P_LIB_VAR, setupenv.pas_lib_root); if (root[0] != 0) { lib_fixupname(setupenv.pas_lib); } #endif } typedef struct { char const *name; char const *val; } NameVal; typedef struct { ToolEnv *t; ToolEdit_EnumFn *f; void *arg; char const *prefix; size_t prefix_len; Uint n; NameVal *matches; } TE_EnumRec; typedef struct { char const *prefix; size_t prefix_len; Uint n; } TE_CountRec; static int TECount_F(void *arg, char const *name, char const *val) { TE_CountRec *tp = (TE_CountRec *)arg; IGNORE(val); if (tp->prefix_len == 0 || StrnEq(name, tp->prefix, tp->prefix_len)) tp->n++; return 0; } Uint TE_Count(ToolEnv *t, char const *prefix) { TE_CountRec tr; tr.prefix = prefix; tr.prefix_len = strlen(prefix); tr.n = 0; toolenv_enumerate(t, TECount_F, &tr); return tr.n; } static int TE_EnumEnter(void *arg, char const *name, char const *val) { TE_EnumRec *tp = (TE_EnumRec *)arg; if (tp->prefix_len == 0 || StrnEq(name, tp->prefix, tp->prefix_len)) { tp->matches[tp->n].name = name; tp->matches[tp->n].val = val; tp->n++; } return 0; } static int CFNameVal(void const *a, void const *b) { NameVal const *ap = (NameVal const *)a; NameVal const *bp = (NameVal const *)b; uint32 an = strtoul(&ap->name[3], NULL, 16), bn = strtoul(&bp->name[3], NULL, 16); return an < bn ? -1 : an == bn ? 0 : 1; } int Tool_OrderedEnvEnumerate( ToolEnv *t, char const *prefix, ToolEdit_EnumFn *f, void *arg) { Uint n = TE_Count(t, prefix); TE_EnumRec tr; int rc = 0; tr.t = t; tr.f = f; tr.arg = arg; tr.prefix = prefix; tr.prefix_len = strlen(prefix); if (n != 0) { Uint i; tr.matches = (NameVal *)malloc(n * sizeof(NameVal)); tr.n = 0; toolenv_enumerate(t, TE_EnumEnter, &tr); qsort(tr.matches, tr.n, sizeof(NameVal), CFNameVal); for (i = 0; i < tr.n; i++) { rc = f(arg, tr.matches[i].name, tr.matches[i].val, FALSE); if (rc != 0) break; } free(tr.matches); } return rc; } Uint TE_Integer(ToolEnv *t, char const *name, Uint def) { char const *tval = toolenv_lookup(t, name); if (tval == NULL || tval[0] != '=') return def; return (Uint)strtoul(&tval[1], NULL, 10); } bool TE_HasValue(ToolEnv *t, char const *name, char const *val) { char const *tval = toolenv_lookup(t, name); return tval != NULL && StrEq(val, tval); } /*************************************************************/ /* */ /* Find a command line keyword and return flag */ /* */ /*************************************************************/ /* full case-insensitive */ bool cistreq(const char *s1, const char *s2) { for ( ; ; ) { int ch1 = *s1++, ch2 = *s2++; if (safe_tolower(ch1) != safe_tolower(ch2)) return NO; if (ch1 == 0) return YES; } } /* full case-insensitive */ bool cistrneq(const char *s1, const char *s2, size_t n) { while (0 < n--) { int ch1 = *s1++, ch2 = *s2++; if (safe_tolower(ch1) != safe_tolower(ch2)) return NO; if (ch1 == 0) return YES; } return YES; } /*************************************************************/ /* */ /* Add an option to a link or assembler command. */ /* */ /*************************************************************/ static int32 cmd_cat(char *cmd, int32 posn, const char *extra) { size_t l = strlen(extra); if (posn != 0 && l != 0) { if (cmd != NULL) cmd[posn] = ' '; ++posn; } if (cmd != NULL && l != 0) memcpy(cmd + posn, extra, l+1); return posn + l; } /*************************************************************/ /* */ /* Call the assembler to assemble a '.s' file */ /* */ /*************************************************************/ #ifndef HOST_CANNOT_INVOKE_ASSEMBLER #ifndef target_asm_options_ # define target_asm_options_(x) "" #endif static int assembler(ToolEnv *t, const char *asm_file, const char *obj_file) { int32 flags = driver_flags; char *cmd; char small_cmd[SMALL_COMMAND]; alloc_perfileinit(); #ifndef NO_CONFIG config_init(t); #endif cmd = NULL; for (;;) { /* once round to count the length and once to copy the strings... */ int32 cmdlen = cmd_cat(cmd, 0, setupenv.assembler_cmd); cmdlen = cmd_cat(cmd, cmdlen, target_asm_options_(t)); if (flags & KEY_DEBUG) cmdlen = cmd_cat(cmd, cmdlen, " -g"); if (flags & KEY_READONLY) cmdlen = cmd_cat(cmd, cmdlen, " -R"); if (!Compiling_On_Unix) cmdlen = cmd_cat(cmd, cmdlen, asm_file); if (Compiling_On_Unix) cmdlen = cmd_cat(cmd, cmdlen, "-o"); cmdlen = cmd_cat(cmd, cmdlen, obj_file); if (Compiling_On_Unix) cmdlen = cmd_cat(cmd, cmdlen, asm_file); if (cmd != NULL) break; if (cmdlen < SMALL_COMMAND) cmd = small_cmd; else cmd = (char *)SynAlloc(cmdlen+1); } if (driver_flags & KEY_VERIFY) cc_msg("[%s]\n", cmd); { int rc = system(cmd); drop_local_store(); return rc; } } #endif /*************************************************************/ /* */ /* Link compiled files together */ /* */ /*************************************************************/ #ifndef target_lib_name_ # define target_lib_name_(e,x) x #endif #ifndef HOST_CANNOT_INVOKE_LINKER #ifndef LINKER_IS_SUBPROGRAM typedef struct { char *cmd; int32 cmdlen; ToolEnv *t; } LinkerLibRec; static int LibEnum_F(void *arg, char const *name, char const *val, bool readonly) { LinkerLibRec *llr = (LinkerLibRec *)arg; IGNORE(readonly); IGNORE(name); llr->cmdlen = cmd_cat(llr->cmd, llr->cmdlen, target_lib_name_(llr->t, &val[1])); return 0; } #else typedef struct { char **argv; int count; ToolEnv *t; } LinkerLibRec; static int LibEnum_F(void *arg, char const *name, char const *val, bool readonly) { LinkerLibRec *llr = (LinkerLibRec *)arg; IGNORE(readonly); IGNORE(name); llr->argv[llr->count++] = modifiablecopy(target_lib_name_(llr->t, &val[1])); return 0; } #endif static void linker(ToolEnv *t, int32 flags) { #ifdef TARGET_IS_NULL /* Hmmm, but, but ... */ IGNORE(flags); #else Uint count; const char *startup; alloc_perfileinit(); #ifndef NO_CONFIG config_init(t); #endif switch (flags & (KEY_PROFILE | KEY_XPROFILE)) { case KEY_PROFILE: startup = setupenv.profile_startup; break; case KEY_XPROFILE: startup = setupenv.profile_g_startup; break; default: startup = setupenv.link_startup; break; } #ifndef LINKER_IS_SUBPROGRAM { char *cmd = NULL; int32 cmdlen, libstart; char small_cmd[SMALL_COMMAND]; for (;;) { /* once round to count the length and once to copy the strings... */ cmdlen = 0; cmdlen = cmd_cat(cmd, cmdlen, setupenv.link_cmd); for (count = 0; count < ld_arg.n; ++count) cmdlen = cmd_cat(cmd, cmdlen, ld_arg.v[count]); cmdlen = cmd_cat(cmd, cmdlen, "-o"); cmdlen = cmd_cat(cmd, cmdlen, setupenv.output_file); cmdlen = cmd_cat(cmd, cmdlen, startup); for (count = 0; count < ld_fil.n; ++count) cmdlen = cmd_cat(cmd, cmdlen, ld_fil.v[count]); libstart = cmdlen; if (flags & KEY_HOST_LIB) cmdlen = cmd_cat(cmd, cmdlen, target_lib_name_(t, setupenv.host_lib)); #ifdef PASCAL cmdlen = cmd_cat(cmd, cmdlen, target_lib_name_(t, setupenv.pas_lib)); #endif #ifdef FORTRAN cmdlen = cmd_cat(cmd, cmdlen, target_lib_name_(t, setupenv.fort_lib)); #endif { LinkerLibRec llr; llr.cmd = cmd; llr.cmdlen = cmdlen; llr.t = t; Tool_OrderedEnvEnumerate(t, "-L.", LibEnum_F, &llr); cmdlen = llr.cmdlen; } if (cmd != NULL) break; if (cmdlen < SMALL_COMMAND) cmd = small_cmd; else cmd = (char *)SynAlloc(cmdlen+1); } for (; libstart < cmdlen; libstart++) { /* space-separate, rather than comma-join, the library list */ if (cmd[libstart] == ',') cmd[libstart] = ' '; } if (driver_flags & KEY_VERIFY) cc_msg("[%s]\n", cmd); count = system(cmd); } #else /* LINKER_IS_SUBPROGRAM */ { char **argv = (char **)SynAlloc((ld_arg.n+ld_fil.n+7+TE_Count(t, "-L.")) * sizeof(char **)); extern int do_link(int argc, char **argv, backchat_Messenger *bc, void *bcarg); argv[0] = modifiablecopy(setupenv.link_cmd); memcpy(&argv[1], ld_arg.v, ld_arg.n * sizeof(char **)); count = ld_arg.n+1; argv[count++] = "-o"; argv[count++] = modifiablecopy(setupenv.output_file); if (*startup != 0) argv[count++] = modifiablecopy(startup); memcpy(&argv[count], ld_fil.v, ld_fil.n * sizeof(char **)); count += ld_fil.n; if (flags & KEY_HOST_LIB) argv[count++] = modifiablecopy(target_lib_name_(t, setupenv.host_lib)); #ifdef PASCAL argv[count++] = modifiablecopy(target_lib_name_(t, setupenv.pas_lib)); #endif #ifdef FORTRAN argv[count++] = modifiablecopy(target_lib_name_(t, setupenv.fort_lib)); #endif { LinkerLibRec llr; llr.argv = argv; llr.count = count; llr.t = t; Tool_OrderedEnvEnumerate(t, "-L.", LibEnum_F, &llr); count = llr.count; } argv[count] = 0; count = do_link(count, argv, backchat.send, backchat.handle); } #endif /* LINKER_IS_SUBPROGRAM */ if (count != 0) ++main_error_count; /* * In PCC mode delete the '.o' file if only one file was compiled. * NB. (count==0) is used to check the link was ok. */ if ((LanguageIsPascal || StrEq(toolenv_lookup(t, ".lang"), "=-pcc")) && cc_fil.n == 1 && ld_fil.n == 1 && count == 0) remove(ld_fil.v[0]); drop_local_store(); #endif /* TARGET_IS_NULL */ } #endif /* HOST_CANNOT_INVOKE_LINKER */ static int PrintEnv(void *arg, char const *name, char const *val) { IGNORE(arg); cc_msg(" %s %s", name, val); return 0; } /* * Process input file names. */ static void process_file_names(ToolEnv *t, ArgV *v) { Uint count, filc = v->n; int32 flags = driver_flags; UnparsedName unparse; /* * Reset cc_filc here - we use it to count the actual number of .c files * (so linker() can delete the intermediate object file in the case that * there is exactly 1 C file), rather than the number of files to be * processed by this function. */ cc_fil.n = 0; for (count = 0; count < filc; ++count) { char const *current = v->v[count]; int state = 0; /* hack for contorted program flow */ int extn_ch; char *source_file, *listing_file = NULL, *md_file = NULL; if (strlen(current) > MAX_TEXT-5) { cc_msg_lookup(driver_ignored_filename_overlong, current); continue; } fname_parse(current, FNAME_SUFFIXES, &unparse); #ifndef COMPILING_ON_UNIX if (unparse.extn == NULL) /* On non-Unix hosts use a sensible default if no extension was given */ #ifdef FOR_ACORN if (!cplusplus_flag) #endif { unparse.extn = LANG_EXTN_STRING; unparse.elen = sizeof(LANG_EXTN_STRING)-1; } extn_ch = unparse.extn[0]; #else if (unparse.extn == NULL) extn_ch = 0; else extn_ch = unparse.extn[0]; #endif switch(extn_ch) { #ifndef HOST_CANNOT_INVOKE_LINKER # ifdef COMPILING_ON_UNIX case 'a': # else case 'O': # endif case 'o': if (!(flags & (KEY_PREPROCESS+KEY_MAKEFILE))) { AddArg(&ld_fil, copy_unparse(&unparse, NULL)); break; } else cc_msg_lookup(driver_conflict_EM); /* and fall through ... */ #endif default: if (!(flags & (KEY_PREPROCESS+KEY_MAKEFILE))) { if ((flags & KEY_CFRONTPREPROCESS) != 0) goto case_lang_extn; cc_msg_lookup(driver_unknown_filetype, current); ++cmd_error_count; continue; } /* fall through again (-E, -M) */ #ifndef HOST_CANNOT_INVOKE_ASSEMBLER /* The logical place for this code is at NO_OBJECT.. after ccom() call. */ # ifndef COMPILING_ON_UNIX case 'S': # endif case 's': if (!(flags & (KEY_PREPROCESS+KEY_MAKEFILE))) { const char *asm_file = copy_unparse(&unparse, NULL); const char *obj_file = copy_unparse(&unparse, OBJ_EXTN); state = 1; if (assembler(t, asm_file, obj_file) != 0) { main_error_count++; remove(obj_file); } /* and fall through... foo.s... */ } /* fall through again (-E, -M, foo.s) */ #endif #ifdef COMPILING_ON_UNIX case LANG_UC_EXTN: /* unix foo.C for C++ (rework other hosts?) */ case 'i': /* for X/Open compliance (what about '.I'?) */ #else case LANG_UC_EXTN: #endif case_lang_extn: case LANG_EXTN: { char *out_file = setupenv.output_file; char *out_name = NULL; if ((flags & KEY_RENAME) && filc == 1 && !(flags & KEY_LINK)) /* Assert: KEY_RENAME => setupenv.output_file != NULL */ out_name = out_file; else if (flags & KEY_ASM_OUT) out_name = copy_unparse(&unparse, ASM_EXTN); #ifdef NO_OBJECT_OUTPUT2 /* Turn "cc -c foo.c" into "cc -S foo.c"; as foo.s" */ if (!(flags & (KEY_PREPROCESS|KEY_MAKEFILE|KEY_ASM_OUT))) out_name = copy_unparse(&unparse, ASM_EXTN); #endif if (flags & KEY_LISTING) listing_file = copy_unparse(&unparse, setupenv.list); if (flags & KEY_MD) md_file = copy_unparse(&unparse, "d"); source_file = copy_unparse(&unparse, NULL); if (out_file == NULL /* No default output file */ || filc != 1 /* more than 1 file */ || (flags & KEY_LINK) /* going to link */ || !(flags & KEY_RENAME)) /* no -o <file> */ { out_file = copy_unparse(&unparse, OBJ_EXTN); } /* else... * -o && no-link && 1-file && default-op-file */ if (out_name == NULL) out_name = out_file; if (!(flags & (KEY_MAKEFILE+KEY_PREPROCESS))) { AddArg(&ld_fil, out_file); if (state == 1) /* already called the assembler so... */ break; } if (flags & KEY_VERIFY) { cc_msg("["); toolenv_enumerate(t, PrintEnv, NULL); cc_msg("]\n"); } if (ccom(t, source_file, out_name, listing_file, md_file)) { ++main_error_count; #ifdef COMPILING_ON_RISC_OS /* The next line is dirty and should be done by checking return code, */ /* not peeking at other's variables. */ if (errorcount) /* only delete o/p file if serious errors */ #endif remove(out_name); } #ifdef NO_OBJECT_OUTPUT2 /* @@@ '2' is a temp hack */ #ifndef HOST_CANNOT_INVOKE_ASSEMBLER if (!(flags & (KEY_PREPROCESS|KEY_MAKEFILE|KEY_ASM_OUT))) { if (assembler(t, out_name, out_file) != 0) { main_error_count++; remove(out_file); } remove(out_name); } #endif #endif } /* and for the benefit of linker(), count the sources */ ++cc_fil.n; break; } /* * If no output file has been given, derive one from the 1st file name. */ if (setupenv.output_file == NULL && (flags & KEY_LINK)) setupenv.output_file = copy_unparse(&unparse, setupenv.link_ext); } } #ifdef FORTRAN # define FortranUnimplementedOption(ch,current)\ if (current[1] == ch) { nimp_option(current); break; } #else # define FortranUnimplementedOption(ch,current) #endif /*************************************************************/ /* */ /* Validate the command line keywords */ /* */ /*************************************************************/ static void validate_flags(void) { int32 flags = driver_flags; #ifdef WANT_WHINGY_MSGS_EVEN_WHEN_WRONG if (ld_arg.n != 0 && !(flags & KEY_LINK)) /* Beware: the next line catches most curios, but not -lxxx */ cc_msg_lookup(driver_ignored_linkerflags); #endif if (Compiling_On_Unix && (flags & KEY_HOST_LIB)) { cc_msg_lookup(driver_ignored_arthur_unix); flags &= ~KEY_HOST_LIB; } if (flags & KEY_COMMENT && !(flags & KEY_PREPROCESS)) flags &= ~KEY_COMMENT; if ((flags & (KEY_MAKEFILE+KEY_PREPROCESS+KEY_MD)) == (KEY_MAKEFILE+KEY_PREPROCESS)) { cc_msg_lookup(driver_conflict_EM); flags &= ~KEY_MAKEFILE; } if (flags & KEY_PROFILE && flags & KEY_XPROFILE) flags &= ~KEY_PROFILE; #ifdef FORTRAN if (flags & KEY_STRICT) { if (flags & KEY_ONETRIP) { cc_msg_lookup(driver_conflict_strict_onetrip); flags &= ~KEY_ONETRIP; } if (flags & KEY_F66) { cc_msg_lookup(driver_conflict_strict_f66); flags &= ~KEY_F66; } if (flags & KEY_LONGLINES) { cc_msg_lookup(driver_conflict_strict_extend); flags &= ~KEY_LONGLINES; } } if ((flags & KEY_F66) && (flags & KEY_ONETRIP)) { cc_msg_lookup(driver_implies_f66_onetrip); flags &= ~KEY_ONETRIP; } #endif driver_flags = flags; } static void give_help(const char *command_name) { #ifdef HOST_WANTS_NO_BANNER msg_printf(driver_banner); #endif #ifdef TIME_LIMIT { time_t expire = TIME_LIMIT; msg_fprintf(driver_expire,VENDOR_NAME,ctime(&expire)); } #endif { msg_t *p = driver_help_text; msg_printf(*p, command_name); while (*++p != NULL) msg_printf(*p,command_name); } } /*************************************************************/ /* */ /* Set command line options for current flags */ /* */ /*************************************************************/ #ifdef FORTRAN static char pragmax[16]; static char pragmaw[16]; #endif static void set_flag_options(ToolEnv *t) { #ifdef FORTRAN int32 flags = driver_flags; int32 pragmaw_flags = 0; if (flags & KEY_ONETRIP) pragmaw_flags |= F66_ONETRIP; if (flags & KEY_F66) pragmaw_flags |= (F66_ONETRIP + F66_IOSUBLIST + F66_INTRINSGO); if (flags & KEY_LONGLINES) pragmax_flags |= OPT_LONGLINES; if (flags & KEY_STRICT) pragmax_flags = 0; sprintf(pragmaw, "-zpw%-lu", pragmaw_flags); sprintf(pragmax, "-zpx%-lu", pragmax_flags); new_cc_arg(pragmaw); new_cc_arg(pragmax); #endif #if defined(TARGET_IS_UNIX) && defined (COMPILING_ON_ACORN_KIT) /* Remove -ZS<system> and -ZI<file> if -strict... */ /* AM: why? Maybe of more general use? */ if (driver_flags & KEY_STRICT) { tooledit_insert(t, "-ZI", NULL); tooledit_insert(t, "-ZS", NULL); } #else IGNORE(t); #endif } static void bad_option(const char *opt) { cc_msg_lookup(driver_option_bad, opt); ++cmd_error_count; } #ifdef FORTRAN static void nimp_option(const char *opt) { cc_msg_lookup(driver_option_nimp, opt); ++cmd_error_count; } #endif typedef struct { char const *prefix; size_t prefixlen; uint32 n; } FindLastRec; static int FindLast_F(void *arg, char const *name, char const *val) { FindLastRec *fr = (FindLastRec *)arg; IGNORE(val); if (StrnEq(name, fr->prefix, fr->prefixlen)) { uint32 n = strtoul(&name[fr->prefixlen], NULL, 16); if (n > fr->n) fr->n = n; } return 0; } static uint32 FindLast(ToolEnv *t, char const *prefix) { FindLastRec fr; fr.prefix = prefix; fr.prefixlen = strlen(prefix); fr.n = 0; toolenv_enumerate(t, FindLast_F, &fr); return fr.n; } static void AddInclude(ToolEnv *t, char const *prefix, char const *val) { char b[FILENAME_MAX+16]; uint32 n = FindLast(t, prefix); sprintf(b, "%s%lx.%s", prefix, (long)((n + 0x1fffff) & ~0xfffff), val); tooledit_insertwithjoin(t, b, '=', val); } static struct { char const *name; char const *alias; } const EnvNames[] = { { ".-Isearch",".fk" }, { ".rolits", ".fw" }, { ".enums", ".fy" }, { ".swilr", ".fz" } }; static char const *EnvName(char const *alias) { Uint i; for (i = 0; i < sizeof(EnvNames) / sizeof(EnvNames[0]); i++) if (StrEq(alias, EnvNames[i].alias)) return EnvNames[i].name; return alias; } static void EnvFlagSet(ToolEnv *t, char const *opts, int type, char const *valid, bool ignoreerrors) { char name[4]; char val[8]; bool plus = NO; int opt; for (; (opt = *opts) != 0; ++opts) if (opt == '+') plus = YES; else if (opt == '-') plus = NO; else { int ch = safe_tolower(opt); if (strchr(valid, ch) == 0) { if (!ignoreerrors) cc_warn(warn_option_letter, type, opt); } else { sprintf(name, ".%c%c", type, ch); if (plus) sprintf(val, "=-%c+%c", type, ch); else sprintf(val, "=-%c%c", type, ch); tooledit_insert(t, EnvName(name), val); } } } static void AddDefine(ToolEnv *t, char const *s) { char b[256]; char *equalp = strchr(s, '='); if (equalp == NULL) { sprintf(b, "-D%s", s); tooledit_insert(t, b, "?"); } else { int l = equalp-s; sprintf(b, "-D%.*s", l, s); tooledit_insertwithjoin(t, b, '=', equalp); } } static void debug_set(char const *opts) { int opt; for (; (opt = *opts) != 0; ++opts) { uint32 debugmask = 0; switch (safe_toupper(opt)) { #ifdef ENABLE_AETREE case 'A': ++aetree_debugcount; debugmask = DEBUG_AETREE; break; #endif case 'B': debugmask = DEBUG_BIND; break; #ifdef ENABLE_CSE case 'C': ++cse_debugcount; debugmask = DEBUG_CSE; break; #endif case 'D': debugmask = DEBUG_DATA; break; case 'E': debugmask = DEBUG_TEMPLATE; break; case 'F': debugmask = DEBUG_FNAMES; break; case 'G': debugmask = DEBUG_CG; break; case 'H': debugmask = DEBUG_SPILL; break; case 'I': ++files_debugcount; debugmask = DEBUG_FILES; break; case 'J': debugmask = DEBUG_SR; break; #ifdef ENABLE_LOCALCG case 'K': ++localcg_debugcount; debugmask = DEBUG_LOCALCG; break; #endif case 'L': debugmask = DEBUG_LEX; break; case 'M': debugmask = DEBUG_MAPSTORE; break; case 'O': debugmask = DEBUG_OBJ; break; case 'P': debugmask = DEBUG_PP; break; case 'Q': debugmask = DEBUG_Q; break; case 'R': debugmask = DEBUG_REGS; break; case 'S': debugmask = DEBUG_SYN; break; case 'T': debugmask = DEBUG_TYPE; break; case 'U': debugmask = DEBUG_STORE; break; case 'W': debugmask = DEBUG_2STORE; break; case 'X': debugmask = DEBUG_X; break; case 'Y': debugmask = DEBUG_LOOP; break; case 'Z': ++syserr_behaviour; #ifndef COMPILING_ON_MSDOS #ifdef __CC_NORCROFT (void) signal(SIGINT, SIG_DFL); /* permit NorCroft backtrace */ #endif #endif break; default: cc_warn(warn_option_zq, opt); } sysdebugmask |= debugmask; } } static void AddDebugFlags(char *s, uint32 tflags, char const *fl) { char const *p; for (p = fl; *p != 0; p++) if (!(tflags & (1L << (*p - 'a')))) *s++ = *p; *s++ = '+'; for (p = fl; *p != 0; p++) if (tflags & (1L << (*p - 'a'))) *s++ = *p; *s = 0; } static int ogflags; #define OG_O 1 #define OG_G 2 #define OG_GX 4 static bool HandleArg(ToolEnv *t, char const *current, char const *nextarg, bool ignoreerrors) { int32 flags = driver_flags; int uc_opt = safe_toupper(current[1]); bool usednext = NO; char b[512]; switch(uc_opt) { #ifdef FORTRAN case 'F': if (current[1] == 'f') break; /* @@@ LDS 10Aug89 - DO NOT CATCH 'O' HERE - IT BREAKS Unix Makefiles */ case 'M': if (current[1] == 'M') break; case 'U': case 'V': #else #ifndef DISABLE_ERRORS case 'E': if (current[2] == 'S' && current[3] == 0) break; #endif #ifndef PASCAL /*ECN*/ case 'R': #endif #endif case 'C': case 'S': if (current[2] == 0) break; if (!ignoreerrors) bad_option(current); } switch(uc_opt) { #ifdef FORTRAN case '1': flags |= KEY_ONETRIP; break; case 'C': if (current[1] == 'c') flags &= ~KEY_LINK; else pragmax_flags |= OPT_CHECKSUB; break; case 'I': if ((current[1] == 'i') && (current[2] == '2')) pragmax_flags |= OPT_DEFHINTEGER; else goto may_take_next_arg; break; case 'N': break; case 'O': if (current[1] == 'o') goto may_take_next_arg; if (current[2] != 0) /* -O has no effect currently */ { int n = (current[2] - '0'); if ((current[3] != 0) || (n < 0) || (n > MINO_MAX)) { if (!ignoreerrors) bad_option(current); } else { new_cc_arg((n & MINO_CSE) ? "-ZPZ1" : "-ZPZ0"); if (n & MINO_NAO) pragmax_flags |= OPT_NOARGALIAS; else pragmax_flags &= ~OPT_NOARGALIAS; } } break; case 'R': if (current[1] == 'R') nimp_option(current); else { if (current[2] == '8') pragmax_flags |= OPT_DEFDOUBLE; else { new_cc_arg("-R"); if (Compiling_On_Unix) flags |= KEY_READONLY; } } break; case 'U': if (current[1] == 'U') pragmax_flags &= ~EXT_CASEFOLD; else pragmax_flags |= OPT_IMPUNDEFINED; break; case 'V': if (current[1] == 'v') { new_cc_arg("-FB"); if (!ignoreerrors) cc_msg_lookup(driver_banner); } else goto link_command; break; #else /* FORTRAN */ case 'C': if (current[1] == 'c') flags &= ~KEY_LINK; else tooledit_insert(t, "-C", "?"); break; case 'I': case 'J': goto may_take_next_arg; case 'O': if (current[1] == 'o') goto may_take_next_arg; ogflags |= OG_O; if (current[2] != 0) { if (cistreq(&current[2], "time")) tooledit_insert(t, "-O", "=time"); else if (cistreq(&current[2], "space")) tooledit_insert(t, "-O", "=space"); else if (!ignoreerrors) bad_option(current); } break; #endif /* FORTRAN */ case '\0': flags |= KEY_STDIN; /* '-' on its own denotes stdin... */ break; case 'E': FortranUnimplementedOption('E', current); #ifdef DISABLE_ERRORS /* provide support for -Exyz to suppress certain errors. */ if (current[2] != 0) { EnvFlagSet(t, &current[2], 'E', "acfilmpvz", ignoreerrors); break; } #endif if (Compiling_On_Unix && current[1] == 'e') goto may_take_next_arg; /* X/Open -e epsym to ld */ #ifdef COMPILING_ON_MVS if (current[2]) { if (!ignoreerrors) cc_warn(warn_option_E, current); break; } #endif tooledit_insert(t, ".pp_only", "?"); flags &= ~KEY_LINK; break; case 'F': FortranUnimplementedOption('F', current); EnvFlagSet(t, &current[2], 'f', "abcdefhijklmnopqrstuvwxyz", ignoreerrors); break; case 'G': ogflags |= OG_G; if (current[2] == 0) { tooledit_insert(t, "-g", "=+"); tooledit_insert(t, "-gt", "=+flvp"); tooledit_insert(t, "-gx", "?"); } else if (current[2] == 'x') { ogflags |= OG_GX; tooledit_insertwithjoin(t, "-gx", '=', &current[3]); /* just option setting; no -g implication */ break; } else if (current[2] == 't') { tooledit_insertwithjoin(t, "-gt", '=', &current[3]); /* just option setting; no -g implication */ break; } else if (current[2] == '-') { tooledit_insert(t, "-g", "=-"); break; } else if (current[2] == '+') { tooledit_insert(t, "-g", "=+"); break; } else { /* old fashioned -g with flags option */ char const *p = &current[2]; int ch; uint32 tflags = 0, optflags = 0; while ((ch = *p++) != 0) switch (ch) { case 'f': case 'l': case 'v': case 'p': tflags |= (1L << (ch - 'a')); break; case 'c': case 'r': case 'g': case 'o': optflags |= (1L << (ch - 'a')); break; } if (tflags == 0) tooledit_insert(t, "-gt", "=+flvp"); else { char s[6]; AddDebugFlags(s, tflags, "flpv"); tooledit_insertwithjoin(t, "-gt", '=', s); } if (optflags == 0) tooledit_insert(t, "-gx", "?"); else { char s[5]; int i = 0; for (ch = 'a'; ch <= 'z'; ch++) if (optflags & (1L << (ch - 'a'))) s[i++] = ch; s[i] = 0; ogflags |= OG_GX; tooledit_insertwithjoin(t, "-gx", '=', s); } tooledit_insert(t, "-g", "=+"); } if (Compiling_On_Unix) AddInclude(t, "-L.", "g"); else { flags |= KEY_DEBUG; AddArg(&ld_arg, "-d"); } break; case 'L': if (Compiling_On_Unix) { if (current[1] == 'l') AddInclude(t, "-L.", &current[2]); else AddArg(&ld_arg, current); } else goto may_take_next_arg; break; case 'M': FortranUnimplementedOption('m', current); if (Compiling_On_Unix && current[1] == 'm') /* request link map */ AddArg(&ld_arg, current); else switch(safe_toupper(current[2])) { case 'X': if (current[3] != 0) goto defolt; tooledit_insert(t, "-M", "=<"); flags &= ~KEY_LINK; break; case '\0': tooledit_insert(t, "-M", "?"); flags &= ~KEY_LINK; break; case 'D': if (current[3] == '\0' || current[3] == '-' && current[4] == 0) { tooledit_insert(t, "-M", "=D"); if (current [3] == 0) flags |= KEY_MD; break; } default: defolt: if (!ignoreerrors) bad_option(current); } break; case 'P': uc_opt = safe_toupper(current[2]); switch(uc_opt) { case '\0': flags |= KEY_PROFILE; break; case 'G': case 'X': if (current[3] == '\0') { flags |= KEY_XPROFILE; break; } default: if (!ignoreerrors) bad_option(current); return usednext; } if (current[2] == 0) tooledit_insert(t, "-p", "?"); else tooledit_insertwithjoin(t, "-p", '=', &current[2]); if (setupenv.profile_lib[0] != '\0') setupenv.default_lib = setupenv.profile_lib; if (setupenv.fort_profile_lib[0] != '\0') setupenv.fort_lib = setupenv.fort_profile_lib; break; #ifndef FORTRAN case 'R': if (Compiling_On_Unix && current[1] == 'r') AddArg(&ld_arg, "-r"); /* X/Open compliance */ else { #ifdef PASCAL /*ECN*/ EnvFlagSet(t, &current[2], 'r', "acdnpr", ignoreerrors); #else tooledit_insert(t, ".rolits", "=-f+w"); #endif if (Compiling_On_Unix) flags |= KEY_READONLY; } break; #endif case 'S': if (Compiling_On_Unix && current[1] == 's') AddArg(&ld_arg, "-s"); else { flags = (flags & ~KEY_LINK) | KEY_ASM_OUT; tooledit_insert(t, ".asm_out","?"); } break; case 'W': if (current[2] == 0) { EnvFlagSet(t, "adfgilnprv", 'W', "acdfgilmnoprstuvz", ignoreerrors); tooledit_insert(t, ".nowarn", "=-W"); } else EnvFlagSet(t, &current[2], 'W', "acdfgilmnoprstuvz", ignoreerrors); break; case 'Z': uc_opt = safe_toupper(current[2]); switch(uc_opt) { case '\0': /* Pass on '-z' to the linker */ goto link_command; case 'A': if (safe_toupper(current[3]) == 'P' && isdigit(current[4])) { if (tooledit_insertwithjoin(t, "-zap", '=', &current[4]) != TE_Failed) break; } #ifdef MIN_ALIGNMENT_CONFIGURABLE else if (safe_toupper(current[3]) == 'S' && isdigit(current[4])) { if (tooledit_insertwithjoin(t, "-zas", '=', &current[4]) != TE_Failed) break; } else if (safe_toupper(current[3]) == 'T' && isdigit(current[4])) { if (tooledit_insertwithjoin(t, "-zat", '=', &current[4]) != TE_Failed) break; } #endif goto check_mcdep; case 'C': tooledit_insert(t, ".schar", "=-zc"); break; case 'I': if (isdigit(current[3])) goto check_mcdep; goto may_take_next_arg; case 'Q': debug_set(&current[3]); break; case 'O': tooledit_insert(t, ".areaperfn", "=-zo"); break; case '+': switch (safe_toupper(current[3])) { case 'O': tooledit_insert(t, ".areaperfn", "=-z+o"); break; case 'C': tooledit_insert(t, ".schar", "=-z+c"); break; default: goto check_mcdep; } break; #ifndef NO_DUMP_STATE case 'G': switch (safe_toupper(current[3])) { case 'W': tooledit_insertwithjoin(t, "-zgw", '=', &current[4]); break; case 'R': tooledit_insertwithjoin(t, "-zgr", '=', &current[4]); break; default: goto check_mcdep; } break; #endif case 'J': tooledit_insert(t, "-zj", "?"); break; case 'P': if (isalpha(current[4])) { bool negate; PragmaSpelling const *p = keyword_pragma(&current[3], &negate); if (p != NULL) { int32 val = p->value; if (negate) { #ifdef FORTRAN if (pragchar == 'x' || pragchar == 'w') val = ~val; else #endif val = !val; } sprintf(b, "-zp%c", p->code); sprintf(&b[8], "=%#lx", (long)val); tooledit_insert(t, b, &b[8]); } } else { sprintf(b, "-zp%c", current[3]); tooledit_insertwithjoin(t, b, '=', &current[4]); } break; case 'T': tooledit_insert(t, "-disallow_tentative_statics", "?"); break; case 'Z': if (safe_toupper(current[3]) == 'T') { tooledit_insert(t, "-disallow_tentative_statics", "?"); current++; } tooledit_insertwithjoin(t, "-zz", '=', &current[3]); break; check_mcdep: default: if (!mcdep_config_option(current[2], &current[3], t)) { if (!ignoreerrors) cc_warn(warn_option, current); } break; } break; link_command: default: #ifndef HOST_CANNOT_INVOKE_LINKER AddArg(&ld_arg, current); break; #else if (!ignoreerrors) bad_option(current); break; #endif #ifndef FORTRAN case 'U': #endif case 'D': may_take_next_arg: uc_opt = safe_toupper(current[1]); if (uc_opt == 'Z') { uc_opt = safe_toupper(current[2]); if (uc_opt == 'I') uc_opt = 'S'; else uc_opt = 'Z'; } if (current[2] == 0 || uc_opt == 'S' || current[3] == 0 && uc_opt == 'Z') { if (nextarg == NULL) { if (!ignoreerrors) cc_msg_lookup(driver_option_missing_arg, current); ++cmd_error_count; break; } usednext = YES; } else if (uc_opt == 'Z') nextarg = &current[3]; else nextarg = &current[2]; switch (uc_opt) { #ifdef COMPILING_ON_UNIX case 'E': /* actually can only be "-e" here... X/Open */ #endif case 'U': if (Compiling_On_Unix && current[1] != uc_opt) /* e or u */ { char *next = join_strs("-e ", nextarg); next[1] = current[1]; AddArg(&ld_arg, next); /* X/Open */ break; } /* 'U' falls through */ sprintf(b, "-D%s", nextarg); tooledit_insert(t, b, "="); break; case 'D': AddDefine(t, nextarg); break; case 'I': AddInclude(t, "-I.", nextarg); break; case 'J': AddInclude(t, "-J.", nextarg); break; #ifndef HOST_CANNOT_INVOKE_LINKER case 'L': AddInclude(t, "-L.", nextarg); break; #endif case 'O': flags |= KEY_RENAME; { UnparsedName unparse; fname_parse(nextarg, FNAME_SUFFIXES, &unparse); setupenv.output_file = copy_unparse(&unparse, NULL); } break; case 'S': /* -ZI<system> file */ tooledit_insertwithjoin(t, "-ZS", '=', &current[3]); tooledit_insertwithjoin(t, "-ZI", '=', nextarg); break; case 'Z': tooledit_insertwithjoin(t, "-zz", '=', nextarg); break; } } driver_flags = flags; return usednext; } /* * Extract compilation options from the command line. */ typedef struct { char const *name; int32 key; char const *envname; char const *envval; } KW; static KW const keytab[] = { {"-help", KEY_HELP, NULL, NULL}, {"-h", KEY_HELP, NULL, NULL}, {"-verify", KEY_VERIFY, NULL, NULL}, {"-echo", 0, ".echo", "=-echo"}, {"-link", KEY_LINK, NULL, NULL}, {"-list", KEY_LISTING, NULL, NULL}, {"-errors", KEY_NEXT+KEY_ERRORSTREAM, NULL, NULL}, {"-via", KEY_NEXT+KEY_VIAFILE, NULL, NULL}, {"-config", KEY_CONFIG}, #ifdef TARGET_ENDIANNESS_CONFIGURABLE {"-littleend", 0, ".bytesex", "=-li"}, {"-li", 0, ".bytesex", "=-li"}, {"-bigend", 0, ".bytesex", "=-bi"}, {"-bi", 0, ".bytesex", "=-bi"}, #endif #if defined(PASCAL) /*ECN*/ {"-iso", 0, ".lang", "-iso"}, {"-arthur", KEY_HOST_LIB, NULL, NULL}, {"-super", KEY_HOST_LIB, NULL, NULL}, {"-counts", KEY_COUNTS+KEY_LISTING, NULL, NULL}, #elif defined(FORTRAN) # ifndef TARGET_IS_UNIX {"-bsd", KEY_PCC, NULL, NULL}, # endif {"-onetrip", KEY_ONETRIP, NULL, NULL}, {"-fussy", KEY_STRICT, NULL, NULL}, {"-f66", KEY_F66, NULL, NULL}, {"-strict", KEY_STRICT, NULL, NULL}, {"-extend", KEY_LONGLINES, NULL, NULL}, #else /* not FORTRAN or PASCAL */ {"-ansi", 0, ".lang", "=-ansi"}, {"-ansic", 0, ".lang", "=-ansi"}, {"-pcc", 0, ".lang", "=-pcc"}, {"-fussy", 0, ".lang", "=-strict"}, {"-strict", 0, ".lang", "=-strict"}, {"-pedantic", 0, ".lang", "=-strict"}, #ifdef CPLUSPLUS {"-cfront", 0, ".lang", "=-cfront"}, {"-cpp", 0, ".lang", "=-cpp"}, #endif {"-arthur", KEY_HOST_LIB, NULL, NULL}, {"-super", KEY_HOST_LIB, NULL, NULL}, {"-counts", KEY_COUNTS+KEY_LISTING, NULL, NULL}, # ifdef FOR_ACORN {"-throwback", KEY_THROWBACK, NULL, NULL}, {"-desktop", KEY_NEXT+KEY_DESKTOP, NULL, NULL}, {"-depend", KEY_NEXT+KEY_DEPEND, NULL, NULL}, {"-c++", KEY_CFRONTPREPROCESS, NULL, NULL}, # endif # ifdef RISCiX113 {"-riscix1.2", KEY_RIX120, NULL, NULL}, # endif #endif /* PASCAL */ }; static KW const *keyword(const char *string) { unsigned count; for (count = 0; count < sizeof(keytab)/sizeof(keytab[0]); ++count) if (cistreq(string, keytab[count].name)) return &keytab[count]; return NULL; } typedef struct { char const *s; Uint i; } ViaSRec; static int vias_getc(void *arg) { ViaSRec *p = (ViaSRec *)arg; int ch = p->s[p->i]; if (ch == 0) return EOF; p->i++; return ch; } static int via_getc(void *arg) { return fgetc((FILE *)arg); } static int mapvia( void *v, int (*getcfn)(void *), char const *viafile, char **newargv) { int ch, newargc; bool got_via = NO; char word[128]; if (v == NULL) { cc_msg_lookup(driver_via_not_opened, viafile); compiler_exit(1); } for (newargc = 0, ch = ' ';;) { unsigned p = 0; while (ch != EOF && isspace(ch)) ch = getcfn(v); if (ch == EOF) break; if (ch == '"' || ch == '\'') { int quote = ch; for (;;) { ch = getcfn(v); if (ch == EOF || ch == quote) break; if (p < (sizeof(word)-1)) word[p++] = ch; } } else do { if (p < (sizeof(word)-1)) word[p++] = ch; ch = getcfn(v); } while (ch != EOF && !isspace(ch)); word[p] = 0; if (got_via) { FILE *f = fopen(word, "r"); newargc += mapvia(f, via_getc, word, newargv==NULL ? NULL : newargv+newargc); fclose(f); got_via = NO; } else if (cistreq(word, "-via")) got_via = YES; else { if (newargv != NULL) { size_t len = strlen(word)+1; newargv[newargc] = (char *)memcpy(PermAlloc((int32)len), word, len); } ++newargc; } } return newargc; } static void read_options( int count, int argc, char **argv, ToolEnv *t, bool ignoreerrors) { for (; count < argc; ++count) { char const *arg = argv[count]; KW const *key = keyword(arg); if (key == NULL) { KW_Status status = mcdep_keyword(arg, argv[count+1], t); if (status == KW_OKNEXT) { count++; continue; } else if (status == KW_OK) { continue; } else if (status != KW_NONE) { if (!ignoreerrors) { cc_msg_lookup(driver_option_bad1); cc_msg("'%s", arg); if (status == KW_BADNEXT) cc_msg(" %s", argv[++count]); cc_msg("'"); /* makes NLS string more sensible */ cc_msg_lookup(driver_option_bad2); } ++cmd_error_count; continue; } } else if (key->envname != NULL) { char b[64]; char const *s = key->envval; if (StrEq(key->envname, ".lang")) { char const *val = toolenv_lookup(t, key->envname); if (StrEq(key->envval, "=-strict")) { if (strchr(val, ' ') == NULL) { strcpy(b, val); strcat(b, " -strict"); s = b; } } else if (StrEq(val, "=-strict")) { strcpy(b, key->envval); strcat(b, " -strict"); s = b; } } tooledit_insert(t, key->envname, s); continue; } else { if (key->key & KEY_NEXT) { if (++count >= argc) { if (ignoreerrors) return; else { cc_msg_lookup(driver_option_missing_filearg, arg); compiler_exit(1); } } #ifdef FOR_ACORN if (key->key & KEY_DEPEND) { tooledit_insert(t, "-M", "=+"); tooledit_insertwithjoin(t, ".depend", '=', argv[count]); } else if (key->key & KEY_DESKTOP) dde_desktop_prefix = argv[count]; else #endif if (key->key & KEY_ERRORSTREAM) { if (!ignoreerrors) { errors = fopen(argv[count], "w"); if (errors == NULL) { cc_msg_lookup(driver_cant_open_output, argv[count]); compiler_exit(1); } } argv[count] = NULL; } else if (key->key & KEY_VIAFILE) { FILE *v = fopen(argv[count], "r"); int n = mapvia(v, via_getc, argv[count], NULL); if (n < 0) { if (ignoreerrors) return; else compiler_exit(1); } if (n == 0) ++count; else { char **newargv = (char **) PermAlloc(sizeof(char *) * ((int32)argc - count + n + 1)); int j; fseek(v, 0L, SEEK_SET); n = mapvia(v, via_getc, NULL, &newargv[1]); for (j = count; ++j < argc;) newargv[++n] = argv[j]; newargv[++n] = NULL; count = 0; argc = n; argv = newargv; } fclose(v); } } #if defined(FORTRAN) && !defined(TARGET_IS_UNIX) else if (key->key == KEY_PCC) pragmax_flags = RISCIX_FORTRAN_PRAGMAX; #endif #ifdef FOR_ACORN else if (key->key & KEY_THROWBACK) dde_throwback_flag = 1; else if (key->key & KEY_CFRONTPREPROCESS) cplusplus_flag = 1; #endif else if (key->key & KEY_COUNTS) { tooledit_insert(t, "-K", "?"); driver_flags |= key->key; } else driver_flags |= key->key; continue; } /* not a keyword argument */ if (arg[0] == '-') { if (HandleArg(t, arg, argv[count+1], ignoreerrors)) count++; } else { AddArg(&cc_fil, arg); } } if (ogflags & OG_O) { tooledit_insert(t, "-zpz", "=1"); if (ogflags & OG_G && !(ogflags & OG_GX)) tooledit_insert(t, "-gx", "=o"); } #ifdef PASCAL /*ECN*/ driver_flags |= KEY_ANSI; #endif } void TE_DecodeArgumentLine(ToolEnv *t, char const *s, bool ignoreerrors) { ViaSRec vr; int n; vr.i = 0; vr.s = s; n = mapvia(&vr, vias_getc, NULL, NULL); if (n < 0) compiler_exit(1); if (n > 0) { char **newargv = (char **)PermAlloc(sizeof(char *) * ((int32)n+1)); vr.i = 0; n = mapvia(&vr, vias_getc, NULL, newargv); newargv[n] = NULL; read_options(0, n, newargv, t, ignoreerrors); } } static void FinishedOptions(ToolEnv *t) { #ifdef RISCiX113 if (!(driver_flags & KEY_RIX120)) tooledit_insert(t, "-D__type", "==___type"); #endif if (FindLast(t, "-J.") == 0) { /* * No -J so add default system path to -I list */ #ifdef PASCAL const char *path = setupenv.include_pas_path; #else const char *path = setupenv.include_pcc_path; # ifdef RISCiX113 if (((flags & KEY_ANSI) || !(flags & (KEY_PCC))) && !(flags & KEY_RIX120)) path = setupenv.include_ansi_path; # endif #endif AddInclude(t, "-I.", path); } /* If compiling on Unix and in Ansi mode add extra libraries. */ /* * ACN: Oh misery - if I am compiling and linking under Unix, but to generate * Helios binaries, I do not want to scan the extra libraries indicated * here. I think the problem here is mostly because TARGET_IS_HELIOS * improperly sets the KEY_UNIX bit in flags - but to invent a KEY_HELIOS * would also be some work since elsewhere in this code there seems * to be a dichotomy assumed between Unix and Risc-OS... * AM: except for this file the alternative of MVS should be possible! * Thus the conditional * compilation here seems (in the short term) my easiest way out. */ #ifdef RISCiX113 if (((flags & KEY_ANSI) || !(flags & (KEY_PCC))) && !(flags & KEY_RIX120)) { AddInclude(t, "-L.", "ansi"); AddInclude(t, "-L.", "m"); } #endif if (FindLast(t, "-L.") == 0 || Compiling_On_Unix) AddInclude(t, "-L.", setupenv.default_lib); } /* * Main. */ static void InitArgV(ArgV *p, int n) { p->v = (char const **)PermAlloc(sizeof(char *) * n); p->sz = n; p->n = 0; } static char *progname_copy; char const *compiler_name(void) { return progname_copy; } static void *falloc(size_t n) { return PermAlloc(n); } static int cc_main(int argc, char **argv, ToolEnv *t) { char *progname; bool is_cpp = NO; #if (defined(COMPILING_ON_UNIX) && defined(FORTRAN)) progname = "f77"; /* rather than the "f77comp" we would get from argv[0] */ #else char p[32]; char *default_output = setupenv.output_file; #endif errors = NULL; sysdebugmask = 0; syserr_behaviour = 0; aetree_debugcount = 0; #ifdef ENABLE_CSE cse_debugcount = 0; #endif localcg_debugcount = 0; #ifdef TARGET_HAS_DEBUGGER usrdbgmask = 0; #endif alloc_initialise(); trackfile_initialise(falloc); errstate_initialise(); progname = program_name(argv[0], p, 32); progname_copy = PermString(progname); #ifdef TIME_LIMIT if (time(0) > TIME_LIMIT) { fprintf(stderr, "This time-limited software has expired.\nPlease contact " VENDOR_NAME /* specified in options.h */ " for an up to date release.\n"); compiler_exit(99); } #endif main_error_count = cmd_error_count = 0; #ifdef CHECK_AUTHORIZED check_authorized(); #endif #ifdef NLS msg_init(argv[0], MSG_TOOL_NAME); #endif #ifndef HOST_WANTS_NO_BANNER cc_msg_lookup(driver_banner); #endif #ifndef COMPILING_ON_UNIX #ifndef COMPILING_ON_MSDOS (void) signal(SIGINT, compile_abort); #else /* DOS, Windows, Win32 */ (void) signal(SIGTERM, compile_abort); #endif #else # ifdef DRIVER_PRE_RELEASE_MSG cc_msg_lookup(driver_prerelease); # endif #ifndef COMPILING_ON_MSDOS /* The signal ignore state can be inherited from the parent... */ if (signal(SIGINT, SIG_IGN) != SIG_IGN) (void) signal(SIGINT, compile_abort); #ifdef SIGHUP if (signal(SIGHUP, SIG_IGN) != SIG_IGN) (void) signal(SIGHUP, compile_abort); #endif if (signal(SIGTERM, SIG_IGN) != SIG_IGN) (void) signal(SIGTERM, compile_abort); #endif #endif get_external_environment(); driver_flags = setupenv.initial_flags; #ifdef FORTRAN pragmax_flags = setupenv.initial_pragmax; #endif if (argc == 1) { /* used with no argument */ give_help(progname); compiler_exit(1); } { UnparsedName un; fname_parse(argv[0], ".exe .EXE" , &un); if (un.rlen == 3 && (StrnEq(un.root, "cpp", 3) || StrnEq(un.root, "CPP", 3))) { /* The compiler was called as '...cpp' - treat as 'cc -E'. */ driver_flags = (driver_flags | KEY_PREPROCESS) & ~KEY_LINK; tooledit_insert(t, ".pp_only", "?"); } } InitArgV(&cc_arg, argc); InitArgV(&cc_fil, argc); InitArgV(&ld_arg, argc); InitArgV(&ld_fil, argc); { char const *etc = toolenv_lookup(t, ".etc"); if (etc != NULL) TE_DecodeArgumentLine(t, &etc[1], NO); } read_options(1, argc, argv, t, NO); #ifdef FOR_ACORN if (!(driver_flags & KEY_CFRONTPREPROCESS)) /* IDJ: 06-Jun-94: banner if not -c++ */ cc_msg_lookup(driver_banner); #endif validate_flags(); if (driver_flags & KEY_HELP) { give_help(progname); compiler_exit(0); } if (driver_flags & KEY_CONFIG) { if (toolenv_putinstallationdelta(t) != 0) { cc_msg_lookup(driver_toolenv_writefail); compiler_exit(EXIT_error); } compiler_exit(0); } FinishedOptions(t); { char const *echoval = toolenv_lookup(t, ".echo"); if (echoval != NULL && StrEq(echoval, "=-echo")) { size_t atstart = 1; char line[256]; char *dynline = NULL; char *linep = line; int len; if (argv[0] != NULL) atstart += strlen(argv[0])+1; len = tooledit_getcommandline(t, line+atstart, 254-atstart); if (len > (int)(254-atstart)) { dynline = (char *)malloc(len+2+atstart); len = tooledit_getcommandline(t, dynline+atstart, len+2); linep = dynline; } linep[0] = '['; if (argv[0] != NULL) { strcpy(linep+1, argv[0]); linep[atstart-1] = ' '; } linep[len+atstart-1] = ']'; linep[len+atstart] = '\n'; linep[len+atstart+1] = 0; cc_msg(linep); if (dynline != NULL) free(dynline); } } set_flag_options(t); if (toolenv_lookup(t, ".pp_only") != NULL) { is_cpp = YES; if (cc_fil.n >= 2) { if (cc_fil.n > 2) cc_msg_lookup(driver_cpp_toomanyfileargs); if (freopen(cc_fil.v[1], "w", stdout) == NULL) { cc_msg_lookup(driver_cpp_cantopenoutput, cc_fil.v[1]); compiler_exit(EXIT_error); } cc_fil.n = 1; } } if (cc_fil.n > 0) { if (driver_flags & KEY_STDIN) cc_msg_lookup(driver_stdin_otherfiles); process_file_names(t, &cc_fil); } else if (is_cpp || (driver_flags & KEY_STDIN)) { char *output_file = setupenv.output_file == default_output ? NULL : setupenv.output_file; /* was: output_file = setupenv.output_file; but writes asm to a.out */ /* we need to separate the differing uses of "output_file". */ #ifdef DEFAULT_STDIN_OBJECT if (!(driver_flags & (KEY_PREPROCESS|KEY_MAKEFILE|KEY_ASM_OUT)) && setupenv.output_file == NULL) output_file = DEFAULT_STDIN_OBJECT; #endif if (ccom(t, "-", output_file, NULL, NULL)) { ++main_error_count; if (output_file != NULL) #ifdef COMPILING_ON_RISC_OS /* The next line is dirty and should be done by checking return code, */ /* not peeking at other's variables. */ if (errorcount) /* only delete o/p file if serious errors */ #endif remove(output_file); } } else cc_msg_lookup(driver_noeffect, progname); #ifndef HOST_CANNOT_INVOKE_LINKER # ifdef LINKER_IS_SUBPROGRAM /* IJR: hack to ensure that path gets passed to linker in argv[0] for NLS */ { UnparsedName un; size_t n; char *new_name; fname_parse(argv[0], "" , &un); un.root = setupenv.link_cmd; un.rlen = strlen(un.root); n = un.vlen + un.plen + un.rlen + un.elen + 10; new_name = (char *)PermAlloc(n); if (fname_unparse(&un, FNAME_AS_NAME, new_name, n) < 0) driver_abort("internal fault in \"copy_unparse\""); /* @@@ syserr? */ setupenv.link_cmd = new_name; } # endif if (main_error_count == 0 && (driver_flags & KEY_LINK) && ld_fil.n > 0) linker(t, driver_flags); #endif /* * The SUN ignores the return value from main so exit() instead */ compiler_exit(main_error_count + cmd_error_count > 0 ? EXIT_error : 0); return 0; } static int cc(int argc, ArgvType *argv, ToolEnv *t, backchat_Messenger *sendmsg, void *backchathandle) { int status; backchat.send = sendmsg; backchat.handle = backchathandle; status = setjmp(exitbuf); if (status == 0) status = cc_main(argc, argv, t); else status = compiler_exit_status; return status; } char const *toolenv_toolname(void) { return MSG_TOOL_NAME; } ToolEnv *cc_default_env; static int cc_finalise(ToolEntryPoints const *te) { IGNORE(te); if (cc_default_env != NULL) toolenv_dispose(cc_default_env); return 0; } static int MergeEnv(ToolEnv *t, ToolEnvDelta delta) { int rc; alloc_initialise(); rc = toolenv_merge(t, delta); if (rc == 0) TE_NormaliseEtc(t); alloc_finalise(); return rc; } static int CC_EditEnv(ToolEnv *t, HWND wh) { int rc; alloc_initialise(); rc = Tool_EditEnv(t, wh); alloc_finalise(); return rc; } static ToolEntryPoints const entries = { cc_finalise, cc, toolenv_new, toolenv_dispose, MergeEnv, toolenv_mark, toolenv_getdelta, toolenv_putinstallationdelta, CC_EditEnv, NULL }; const ToolEntryPoints *armccinit(void) { cc_default_env = NULL; return &entries; } typedef struct { char const *name; char const *val; } EnvItem; #ifdef TARGET_DEFAULT_BIGENDIAN # if TARGET_DEFAULT_BIGENDIAN # define BYTESEX_DEFAULT_STR "=-bi" # else # define BYTESEX_DEFAULT_STR "=-li" # endif #else # define BYTESEX_DEFAULT_STR "=-li" #endif #define str(s) #s #define xstr(s) str(s) static EnvItem const builtin_defaults[] = { {".bytesex", BYTESEX_DEFAULT_STR}, #if defined(CPLUSPLUS) {".lang", "=-cpp"}, #elif defined(TARGET_IS_UNIX) {".lang", "=-fc"}, #else {".lang", "=-ansi"}, #endif #if (D_SUPPRESSED & D_IMPLICITCAST) {".Ec", "=-Ec"}, #else {".Ec", "=-E+c"}, #endif #if (D_SUPPRESSED & D_PPALLOWJUNK) {".Ep", "=-Ep"}, #else {".Ep", "=-E+p"}, #endif #if (D_SUPPRESSED & D_ZEROARRAY) {".Ez", "=-Ez"}, #else {".Ez", "=-E+z"}, #endif #if (D_SUPPRESSED & D_CAST) {".Ef", "=-Ef"}, #else {".Ef", "=-E+f"}, #endif #if (D_SUPPRESSED & D_LINKAGE) {".El", "=-El"}, #else {".El", "=-E+l"}, #endif #ifdef TARGET_WANTS_FUNCTION_NAMES {".ff", "=-f+f"}, #else {".ff", "=-ff"}, #endif {".fa", "=-f+a"}, {".fv", "=-f+v"}, #if (D_SUPPRESSED & D_ASSIGNTEST) {".Wa", "=-Wa"}, #else {".Wa", "=-W+a"}, #endif #if (D_SUPPRESSED & D_DEPRECATED) {".Wd", "=-Wd"}, #else {".Wd", "=-W+d"}, #endif #if (D_SUPPRESSED & D_IMPLICITFNS) {".Wf", "=-Wf"}, #else {".Wf", "=-W+f"}, #endif #if (D_SUPPRESSED & D_GUARDEDINCLUDE) {".Wg", "=-Wg"}, #else {".Wg", "=-W+g"}, #endif #if (D_SUPPRESSED & D_LOWERINWIDER) {".Wl", "=-Wl"}, #else {".Wl", "=-W+l"}, #endif #if (D_SUPPRESSED & D_IMPLICITNARROWING) {".Wn", "=-Wn"}, #else {".Wn", "=-W+n"}, #endif #if (D_SUPPRESSED & D_MULTICHAR) {".Wm", "=-Wm"}, #else {".Wm", "=-W+m"}, #endif #if (D_SUPPRESSED & D_LONGLONGCONST) {".Wo", "=-Wo"}, #else {".Wo", "=-W+o"}, #endif #if (D_SUPPRESSED & D_PPNOSYSINCLUDECHECK) {".Wp", "=-Wp"}, #else {".Wp", "=-W+p"}, #endif #if (D_SUPPRESSED & D_STRUCTPADDING) {".Ws", "=-Ws"}, #else {".Ws", "=-W+s"}, #endif #if (D_SUPPRESSED & D_FUTURE) {".Wu", "=-Wu"}, #else {".Wu", "=-W+u"}, #endif #if (D_SUPPRESSED & D_IMPLICITVOID) {".Wv", "=-Wv"}, #else {".Wv", "=-W+v"}, #endif #if (D_SUPPRESSED & D_STRUCTASSIGN) {".Wz", "=-Wz"}, #else {".Wz", "=-W+z"}, #endif #ifdef CPLUSPLUS # if (D_SUPPRESSED & D_CFRONTCALLER) {".Wc", "=-Wc"}, # else {".Wc", "=-W+c"}, # endif # if (D_SUPPRESSED & D_IMPLICITCTOR) {".Wi", "=-Wi"}, # else {".Wi", "=-W+i"}, # endif # if (D_SUPPRESSED & D_IMPLICITVIRTUAL) {".Wr", "=-Wr"}, # else {".Wr", "=-W+r"}, # endif # if (D_SUPPRESSED & D_UNUSEDTHIS) {".Wt", "=-Wt"}, # else {".Wt", "=-W+t"}, # endif #endif {".-Isearch","=-f+k"}, {"-O", "=mix"}, #if defined(TARGET_IS_UNIX) || defined(TARGET_HAS_SEPARATE_CODE_DATA_SEGS) {".rolits", "=-fw"}, #else {".rolits", "=-f+w"}, #endif {".enums", "=-f+y"}, {".schar", "=-z+c"}, {".swilr", "=-f+z"}, {"-gx", "?"}, {"-gt", "=+p"}, {"-g", "=-"}, {".nowarn", "?"}, #ifdef PASCAL {".rd", "=-rd"}, #endif #ifdef DEFAULT_DOES_NO_CSE {"-zpz", "=0"}, #else {"-zpz", "=1"}, #endif {"-D__CC_NORCROFT", "==1"}, /* * Predefine some symbols that give basic information about the size * of objects. These are made to exist because ANSI rules mean that * one can not go * #if sizeof(xxx) == nnn * as a pre-processing directive. */ {"-D__sizeof_int", "==" xstr(sizeof_int)}, {"-D__sizeof_long", "==" xstr(sizeof_long)}, {"-D__sizeof_ptr", "==" xstr(sizeof_ptr)}, { "-zat", "=" xstr(alignof_toplevel_static_default) }, {NULL, NULL} }; int toolenv_insertdefaults(ToolEnv *t) { EnvItem const *p = builtin_defaults; char v[8]; char const *s = TOOLVER_ARMCC; int i; int rc; v[0] = v[1] = '='; for (i = 2; isdigit(s[0]) || s[0] == '.'; i++, s++) v[i] = s[0]; v[i] = 0; tooledit_insert(t, "-D__ARMCC_VERSION", v); for (; p->name != NULL; p++) { ToolEdit_InsertStatus rc = tooledit_insert(t, p->name, p->val); if (rc == TE_Failed) return 1; } { int argc = 0; char **argp; for (argp = driver_options; *argp != NULL; ++argp) argc++; read_options(0, argc, driver_options, t, NO); } { static char const * const predefs[] = TARGET_PREDEFINES; Uint i; for (i=0; i < sizeof(predefs)/sizeof(predefs[0]); i++) /* note that the arg may be of the form "name" or "name=toks" */ /* the "name" form is equivalent to "name=1". */ AddDefine(t, predefs[i]); } if (setupenv.initial_flags & KEY_PCC) tooledit_insert(t, ".lang", "-pcc"); #ifdef TARGET_SUPPORTS_TOOLENVS rc = mcdep_toolenv_insertdefaults(t); #endif TE_NormaliseEtc(t); if (cc_default_env == NULL) { cc_default_env = toolenv_copy(t); } return rc; } /* End of driver.c */
stardot/ncc
armthumb/inlnasm.h
/* * inlnasm.h: ARM/Thumb inline assembler header * Copyright (C) Advanced Risc Machines Ltd., 1997 * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _inlnasm_h #define _inlnasm_h #ifdef TARGET_HAS_INLINE_ASSEMBLER #include "cgdefs.h" #include "jopcode.h" #include "mcdpriv.h" #define ASM_NONE 0 #define ASM_STRING 1 #define ASM_BLOCK 2 #define MKOP(op,icl) ((op)|((icl)<<16)) #define OPCODE(opcode) ((opcode)&255) #define INSTRCL(opcode) (((opcode)>>16)&15) #define GETCC(opcode) ((opcode)&0xf0000000) #define GETSHIFT(opcode)((opcode)&0x00007000) #define INVCC(cc) ((cc)^0x10000000) #define CC_EQ 0x00000000U #define CC_NE 0x10000000U #define CC_CS 0x20000000U #define CC_CC 0x30000000U #define CC_MI 0x40000000U #define CC_PL 0x50000000U #define CC_VS 0x60000000U #define CC_VC 0x70000000U #define CC_HI 0x80000000U #define CC_LS 0x90000000U #define CC_GE 0xa0000000U #define CC_LT 0xb0000000U #define CC_GT 0xc0000000U #define CC_LE 0xd0000000U #define CC_AL 0xe0000000U #define CC_NOT 0xf0000000U #define SET_CC 0x08000000 #define SET_PSR 0x04000000 enum { M_SIGNED = 0x0100, M_BYTE = 0x0200, M_HALF = 0x0400, M_WORD = 0x0000, M_LONG = 0x0100, /* for LDC/STC */ M_PREIDX = 0x1000, M_UPIDX = 0x2000, M_WB = 0x4000, M_TRANS = 0x8000, /* LDRT/STRT */ MM_DA = 0x0000, MM_DB = 0x1000, MM_IA = 0x2000, MM_IB = 0x3000, MM_TYPE = 0x3000, MM_STACK = 0x0100 /* temporary flag LDM/STM */ }; enum { SH_LSL = 0x00000000, SH_LSR = 0x00100000, SH_ASR = 0x00200000, SH_ROR = 0x00300000, SH_RRX = 0x00400000, SH_MASK= 0x00700000 }; enum { RN_REG = 0x00000000, RN_CONST = 0x01000000, RN_SHIFT = 0x02000000, RN_SHIFT_REG = 0x03000000, RN_OPND_MASK = 0x03000000 }; enum { CPSR = 0, SPSR = 16, PSR_F = 8, PSR_S = 4, PSR_X = 2, PSR_C = 1, PSR_CF = PSR_C + PSR_F, PSR_FLAGS = PSR_F+PSR_S+PSR_X+PSR_C }; /* instruction classes */ enum { CL_NONE, CL_MOV, CL_CMP, CL_BIN, CL_MEM, CL_LDM, CL_MUL, CL_MULL, CL_SWI, CL_SWP, CL_PSR, CL_BR, CL_COP, CL_CMEM, CL_NOP, CL_SH }; enum { A_AND = 0x00, A_EOR = 0x01, A_SUB = 0x02, A_RSB = 0x03, A_ADD = 0x04, A_ADC = 0x05, A_SBC = 0x06, A_RSC = 0x07, A_TST = 0x08, A_TEQ = 0x09, A_CMP = 0x0a, A_CMN = 0x0b, A_ORR = 0x0c, A_MOV = 0x0d, A_BIC = 0x0e, A_MVN = 0x0f, A_MRS = 0x10, A_MSR = 0x11, A_MUL = 0x12, A_MLA = 0x13, A_MULL= 0x14, A_MLAL= 0x15, A_LDR = 0x16, A_STR = 0x17, A_LDM = 0x18, A_STM = 0x19, A_SWP = 0x1a, A_SWI = 0x1b, A_B = 0x1c, A_BL = 0x1d, A_CDP = 0x1e, A_MRC = 0x1f, A_MCR = 0x20, A_LDC = 0x21, A_STC = 0x22, A_NOP = 0x23, A_LABEL = 0x24, NUM_ARM_OPCODES = 0x25, T_NEG = 0x25, T_ASR = 0x26, T_LSL = 0x27, T_LSR = 0x28, T_ROR = 0x29 }; extern void cg_asm(Cmd *c); extern void translate_asm_instr(PendingOp *cur); extern int32 trans_cc_tab [16]; #define translate_cc(asmcc) (trans_cc_tab[GETCC(asmcc)>>28]) #define is_asminstr(op) ((op & J_TABLE_BITS) >= J_FIRST_ASM_JOPCODE && \ (op & J_TABLE_BITS) <= J_LAST_ASM_JOPCODE) #define asminstr(op) OPCODE(op) #else #define SET_CC 0 #define cg_asm (c) #define translate_asm_instr(c) #define is_asminstr(op) 0 #endif extern Cmd *rd_asm_block(void); extern Expr *rd_asm_decl(void); #endif
stardot/ncc
mip/cg.h
<reponame>stardot/ncc /* * mip/cg.h * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Codemist Ltd., 1987-1992. * Copyright (C) Advanced RISC Machines Limited, 1991-1992. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef _cg_h #define _cg_h 1 #ifndef _defs_LOADED # include "defs.h" #endif #ifndef _cgdefs_LOADED # include "cgdefs.h" #endif #ifndef _jopcode_LOADED #include "jopcode.h" #endif extern bool has_main; extern J_OPCODE Q_swap(J_OPCODE); /* alter a condition mask as required after interchanging the two operands of a comparison */ extern Binder *gentempvarofsort(RegSort sort); extern Binder *gentempvarofsortwithname(RegSort sort, char *name); #if defined(CALLABLE_COMPILER) #define cg_topdecl(x, fl) ((void)0) #define cg_reinit() ((void)0) #define cg_tidy() ((void)0) #define cg_topdecl2(locals,regs) ((void)0) #define cg_init() ((void)0) #define cg_sub_reinit() ((void)0) #else extern void cg_topdecl(TopDecl *x, FileLine fl); extern void cg_reinit(void); extern void cg_tidy(void); extern void cg_topdecl2(BindList *local_binders, BindList *regvar_binders); extern void cg_init(void); extern void cg_sub_reinit(void); #endif extern VRegnum cg_exprvoid(Expr *x); extern VRegnum cg_expr(Expr *x); extern void bfreeregister(VRegnum r); extern VRegnum fgetregister(RegSort rsort); extern VRegnum cg_storein(VRegnum r,Expr *val,Expr *e,AEop flag); #endif /* end of mip/cg.h */
stardot/ncc
tests/2672.c
<reponame>stardot/ncc /* * ARM C compiler regression test $RCSfile$ * Copyright (C) 1997 Advanced Risc Machines Ltd. All rights reserved. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #include "testutil.h" __int64 ll_2672; double d_2672; float f_2672; t_2672() { f_2672 = ll_2672; d_2672 = ll_2672; /* convert long long to a double */ } /********************* ***********************/ int main(void) { BeginTest(); EQI(0,0); EndTest(); return 0; }
stardot/ncc
mip/cgdefs.h
<filename>mip/cgdefs.h /* * cgdefs.h - structures used by the back-end * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Codemist Ltd., 1987-1992. * Copyright 1991-1997 Advanced Risc Machines Limited. All rights reserved * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 4 * Checkin $Date$ * Revising $Author$ */ #ifndef _cgdefs_LOADED #define _cgdefs_LOADED /* see mip/defs.h for explanation of this... */ typedef struct BlockHead BlockHead; typedef struct Icode Icode; typedef struct VRegSet *VRegSetP; typedef struct BlockList BlockList; typedef struct CSEBlockHead CSEBlockHead; typedef struct SRBlockHead SRBlockHead; /* * LabelNumbers describe compiler-generated labels (e.g. arising from if-else * and looping constructs). The structure of the forward references list is * defined and managed by target-specific local code generators. The defn field * is also multiply used as a jopcode location (by the code generator) and as * a machine-code location (by the local code generator). Source-level labels * also have associated LabelNumbers addressed via label binders. */ struct LabelNumber { /* compiler-generated-label descriptor */ BlockHead *block; /* block containing label */ union { List *frefs; /* forwd ref list, managed by local cg */ int32 defn; /* jopcode location or code location */ } u; int32 name; /* 'name' (internal label number) - */ }; /* top bit indicates 'label defined' */ /* * Useful access and constructor functions... */ #define addfref_(l,v) ((l)->u.frefs = \ (List *)binder_icons2((l)->u.frefs,(v))) #define addlongfref_(l,v,i) ((l)->u.frefs = \ (List *)binder_icons3((l)->u.frefs,(v),(IPtr)(i))) #define lab_isset_(l) ((l)->name < 0) #define lab_setloc_(l,v) ((l)->name |= ~0x7fffffff, (l)->u.defn = (v)) #define lab_name_(l) ((l)->name) #define lab_xname_(l) (is_exit_label(l) ? (int32)(IPtr)(l) : \ lab_name_(l) & 0x7fffffff) #define lab_block_(l) ((l)->block) /* * A list of labels numbrs is a generic List... used by local code generators * and by disassemblers. The mk function has the obvious sort: * mkLabList: LabList x LabelNumber -> LabList */ typedef struct LabList LabList; #ifndef labcdr # define labcdr cdr #endif struct LabList { LabList *labcdr; LabelNumber *labcar; }; #define mkLabList(a,b) ((LabList *)binder_cons2((LabList *)a,(LabelNumber *)b)) typedef struct HandlerList HandlerList; struct HandlerList { HandlerList* cdr; int /*TypeId*/ type; LabelNumber *handler;}; typedef enum { ex_destructor, ex_handlerblock } ex_enum; /* * Structure describing an exception environment (one per basic block) */ typedef struct ExceptionEnv ExceptionEnv; struct ExceptionEnv { ExceptionEnv *cdr; ex_enum type; union { Binder *destructee; struct HandlerEnv { int handlercount; LabelNumber *handlerblock; HandlerList *handlerlist; } henv; } handlers; }; extern ExceptionEnv *currentExceptionEnv; /* * Structure describing a basic block. */ struct BlockHead { struct Icode *code; /* start of 3-address code */ int32 length; /* length of ditto */ int32 flags; /* misc flag bits (incl. exit cond) */ union { LabelNumber *next; /* successor block */ LabelNumber **table; /* or block table for switch */ BlockHead *backp; /* for branch_chain() only */ } succ1; union { LabelNumber *next1; /* alternative successor */ /* int32 */ IPtr tabsize; /* or size of switch table */ BlockHead *backp1; /* for branch_chain() only */ } succ2; BlockHead *down; /* forward chaining */ BlockHead *up; /* backward chaining */ LabelNumber *lab; /* label for this block */ VRegSetP use; /* registers needed at block head */ /* (private to regalloc) */ /* and also dominators of this block */ /* (during cse & live range splitting*/ union { BindList *l; /* binders active at head of block */ /* int32 */ IPtr i; } stack; BindListList *debenv; /* @@@ temp/rationalise - see flowgraph */ BlockList *usedfrom; /* list of blocks that ref. this one */ union { CSEBlockHead *cse; SRBlockHead *sr; } extra; int32 loopnest; /* depth of loop nesting in this blk */ ExceptionEnv* exenv; /* exception environment */ }; #define blklstcdr cdr #define blkcode_(x) (x->code) /* start of 3-address code */ #define blklength_(x) (x->length) /* length of ditto */ #define blkflags_(x) (x->flags) /* misc flag bits */ #define blknext_(x) (x->succ1.next) /* successor block */ #define blknext1_(x) (x->succ2.next1) /* alternative successor */ #define blktable_(x) (x->succ1.table) /* table of successors */ #define blktabsize_(x) (x->succ2.tabsize) /* size of aforesaid table */ #define blkbackp_(x) (x->succ1.backp) /* for branch_chain() only */ #define blkbackp1_(x) (x->succ2.backp1) /* for branch_chain() only */ #define blkdown_(x) (x->down) /* forward chaining */ #define blkup_(x) (x->up) /* backward chaining */ #define blklab_(x) (x->lab) /* label for this block */ #define blkuse_(x) (x->use) /* registers needed at block head */ #define blk_dominators_(x) (x->use) #define blkstack_(x) (x->stack.l) /* binders active at head of block */ #define blkstacki_(x) (x->stack.i) #define blkdebenv_(x) (x->debenv) /* for debugger */ #define blkusedfrom_(x) (x->usedfrom) /* used in cross-jump optimization */ #define blknest_(x) (x->loopnest) /* # loops enclosing this block. */ #define blkexenv_(x) (x->exenv) /* exception environment */ #define blkcse_(x) (x->extra.cse) #define blksr_(x) (x->extra.sr) /* bits for use in blkflags_(x) */ /* #define BLKREFMASK 3L DEFUNCT refcount 0,1,2,many */ #define BLKALIVE 4L /* used when flattening graph */ #define BLKSWITCH 8L /* contains 'switch' multi-exit */ #define BLK2EXIT 0x10L /* contains conditional exit */ #define BLKBUSY 0x20L /* used when flattening graph */ #define BLKCODED 0x40L /* ditto */ #define BLKEMPTY 0x80L /* SET IF BLOCK EMPTY */ #define BLKLOOP 0x100L /* block is a loop head */ #define BLKCCLIVE 0x200L /* condition code set on entry to */ /* block (block is second part of */ /* 3-way branch) */ /*#define BLKINNER 0x200L*/ /* loop has no other loops inside */ /* Nowhere used ? */ #define BLKOUTER 0x400L /* set in function header block */ #define BLK0EXIT 0x800L /* no exit (tail procedure call) */ #define BLKP2 0x1000L /* bits used to control backpointer */ #define BLKP3 0x2000L /* bits used to control backpointer */ #define BLKCALL 0x4000L /* block contains a proc call */ #define BLK2CALL 0x8000L /* block contains 2 proc calls */ #define BLKSETJMP 0x10000L /* block may call setjmp (groan). */ #define BLKSTACKI 0x100000L /* blkstack is a number not a bindlist*/ #define BLKREXPORTED2 0x200000L #define BLKCCEXPORTED 0x400000L #define BLKREXPORTED 0x800000L /* N.B. Q_MASK values above also used when BLK2EXIT is set (condition) */ /* Also, the following bits are are disjoint from the above but are only */ /* used in 'procflags'. Some of them may later be BLK oriented. */ #define PROC_ARGADDR 0x20000L /* arg address taken */ #define PROC_ARGPUSH 0x40000L /* treat args carefully (see cg.c) */ #define PROC_BIGSTACK 0x80000L /* stack bigger than 256 */ #define PROC_USESADCONS 0x200000L #define PROC_HASMOVC 0x1000000L #define PROC_CASEBRANCH 0x2000000L #define PROC_FPTEMP 0x4000000L /* hack for SPARC. Generalise? */ #define PROC_INLNASM 0x8000000L /* Fn contains inline assembler */ /* Special values to go in blknext_(), getting to be too many... */ #define RetIntLab ((LabelNumber *)-256L) #define RetFloatLab ((LabelNumber *)-252L) #define RetDbleLab ((LabelNumber *)-248L) #define RetVoidLab ((LabelNumber *)-244L) #define RetImplLab ((LabelNumber *)-240L) /* and for use in flowgraph.c - change soon? */ #define RETLAB ((LabelNumber *)-236L) #define NOTALAB ((LabelNumber *)-232L) struct BlockList { BlockList *blklstcdr; BlockHead *blklstcar; }; #define mkBlockList(a,b) ((BlockList *)binder_cons2(a,b)) /* The following is used when a real machine register is required. */ typedef int32 RealRegister; #define RegSort int32 /* the following 3 values ... */ #define INTREG 0x10000000L #define FLTREG 0x20000000L #define DBLREG 0x28000000L #define SENTINELREG 0x30000000L /* for clarity in regalloc */ /* The following mask is used so that cse and regalloc can pack a */ /* RegSort value and a small integer into an int32. */ /* Maybe neither of these are very essential anymore. */ #define REGSORTMASK (~0x07ffffff) /* for pack/unpack of RegSort & int */ #ifdef ADDRESS_REG_STUFF #define ADDRREG 0x18000000L #define isintregtype_(rsort) ((rsort) == INTREG || (rsort) == ADDRREG) #else #define ADDRREG INTREG #define isintregtype_(rsort) ((rsort) == INTREG) #endif #define regbit(n) (((unsigned32)1L)<<(n)) #define reglist(first,nregs) (regbit((first)+(nregs))-regbit(first)) /* the next lines are horrid, but less so that the previous magic numbers */ /* - they test for virtual regs having become real - see flowgraph.c */ /* Their uses ought to be examined and rationalised. */ #define isany_realreg_(r) ((unsigned32)((r)) < (unsigned32)NMAGICREGS) #ifdef TARGET_SHARES_INTEGER_AND_FP_REGISTERS # if sizeof_double == 4 # define is_physical_double_reg_(r) 0 #else # define is_physical_double_reg_(r) \ (xxregtype_(r)==DBLREG && isany_realreg_(r)) # endif #endif #define V_resultreg(rsort) (isintregtype_(rsort) ? R_A1result : R_FA1result) /* The following line allows for the possibility of the function result */ /* register being different in caller and callee (e.g. register windows). */ #define V_Presultreg(rsort) (isintregtype_(rsort) ? R_P1result : R_FP1result) /* 'GAP' is a non-value of type VRegnum. The bit pattern is chosen so */ /* that it invalidates any packing with REGSORTMASK above, and often */ /* causes a memory trap if used as an index (hence better than -1). */ /* It is also specified in a way that is 64-bit-long friendly. */ #define GAP ((VRegnum)(~0x000fffffL)) typedef struct RegList { struct RegList *rlcdr; /* VRegnum */ IPtr rlcar; } RegList; #define mkRegList(a,b) ((RegList *)binder_icons2(a,b)) #define RegList_Member(a,l) (generic_member((IPtr)(a), (List *)(l))) #define RegList_DiscardOne(p) ((RegList *)discard2(p)) #define RegList_NDelete(a,p) ((RegList *)generic_ndelete((IPtr)(a), (List *)(p))) /* Structure for an abstract instruction (3-address code) */ typedef union VRegInt { /* VRegnum */ IPtr r; /* RealRegister */ IPtr rr; /* int32 */ IPtr i; char const *str; StringSegList *s; LabelNumber *l; LabelNumber **lnn; Binder *b; Expr *ex; /* Binder, when we want to view it as an Expr */ FloatCon *f; BindList *bl; Symstr *sym; Int64Con *i64; void *p; /* should only be used for debugger support */ } VRegInt; struct Icode { /* * The jopcode field here really contains a J_OPCODE plus contition bits * (Q_MASK), see jopcode.h. Maybe there should be packed in using bitfields * rather than the unchecked arithmetic coding currently used? This is not * the highest priority clean-up for me to worry about */ uint32 op, flags; VRegInt r1, r2, r3, r4; }; #define INIT_IC(ic,o) {(ic).op=(o);(ic).flags=0;(ic).r1.r=(ic).r2.r=(ic).r3.r=GAP;(ic).r4.r=0;} #define INIT_IC3(ic,o,R1,R2,R3) {(ic).op=(o);(ic).flags=0;(ic).r1=(R1);(ic).r2=(R2);(ic).r3=(R3);(ic).r4.r=0;} #define INIT_IC4(ic,o,R1,R2,R3,R4) {(ic).op=(o);(ic).flags=0;(ic).r1=(R1);(ic).r2=(R2);(ic).r3=(R3);(ic).r4.r=(R4);} #endif /* end of mip/cgdefs.h */
stardot/ncc
mip/sixchar.h
/* * C compiler file sixchar.h, version 3 * Copyright (C) Codemist Ltd., 1989 * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ /* The definitions that follow are to map long and meaningful (?) names */ /* onto ones that are distinct in the first 6 characters (monocase) so */ /* that machines with truly archaic linkers can still cope... */ /* It is not necessary that the names just have six chars. */ #ifndef _sixchar_h #define _sixchar_h 1 /* * To rebuild this list and avoid unnecessary entries: * Build a compiler with the following extra stuff in "options.h", * or with "target.h" adjusted if a linker limit is already in force: * * #define'ing POLICE_THE_SIX_CHAR_NAME_LIMIT will cause mip/defaults.h to * arrange this for you. * * #define TARGET_HAS_LINKER_NAME_LIMIT 1 * # define LINKER_NAME_MAX 6 * # define LINKER_NAME_MONOCASE 1 * #include "sixchar.h" * * Alter "sixchar.h" to remove any definitions not known to be needed, * indeed comment it ALL out as a start. * Then compile the entire compiler, collecting all the error messages * that come out moaning about linker name clashes. Consolidate and sort * same to produce definitions as seen below, and make into the new * "sixchar.h". * The names documented here relate to the ARM and the s370 targetted * versions of the compiler - extra things may need including to cope * with long names in "asm.c" and "gen.c". */ #define alloc_dispose G001_alloc_dispose #define alloc_init G002_alloc_init #define alloc_noteaestoreuse G003_alloc_noteaestoreuse #define alloc_reinit G004_alloc_reinit #define alloc_unmark G005_alloc_unmark #define builtin_init G006_builtin_init #define cautious_mcrepofexpr G007_cautious_mcrepofexpr #define cautious_mcrepoftype G008_cautious_mcrepoftype #define cc_err G009_cc_err #define cc_err_l G010_cc_err_l #define cc_fatalerr G011_cc_fatalerr #define cc_fatalerr_l G012_cc_fatalerr_l #define cc_rerr G013_cc_rerr #define cc_rerr_l G014_cc_rerr_l #define cc_warn G015_cc_warn #define cc_warn_l G016_cc_warn_l #define codebuf_init G017_codebuf_init #define codebuf_reinit G018_codebuf_reinit #define codebuf_reinit2 G019_codebuf_reinit2 #define codeseg_flush G020_codeseg_flush #define codeseg_function_name G021_codeseg_function_name #define codeseg_stringsegs G022_codeseg_stringsegs #define codesegment G023_codesegment #define compile_abort G024_compile_abort #define config G025_config #define config_init G026_config_init #define current_env G027_current_env #define currentfunction G028_currentfunction #define discard2 G031_discard2 #define discard3 G032_discard3 #define driver_abort G033_driver_abort #define emitfl G034_emitfl #define emitfloat G035_emitfloat #define emitsetsp G036_emitsetsp #define emitsetspandjump G037_emitsetspandjump #define fc_two G038_fc_two #define fc_two_31 G039_fc_two_31 #define flowgraph_reinit G040_flowgraph_reinit #define flt_dtoi G041_flt_dtoi #define flt_dtou G042_flt_dtou #define fltrep_narrow G043_fltrep_narrow #define fltrep_narrow_round G044_fltrep_narrow_round #define fltrep_stod G045_fltrep_stod #define fltrep_widen G046_fltrep_widen #define fname_parse G047_fname_parse #define fname_set_try_order G048_fname_set_try_order #define fname_unparse G049_fname_unparse #define global_mk_binder G050_global_mk_binder #define global_mk_tagbinder G051_global_mk_tagbinder #define globalize_int G052_globalize_int #define globalize_typeexpr G053_globalize_typeexpr #define globalloc G054_globalloc #define implicit_decl G055_implicit_decl #define implicit_return_ok G056_implicit_return_ok #define jopprint_opname G057_jopprint_opname #define label_define G058_label_define #define label_reference G059_label_reference #define label_resolve G060_label_resolve #define lit_findadcon G063_lit_findadcon #define lit_findstringincurpool G064_lit_findstringincurpool #define lit_findstringinprevpools G065_lit_findstringinprevpools #define lit_findword G066_lit_findword #define lit_findwordsincurpool G067_lit_findwordsincurpool #define lit_findwordsinprevpools G068_lit_findwordsinprevpools #define local_address G069_local_address #define local_base G070_local_base #define loopopt_reinit G071_loopopt_reinit #define mcdep_config_option G072_mcdep_config_option #define mcdep_init G073_mcdep_init #define mk_cmd_0 G074_mk_cmd_0 #define mk_cmd_block G075_mk_cmd_block #define mk_cmd_case G076_mk_cmd_case #define mk_cmd_default G077_mk_cmd_default #define mk_cmd_do G078_mk_cmd_do #define mk_cmd_e G079_mk_cmd_e #define mk_cmd_for G080_mk_cmd_for #define mk_cmd_if G081_mk_cmd_if #define mk_cmd_lab G082_mk_cmd_lab #define mk_cmd_switch G083_mk_cmd_switch #define mk_expr1 G084_mk_expr1 #define mk_expr2 G085_mk_expr2 #define mk_expr3 G086_mk_expr3 #define mk_exprbdot G087_mk_exprbdot #define mk_exprlet G088_mk_exprlet #define mk_exprwdot G089_mk_exprwdot #define nextsym G090_nextsym #define nextsym_for_hashif G091_nextsym_for_hashif #define obj_codewrite G092_obj_codewrite #define obj_common_end G093_obj_common_end #define obj_common_start G094_obj_common_start #define obj_symlist G095_obj_symlist #define obj_symref G096_obj_symref #define pp_cis G097_pp_cis #define pp_cisname G098_pp_cisname #define pp_inclclose G099_pp_inclclose #define pp_inclopen G100_pp_inclopen #define pp_predefine G101_pp_predefine #define pp_preundefine G102_pp_preundefine #define print_jopcode G103_print_jopcode #define print_xjopcode G104_print_xjopcode #define regalloc_init G105_regalloc_init #define regalloc_reinit G106_regalloc_reinit #define regalloc_tidy G107_regalloc_tidy #define relation_add G108_relation_add #define relation_delete G109_relation_delete #define relation_init G110_relation_init #define relation_map G111_relation_map #define relation_mapanddelete G112_relation_mapanddelete #define relation_member G113_relation_member #define show_code G114_show_code #define show_code_summary G115_show_code_summary #define sym_insert G116_sym_insert #define sym_insert_id G117_sym_insert_id #define syserr G118_syserr #define syserr_behaviour G119_syserr_behaviour #define vregset_compare G120_vregset_compare #define vregset_copy G121_vregset_copy #define vregset_delete G122_vregset_delete #define vregset_difference G123_vregset_difference #define vregset_discard G124_vregset_discard #define vregset_init G125_vregset_init #define vregset_insert G126_vregset_insert #define vregset_intersection G127_vregset_intersection #define vregset_map G128_vregset_map #define vregset_member G129_vregset_member #define vregset_union G130_vregset_union #define xbinder_list2 G131_xbinder_list2 #define xbinder_list3 G132_xbinder_list3 #define xglobal_cons2 G133_xglobal_cons2 #define xglobal_list3 G134_xglobal_list3 #define xglobal_list4 G135_xglobal_list4 #define xglobal_list6 G136_xglobal_list6 #define xsyn_list2 G137_xsyn_list2 #define xsyn_list3 G138_xsyn_list3 #define xsyn_list4 G139_xsyn_list4 #define xsyn_list5 G140_xsyn_list5 #define xsyn_list6 G141_xsyn_list6 #define xsyn_list7 G142_xsyn_list7 #define outcodewordaux G144_outcodewordaux #define cc_ansi_warn G145_cc_ansi_warn #define cse_print_node G146_cse_print_node #define cse_print_loc G147_cse_print_loc #define cse_printexits G148_cse_printexits #define localcg_tidy G149_localcg_tidy #define localcg_reinit G150_localcg_reinit #define instate_declaration G151_instate_declaration #define instate_alias G152_instate_alias #define issimplelvalue G153_issimplelvalue #define issimplevalue G154_issimplevalue #define emitcallreg G155_emitcallreg #define emitsetspgoto G156_emitsetspgoto #define codebuf_tidy G157_codebuf_tidy #endif /* end of sixchar.h */
stardot/ncc
armthumb/dwasd.c
/* * C compiler file arm/dwasd.c * Copyright: (C) 1995, Advanced RISC Machines Limited. All rights reserved. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ /* Runtime switch between ASD and DWARF format debug table generation */ #include <string.h> #include "globals.h" #include "mcdep.h" #include "mcdpriv.h" #include "defs.h" #ifdef TARGET_HAS_MULTIPLE_DEBUG_FORMATS char dbg_name[] = "ASD or DWARF"; int usrdbgmask; int32 asd_tableindex(int32 dt_number); void *asd_notefileline(FileLine fl); void asd_addcodep(void *debaddr, int32 codeaddr); bool asd_scope(BindListList *, BindListList *); void asd_topvar(Symstr *name, int32 addr, TypeExpr *t, int stgclass, FileLine fl); void asd_type(Symstr *name, TypeExpr *t, FileLine fl); void asd_proc(Binder *b, TagBinder *parent, bool ext, FileLine fl); void asd_locvar(Binder *name, FileLine fl); void asd_locvar1(Binder *name); /* used by F77 front-end */ void asd_commblock(Binder *name, SynBindList *members, FileLine fl); void asd_enterproc(void); void asd_bodyproc(void); void asd_return(int32 addr); void asd_xendproc(FileLine fl); void asd_define(char const *name, bool objectmacro, char const *body, dbg_ArgList const *args, FileLine fl); void asd_undef(char const *name, FileLine fl); void asd_include(char const *filename, char const *path, FileLine fl); void asd_notepath(char const *pathname); void asd_init(void); void asd_setformat(char const *); bool asd_needsframepointer(void); void asd_finalise(void); void asd_final_src_codeaddr(int32, int32); #ifdef TARGET_HAS_FP_OFFSET_TABLES void asd_notefpdesc(ProcFPDesc const *fpd); #endif bool asd_debugareaexists(char const *name); void asd_writedebug(void); int32 dwarf_tableindex(int32 dt_number); void *dwarf_notefileline(FileLine fl); void dwarf_addcodep(void *debaddr, int32 codeaddr); bool dwarf_scope(BindListList *, BindListList *); void dwarf_topvar(Symstr *name, int32 addr, TypeExpr *t, int stgclass, FileLine fl); void dwarf_type(Symstr *name, TypeExpr *t, FileLine fl); void dwarf_proc(Binder *b, TagBinder *parent, bool ext, FileLine fl); void dwarf_locvar(Binder *name, FileLine fl); void dwarf_locvar1(Binder *name); /* used by F77 front-end */ void dwarf_commblock(Binder *name, SynBindList *members, FileLine fl); void dwarf_enterproc(void); void dwarf_bodyproc(void); void dwarf_return(int32 addr); void dwarf_xendproc(FileLine fl); void dwarf_define(char const *name, bool objectmacro, char const *body, dbg_ArgList const *args, FileLine fl); void dwarf_undef(char const *name, FileLine fl); void dwarf_include(char const *filename, char const *path, FileLine fl); void dwarf_notepath(char const *pathname); void dwarf_init(void); void dwarf_setformat(char const *); bool dwarf_needsframepointer(void); void dwarf_finalise(void); void dwarf_final_src_codeaddr(int32, int32); #ifdef TARGET_HAS_FP_OFFSET_TABLES void dwarf_notefpdesc(ProcFPDesc const *fpd); #endif bool dwarf_debugareaexists(char const *name); void dwarf_writedebug(void); typedef struct { int32 (*tableindex)(int32); void *(*notefileline)(FileLine); void (*addcodep)(void *, int32); bool (*scope)(BindListList *, BindListList *); void (*topvar)(Symstr *, int32, TypeExpr *, int, FileLine); void (*type)(Symstr *, TypeExpr *, FileLine); void (*proc)(Binder *, TagBinder *, bool, FileLine); void (*locvar)(Binder *, FileLine); void (*locvar1)(Binder *); /* used by F77 front-end */ void (*commblock)(Binder *, SynBindList *, FileLine); void (*enterproc)(void); void (*bodyproc)(void); void (*returnp)(int32); void (*xendproc)(FileLine); void (*define)(char const *, bool, char const *, dbg_ArgList const *, FileLine); void (*undef)(char const *, FileLine); void (*include)(char const *, char const *, FileLine); void (*notepath)(char const *); void (*init)(void); void (*setformat)(char const *); void (*finalise)(void); void (*final_src_codeaddr)(int32, int32); #ifdef TARGET_HAS_FP_OFFSET_TABLES void (*notefpdesc)(ProcFPDesc const *); #endif bool (*debugareaexists)(char const *); void (*writedebug)(void); bool (*needsframepointer)(void); } Dbg_Procs; static Dbg_Procs const asd_procs = { asd_tableindex, asd_notefileline, asd_addcodep, asd_scope, asd_topvar, asd_type, asd_proc, asd_locvar, asd_locvar1, asd_commblock, asd_enterproc, asd_bodyproc, asd_return, asd_xendproc, asd_define, asd_undef, asd_include, asd_notepath, asd_init, asd_setformat, asd_finalise, asd_final_src_codeaddr, #ifdef TARGET_HAS_FP_OFFSET_TABLES asd_notefpdesc, #endif asd_debugareaexists, asd_writedebug, asd_needsframepointer }; static Dbg_Procs const dwarf_procs = { dwarf_tableindex, dwarf_notefileline, dwarf_addcodep, dwarf_scope, dwarf_topvar, dwarf_type, dwarf_proc, dwarf_locvar, dwarf_locvar1, dwarf_commblock, dwarf_enterproc, dwarf_bodyproc, dwarf_return, dwarf_xendproc, dwarf_define, dwarf_undef, dwarf_include, dwarf_notepath, dwarf_init, dwarf_setformat, dwarf_finalise, dwarf_final_src_codeaddr, #ifdef TARGET_HAS_FP_OFFSET_TABLES dwarf_notefpdesc, #endif dwarf_debugareaexists, dwarf_writedebug, dwarf_needsframepointer }; static Dbg_Procs const *procs; int32 dbg_tableindex(int32 dt_number) { return procs->tableindex(dt_number); } void *dbg_notefileline(FileLine fl) { return procs->notefileline(fl); } void dbg_addcodep(void *debaddr, int32 codeaddr) { procs->addcodep(debaddr, codeaddr); } bool dbg_scope(BindListList *newbl, BindListList *oldbl) { return procs->scope(newbl, oldbl); } void dbg_topvar(Symstr *name, int32 addr, TypeExpr *t, int stgclass, FileLine fl) { procs->topvar(name, addr, t, stgclass, fl); } void dbg_type(Symstr *name, TypeExpr *t, FileLine fl) { procs->type(name, t, fl); } void dbg_proc(Binder *b, TagBinder *parent, bool ext, FileLine fl) { procs->proc(b, parent, ext, fl); } void dbg_locvar(Binder *name, FileLine fl) { procs->locvar(name, fl); } void dbg_locvar1(Binder *name) { procs->locvar1(name); } void dbg_commblock(Binder *name, SynBindList *members, FileLine fl) { procs->commblock(name, members, fl); } void dbg_enterproc(void) { procs->enterproc(); } void dbg_bodyproc(void) { procs->bodyproc(); } void dbg_return(int32 addr) { procs->returnp(addr); } void dbg_xendproc(FileLine fl) { procs->xendproc(fl); } void dbg_define(char const *name, bool objectmacro, char const *body, dbg_ArgList const *args, FileLine fl) { procs->define(name, objectmacro, body, args, fl); } void dbg_undef(char const *name, FileLine fl) { procs->undef(name, fl); } void dbg_include(char const *filename, char const *path, FileLine fl) { procs->include(filename, path, fl); } void dbg_notepath(char const *pathname) { procs->notepath(pathname); } void dbg_init(void) { procs->init(); } void dbg_finalise(void) { procs->finalise(); } void dbg_final_src_codeaddr(int32 a, int32 b) { procs->final_src_codeaddr(a, b); } #ifdef TARGET_HAS_FP_OFFSET_TABLES void obj_notefpdesc(ProcFPDesc const *fpd) { procs->notefpdesc(fpd); } #endif bool dbg_debugareaexists(char const *name) { return procs->debugareaexists(name); } void dbg_writedebug(void) { procs->writedebug(); } bool dbg_needsframepointer() { return procs->needsframepointer(); } void dbg_setformat(char const *form) { if (StrnEq(form, "=-dwarf", 7)) { procs = &dwarf_procs; procs->setformat(&form[7]); } else { procs = &asd_procs; procs->setformat(&form[5]); } } #endif /* TARGET_HAS_MULTIPLE_DEBUG_FORMATS */
stardot/ncc
mip/inline.c
/* * inline.c: inline function expansion * Copyright (C) Advanced Risc Machines Ltd., 1993 * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ /* Nasties to tidy up: ** (1) the use of h0_(Binder) ** (2) lab_xname_()/lab_name_(). Use small ints everywhere for labelnumbers? */ #include <string.h> #include <stddef.h> /* offsetof */ #include "globals.h" #include "store.h" #include "flowgraf.h" #include "codebuf.h" #include "regalloc.h" #include "aeops.h" #include "aetree.h" #include "bind.h" #include "jopcode.h" #include "inline.h" #include "cg.h" #include "regsets.h" #include "simplify.h" #include "errors.h" #include "builtin.h" #include "sem.h" #include "dump.h" #include "mcdep.h" typedef struct SavedFnList SavedFnList; typedef union { RegSort rs; VRegnum r; } Inline_VRegIndex; typedef struct { Inline_ArgBinderList abl; int flags; uint8 accesssize, /* a MEM_xx value or MEM_NONE */ accessmap; int32 mink, maxk; Inline_ArgSubstList *argsubst; } Inline_ArgDesc; #define argdesc_(p) (*(Inline_ArgDesc **)&(p)->fn.args) #define adcdr_(p) (*(Inline_ArgDesc **)&cdr_(&(p)->abl)) #define IA_Updated 1 #define IA_OddAccess 2 #define IA_AccessSet 4 #define IA_UpdatedOutsideCore 8 #define IA_OddUseForPlusInCore 16 typedef uint8 BlockMap; typedef enum { IS_Ord, IS_Ctor, IS_Dtor } Inline_Sort; struct SavedFnList { SavedFnList *cdr; Inline_SavedFn fn; int32 maxlabel; VRegnum maxreg; Inline_VRegIndex *vregtypetab; Inline_Sort sort; union { BlockMap *ctor; BlockHead *dtor; } a; uint8 outoflineflags; }; #define ol_used 1 #define ol_emitted 2 typedef struct BindListIndex BindListIndex; struct BindListIndex { BindListIndex *cdr; BindList *orig; BindList *copy; }; typedef struct SymTrans SymTrans; struct SymTrans { SymTrans *cdr; Symstr *oldsym; Symstr *newsym; }; typedef struct { SynBindList *copied; BindListIndex *sharedbindlists; Inline_VRegIndex *vregindex; BindList *nullenv; SymTrans *symtrans; } SaveFnState; static SavedFnList *saved_fns; Inline_SavedFn *Inline_FindFn(Binder *b) { SavedFnList *fn = (SavedFnList *)bindinline_(b); if (fn != NULL) return &fn->fn; return NULL; } void Inline_RealUse(Binder *b) { SavedFnList *fn = (SavedFnList *)bindinline_(b); attributes_(b) |= A_REALUSE; if (fn != NULL) fn->outoflineflags |= ol_used; } static BindList *GlobalSharedBindListCopy(SaveFnState *st, BindList *bl); static Binder *GlobalBinderCopy(SaveFnState *st, Binder *b) { if (h0_(b) != s_binder) return (Binder *)(IPtr)h0_(b); { Symstr *sym = bindsym_(b); Binder *bnew; size_t n; if (bindstg_(b) & (bitofstg_(s_virtual)|b_globalregvar|bitofstg_(s_auto))) n = sizeof(Binder); else { if (attributes_(b) & A_GLOBALSTORE) return b; n = SIZEOF_NONAUTO_BINDER; } if (isgensym(sym)) { SymTrans *p = st->symtrans; for (; p != NULL; p = cdr_(p)) if (p->oldsym == sym) break; if (p == NULL) { p = NewSyn(SymTrans); cdr_(p) = st->symtrans; st->symtrans = p; p->oldsym = sym; p->newsym = gensymvalwithname(YES, symname_(sym)); } sym = p->newsym; } bnew = global_mk_binder(NULL, sym, bindstg_(b), bindtype_(b)); memcpy(bnew, b, n); bindsym_(bnew) = sym; h0_(b) = (AEop)(IPtr)bnew; st->copied = mkSynBindList(st->copied, b); if (bindstg_(b) & b_bindaddrlist) bindbl_(bnew) = GlobalSharedBindListCopy(st, bindbl_(b)); return bnew; } } static BindList *GlobalBindListCopy(SaveFnState *st, BindList *bl) { BindList *bl_new = NULL; BindList *bp, **bpp = &bl_new; Binder *prevb = NULL; for (; bl != NULL; bl = bl->bindlistcdr, bpp = &bp->bindlistcdr) { Binder *b = GlobalBinderCopy(st, bl->bindlistcar); if (prevb) bindcdr_(prevb) = b; prevb = b; bp = (BindList *)global_cons2(SU_Inline, NULL, b); *bpp = bp; } return bl_new; } static BindList *GlobalSharedBindListCopy(SaveFnState *st, BindList *bl) { BindListIndex *p = st->sharedbindlists; if (bl == NULL) return NULL; for (; p != NULL; p = cdr_(p)) if (bl == p->orig) return p->copy; { BindList *bl_new = (BindList *)global_cons2(SU_Inline, GlobalSharedBindListCopy(st, bl->bindlistcdr), GlobalBinderCopy(st, bl->bindlistcar)); st->sharedbindlists = (BindListIndex *)syn_list3(st->sharedbindlists, bl, bl_new); return bl_new; } } static Inline_ArgDesc *ArgDesc_Find(Binder *b, Inline_ArgDesc *ad) { for (; ad != NULL; ad = adcdr_(ad)) if (ad->abl.narrowtype != NULL) { if (b == ad->abl.globnarrowarg) break; } else if (b == ad->abl.globarg) break; return ad; } static bool IsSTRWExpansion(Icode *ic, int32 *offset) { /* Already checked that ic->op is STRBK */ Icode *ic2 = ic+1, *ic3 = ic+2; if ((ic2->op & J_TABLE_BITS) == J_SHRK && ic2->r3.i == 8 && ic->r1.r == ic2->r2.r && (ic3->op & J_TABLE_BITS) == J_STRBK && ic3->r2.r == ic->r2.r && ic3->r1.r == ic2->r1.r && (target_lsbytefirst ? ic3->r3.i == ic->r3.i+1 : ic3->r3.i+1 == ic->r3.i)) { *offset = target_lsbytefirst ? ic->r3.i : ic->r3.i-1; return YES; } return NO; } #define MapSize(n) ((size_t)(((n) + 7) / 8)) static BlockMap *NewTempMap(unsigned32 n) { size_t size = MapSize(n); BlockMap *map = NewSynN(BlockMap, size); memset(map, 0, size); return map; } static BlockMap *NewBlockMap(unsigned32 n) { size_t size = MapSize(n); BlockMap *map = NewGlobN(BlockMap, SU_Inline, size); memset(map, 0, size); return map; } static bool MapBitSet(BlockMap *map, unsigned32 n) { BlockMap *p = &map[n / 8]; unsigned bit = 1 << (n % 8); return ((*p & bit) != 0); } static bool SetMapBit(BlockMap *map, unsigned32 n) { BlockMap *p = &map[n / 8]; unsigned bit = 1 << (n % 8); if ((*p & bit) == 0) { *p |= bit; return YES; } else return NO; } static void ClearMapBit(BlockMap *map, unsigned32 n) { BlockMap *p = &map[n / 8]; unsigned bit = 1 << (n % 8); *p &= ~bit; } static void AddToMap(BlockMap *map, LabelNumber *lab) { if (!is_exit_label(lab)) { BlockHead *b = lab->block; if (SetMapBit(map, lab_name_(lab))) { if (blkflags_(b) & BLKSWITCH) { int32 n = blktabsize_(b); LabelNumber **table = blktable_(b); while (--n >= 0) AddToMap(map, table[n]); } else { if (blkflags_(b) & BLK2EXIT) AddToMap(map, blknext1_(b)); AddToMap(map, blknext_(b)); } } } } /* The compiler prepends code to call new() to constructors, and postpends * code to call delete() to destructors. When called for objects which don't * need allocation/deallocation, this gives rise to dead code which latter * phases of compilation are capable of removing, but at a cost (the increased * number of basic blocks slows down both cse and regalloc). Also, the code * to call new() assigns to __this, preventing it from being substituted when * the constructor is inlined, and therefore (perhaps spuriously) leaving the * constructed object marked as address-taken. */ static void FindStructorCore(SavedFnList *p) { BlockHead *b = blkdown_(top_block); BindList *argbl = currentfunction.argbindlist; Binder *arg1 = argbl == NULL ? NULL : argbl->bindlistcar; p->sort = IS_Ord; if ((blkflags_(b) & BLK2EXIT) && blklength_(b) == 2) { Icode *ic1 = blkcode_(b), *ic2 = ic1 + 1; if (ic1->op == J_LDRV+J_ALIGN4 && ic1->r3.b == arg1 && (ic2->op & ~Q_MASK) == J_CMPK && Q_issame((ic2->op & Q_MASK), Q_NE) && ic2->r3.i == 0 && ic2->r2.r == ic1->r1.r) { BlockMap *map = NewBlockMap(p->maxlabel); SetMapBit(map, lab_name_(blklab_(top_block))); AddToMap(map, blknext1_(b)); p->a.ctor = map; p->sort = IS_Ctor; } } else { BlockHead *b2 = blkup_(bottom_block); BlockHead *b1 = blkup_(b2); if (b1 != NULL && !(blkflags_(b2) & (BLK2EXIT+BLKSWITCH)) && blknext_(b2) == blklab_(bottom_block) && (blkflags_(b1) & BLK2EXIT) && Q_issame(blkflags_(b1) & Q_MASK, Q_EQ) && blknext_(b1) == blklab_(b2) && blknext1_(b1) == blklab_(bottom_block) && argbl != NULL && argbl->bindlistcdr != NULL) { Binder *arg2 = argbl->bindlistcdr->bindlistcar; int32 n = blklength_(b1); if (2 <= n) { Icode const *ic = &blkcode_(b1)[n-2]; if ((ic[1].op & ~Q_MASK) == J_CMPK && ic[1].r3.i == 0 && ic[1].r2.r == ic[0].r1.r) { if (3 <= n && ic[-1].op == J_LDRV+J_ALIGN4 && ic[-1].r3.b == arg2 && ic[0].op == J_ANDK && ic[0].r3.i == 1 && ic[0].r2.r == ic[-1].r1.r) { p->a.dtor = b1; p->sort = IS_Dtor; /* this is tentative: we need to know that arg2 isn't assigned to */ /* before we're certain */ } else if (ic[0].op == J_LDRV+J_ALIGN4 && ic[0].r3.b == arg2) { p->a.dtor = b1; p->sort = IS_Dtor; /* this is tentative: we need to know that arg2 isn't assigned to */ /* before we're certain */ } } } } } } typedef struct ABLList ABLList; struct ABLList { ABLList *cdr; Inline_ArgDesc *arg; }; static Inline_ArgDesc *ABL_Find(ABLList *p, Binder *b) { for (; p != NULL; p = cdr_(p)) if (bindsym_(b) == bindsym_(p->arg->abl.globarg)) return p->arg; return NULL; } static LabelNumber *LabelNo_NoteRef(LabelNumber *l, uint8 *justoneref, uint8 *anyref) { IPtr lno; uint32 mapbit; if (is_exit_label(l)) { lno = (IPtr)l; mapbit = 0; } else { lno = (IPtr)lab_name_(l); mapbit = lno; } if (SetMapBit(anyref, mapbit)) SetMapBit(justoneref, mapbit); else ClearMapBit(justoneref, mapbit); return (LabelNumber *)(IPtr)lno; } bool Inline_Save(Binder *b, BindList *local_binders, BindList *regvar_binders) { SavedFnList *p = NewGlob(SavedFnList, SU_Inline); SaveFnState st; bindinline_(b) = p; p->outoflineflags = (attributes_(b) & A_REALUSE) ? ol_used : 0; st.copied = NULL; st.sharedbindlists = NULL; st.symtrans = NULL; p->fn.fndetails = currentfunction; if (p->fn.fndetails.structresult != NULL) p->fn.fndetails.structresult = GlobalBinderCopy(&st, p->fn.fndetails.structresult); if (p->fn.fndetails.xrflags & xr_defext) Inline_RealUse(b); p->fn.fndetails.argbindlist = GlobalBindListCopy(&st, p->fn.fndetails.argbindlist); p->fn.var_binders = GlobalBindListCopy(&st, local_binders); p->fn.reg_binders = GlobalBindListCopy(&st, regvar_binders); p->fn.top_block = p->fn.bottom_block = NULL; p->fn.firstblockignoresize = 0; p->fn.firstblockignore = NULL; p->fn.ix_narrowspenv = -1; p->maxreg = vregister(INTREG); p->maxlabel = lab_name_(nextlabel()); FindStructorCore(p); { VRegnum n = p->maxreg; Inline_VRegIndex *vt = NewGlobN(Inline_VRegIndex, SU_Inline, p->maxreg); while (--n > NMAGICREGS) vt[n].rs = vregsort(n); p->vregtypetab = vt; } { BindList *bl = p->fn.fndetails.argbindlist; Inline_ArgDesc **adp = &argdesc_(p); FormTypeList *ft = typefnargs_(bindtype_(b)); ABLList *narrowargs = NULL; p->fn.args = NULL; for (; bl != NULL; bl = bl->bindlistcdr) { Inline_ArgDesc *ad = NewGlob(Inline_ArgDesc, SU_Inline); Binder *b = bl->bindlistcar; adcdr_(ad) = NULL; ad->abl.globarg = b; ad->flags = 0; ad->accessmap = 0; *adp = ad; adp = &adcdr_(ad); ad->abl.globnarrowarg = ad->abl.instantiatednarrowarg = NULL; ad->abl.narrowtype = NULL; ad->mink = MaxMemOffset(J_LDRK+J_ALIGN4); ad->maxk = MinMemOffset(J_LDRK+J_ALIGN4); /* ft reflects the declared argument types of the function, bl the types * of arguments actually passed (they will differ in the type of narrow * arguments, and also only bl has an entry for the extra pointer-to-result * argument of structure-returning functions). */ if (!(bl == p->fn.fndetails.argbindlist && p->fn.fndetails.structresult != NULL)) { if (widen_formaltype(ft->fttype) != ft->fttype) { ad->abl.narrowtype = ft->fttype; narrowargs = (ABLList *)syn_list2(narrowargs, ad); } ft = ft->ftcdr; } } if (narrowargs != NULL) { BlockHead *b = blkdown_(top_block); int32 n, len = blklength_(b); Icode *ic = blkcode_(b); uint8 *map = NewBlockMap(2*len); p->fn.firstblockignoresize = 2*len; p->fn.firstblockignore = map; p->fn.ix_max = len; for (n = 0; n < len; ic++, n++) { J_OPCODE op = ic->op & J_TABLE_BITS; if (op == J_SETSPENV && p->fn.ix_narrowspenv == -1) { p->fn.ix_narrowspenv = n; SetMapBit(map, n); } else if (op == J_STRV || op == J_STRDV) { Binder *mb = GlobalBinderCopy(&st, ic->r3.b); Inline_ArgDesc *ad = ABL_Find(narrowargs, mb); if (ad != NULL && ad->abl.globnarrowarg == NULL) { ad->abl.globnarrowarg = mb; SetMapBit(map, len+n); } } else if (op == J_INIT || op == J_INITD) { Binder *mb = GlobalBinderCopy(&st, ic->r3.b); Inline_ArgDesc *ad = ABL_Find(narrowargs, mb); if (ad != NULL && ad->abl.globnarrowarg == NULL) SetMapBit(map, n); } } } } { BlockHead *b = top_block; BlockHead *blast = NULL, *bnew; uint8 *justoneref = NewTempMap(p->maxlabel), *anyref = NewTempMap(p->maxlabel); /* to help determine {first,last}blockmergeable */ for (b = top_block; b != NULL; b = blkdown_(b), blast = bnew) { bnew = NewGlob(BlockHead, SU_Inline); *bnew = *b; blkup_(bnew) = blast; if (blast == NULL) p->fn.top_block = bnew; else blkdown_(blast) = bnew; if (blkflags_(b) & BLKSWITCH) { int32 n = blktabsize_(b); LabelNumber **sw_old = blktable_(b); LabelNumber **sw_new = NewGlobN(LabelNumber *, SU_Inline, n); while (--n >= 0) sw_new[n] = LabelNo_NoteRef(sw_old[n], justoneref, anyref); blktable_(bnew) = sw_new; } else { blknext_(bnew) = LabelNo_NoteRef(blknext_(b), justoneref, anyref); if (blkflags_(b) & BLK2EXIT) blknext1_(bnew) = LabelNo_NoteRef(blknext1_(b), justoneref, anyref); } blklab_(bnew) = (LabelNumber *)(IPtr)lab_name_(blklab_(b)); blkstack_(bnew) = GlobalSharedBindListCopy(&st, blkstack_(b)); { int32 n = blklength_(b), len = n; Icode *code_old = blkcode_(b); Icode *code_new = n == 0 ? (Icode *)DUFF_ADDR : NewGlobN(Icode, SU_Inline, n); bool inctorcore = YES; if (p->sort == IS_Ctor) inctorcore = MapBitSet(p->a.ctor, lab_name_(blklab_(b))); else if (p->sort == IS_Dtor && b == p->a.dtor) p->a.dtor = bnew; blkcode_(bnew) = code_new; while (--n >= 0) { Icode *ic_old = &code_old[n]; Icode *ic_new = &code_new[n]; J_OPCODE op = ic_old->op & J_TABLE_BITS; *ic_new = *ic_old; if (op == J_SETSPENV) { ic_new->r3.bl = GlobalSharedBindListCopy(&st, ic_new->r3.bl); ic_new->r2.bl = GlobalSharedBindListCopy(&st, ic_new->r2.bl); } else if (op == J_SETSPGOTO) { ic_new->r2.bl = GlobalSharedBindListCopy(&st, ic_new->r2.bl); ic_new->r3.l = (LabelNumber *)(IPtr)lab_xname_(ic_new->r3.l); } else if (uses_stack(op) || op == J_CALLK || op==J_ADCON || op == J_INIT || op == J_INITF || op == J_INITD) { Binder *bnew = ic_new->r3.b = GlobalBinderCopy(&st, ic_new->r3.b); Inline_ArgDesc *ad = ArgDesc_Find(bnew, argdesc_(p)); if (ad != NULL) { if (stores_r1(op)) { if (ad->abl.narrowtype == NULL || b != blkdown_(top_block) || !MapBitSet(p->fn.firstblockignore, len+n)) { if (inctorcore) ad->flags |= IA_Updated; else ad->flags |= IA_UpdatedOutsideCore; } } else if (op == J_LDRV) { Icode *next1 = ic_new + 1; if (n+1 < len) { J_OPCODE nextop = next1->op & J_TABLE_BITS; if (j_is_ldr_or_str(nextop) && reads_r2(nextop) && !reads_r3(nextop) && next1->r2.r == ic_new->r1.r) { int32 accesssize; #ifdef TARGET_LACKS_HALFWORD_STORE int32 k; if (nextop == J_STRBK && n+3 < len && IsSTRWExpansion(next1, &k) && k == 0) accesssize = MEM_W; else #endif if (next1->r3.i == 0) { accesssize = j_memsize(nextop); } else accesssize = MEM_NONE; if ((ad->flags & IA_AccessSet) && ad->accesssize != accesssize) accesssize = MEM_NONE; ad->accesssize = accesssize; ad->flags |= IA_AccessSet; ad->accessmap |= (1 << j_memsize(nextop)); if (next1->r3.i < ad->mink) ad->mink = next1->r3.i; if (next1->r3.i > ad->maxk) ad->maxk = next1->r3.i; continue; } else if (nextop == J_MOVR) continue; } if (inctorcore) ad->flags |= IA_OddUseForPlusInCore; } else if (op != J_INIT && op != J_INITF && op != J_INITD) ad->flags |= IA_OddAccess; } } else if (op==J_STRING) ic_new->r3.s = globalize_strseg(ic_new->r3.s); } } } blkdown_(blast) = NULL; p->fn.bottom_block = blast; p->fn.lastblockmergeable = MapBitSet(justoneref, 0) && !(blkflags_(blast) & (BLK2EXIT+BLKSWITCH)) && is_exit_label(blknext_(blast)); p->fn.firstblockmergeable = MapBitSet(justoneref, (IPtr)blklab_(blkdown_(p->fn.top_block))); } { SynBindList *bl = st.copied; for (; bl != NULL; bl = bl->bindlistcdr) h0_(bl->bindlistcar) = s_binder; } if (p->sort == IS_Dtor) { /* retract if the second argument isn't read-only */ Inline_ArgDesc *ad = adcdr_(argdesc_(p)); if (ad->flags & (IA_OddAccess + IA_Updated + IA_UpdatedOutsideCore)) p->sort = IS_Ord; } if (debugging(DEBUG_CG)) { cc_msg("Inline_Save %s", symname_(p->fn.fndetails.symstr)); if (p->sort == IS_Dtor) { cc_msg(": Dtor: %ld\n", (int32)blklab_(p->a.dtor)); } else if (p->sort == IS_Ctor) { int32 i; BlockMap *map = p->a.ctor; int c = '{'; cc_msg(": Ctor: "); for (i = 0; i < p->maxlabel; i++) if (MapBitSet(map, i)) { cc_msg("%c%ld", c, (long)i); c = ' '; } cc_msg("}\n"); } else cc_msg("\n"); } cdr_(p) = saved_fns; saved_fns = p; return YES; } static BindList *FromGlobalSharedBindListCopy(SaveFnState *st, BindList *bl); static Binder *FromGlobalBinderCopy(SaveFnState *st, Binder *b) { if (h0_(b) != s_binder) return (Binder *)(IPtr)h0_(b); { Binder *bnew; size_t n; if (bindstg_(b) & (bitofstg_(s_virtual)|b_globalregvar|bitofstg_(s_auto))) n = sizeof(Binder); else { if (attributes_(b) & A_GLOBALSTORE) return b; n = SIZEOF_NONAUTO_BINDER; } bnew = mk_binder(bindsym_(b), bindstg_(b), bindtype_(b)); memcpy(bnew, b, n); h0_(b) = (AEop)(IPtr)bnew; st->copied = mkSynBindList(st->copied, b); if (bindstg_(b) & bitofstg_(s_auto)) { if (bindstg_(b) & b_bindaddrlist) bindbl_(bnew) = FromGlobalSharedBindListCopy(st, bindbl_(b)); if (bindxx_(b) != GAP) bindxx_(bnew) = st->vregindex[bindxx_(b)].r; } return bnew; } } static BindList *FromGlobalBindListCopy(SaveFnState *st, BindList *bl) { BindList *bl_new = NULL; BindList *bp, **bpp = &bl_new; for (; bl != NULL; bl = bl->bindlistcdr, bpp = &bp->bindlistcdr) { Binder *b = FromGlobalBinderCopy(st, bl->bindlistcar); bp = (BindList *)binder_cons2(NULL, b); *bpp = bp; } return bl_new; } static BindList *FromGlobalSharedBindListCopy(SaveFnState *st, BindList *bl) { BindListIndex *p = st->sharedbindlists; if (bl == NULL) return st->nullenv; for (; p != NULL; p = cdr_(p)) if (bl == p->orig) return p->copy; { BindList *bl_new = (BindList *)binder_cons2( FromGlobalSharedBindListCopy(st, bl->bindlistcdr), FromGlobalBinderCopy(st, bl->bindlistcar)); st->sharedbindlists = (BindListIndex *)syn_list3(st->sharedbindlists, bl, bl_new); return bl_new; } } static LabelNumber *FromGlobalLabel( LabelNumber **index, Inline_RestoreControl *rc, LabelNumber *old) { /* (LabelNumber *) values like 'old' here only hold small ints. */ return !is_exit_label(old) ? index[(IPtr)old] : rc != NULL && rc->exitlabel != NULL ? rc->exitlabel : old; } static BindList *BindListCopy(BindList *bl) { BindList *bl_new = NULL; BindList *bp, **bpp = &bl_new; for (; bl != NULL; bl = bl->bindlistcdr, bpp = &bp->bindlistcdr) { bp = (BindList *)binder_cons2(NULL, bl->bindlistcar); *bpp = bp; } return bl_new; } static SavedFnList *FindSavedFn(Inline_SavedFn *fn) { SavedFnList *p; for (p = saved_fns; p != NULL; p = cdr_(p)) if (fn->fndetails.symstr == p->fn.fndetails.symstr) return p; return NULL; } static bool OverlargeOffset(Inline_ArgDesc const *ad, Expr *ex) { uint8 map = ad->accessmap; int32 k = intval_(arg2_(ex)); int32 mink = k + ad->mink, maxk = k + ad->maxk; int32 align = J_ALIGN4; /* WD: temp hack - will become parameter!! */ if ((map & (1 << MEM_B)) && (mink < MinMemOffset(J_LDRBK+align) || maxk > MaxMemOffset(J_LDRBK+align))) return YES; if ((map & (1 << MEM_W)) && (mink < MinMemOffset(J_LDRWK+align) || maxk > MaxMemOffset(J_LDRWK+align))) return YES; if ((map & (1 << MEM_I)) && (mink < MinMemOffset(J_LDRK+align) || maxk > MaxMemOffset(J_LDRK+align))) return YES; if ((map & (1 << MEM_F)) && (mink < MinMemOffset(J_LDRFK+align) || maxk > MaxMemOffset(J_LDRFK+align))) return YES; if ((map & (1 << MEM_D)) && (mink < MinMemOffset(J_LDRDK+align) || maxk > MaxMemOffset(J_LDRDK+align))) return YES; if ((map & (1 << MEM_LL)) && (mink < MinMemOffset(J_LDRLK+align) || maxk > MaxMemOffset(J_LDRLK+align))) return YES; return NO; } static void ResultRename_fixdef(VRegnum r, Inline_RestoreControl *rc, int32 *mask) /* Renames a fixed (non-renamable) result register in the newresultregs */ { int i; for (i = 0; i < rc->nresults; i++) if (((1 << i) & *mask) && rc->resultregs[i] == r) { rc->newresultregs[i] = r; *mask &= ~(1 << i); } } static void ResultRename_def(VRegnum *r, Inline_RestoreControl *rc, int32 *mask) /* Renames a result register to newresultregs */ { int i; for (i = 0; i < rc->nresults; i++) if (((1 << i) & *mask) && rc->resultregs[i] == *r) { if (rc->newresultregs[i] != GAP) *r = rc->newresultregs[i]; *mask &= ~(1 << i); } } void Inline_Restore(Inline_SavedFn *fn, Inline_RestoreControl *rc) { SaveFnState st; SavedFnList *p = FindSavedFn(fn); Inline_VRegIndex *vt = p->vregtypetab; int32 n = p->maxreg; BindList *argb_orig = fn->fndetails.argbindlist; Inline_ArgDesc *ad; BlockMap *map = NULL; BlockHead *dtorlast = NULL; BlockHead *bottom = p->fn.bottom_block; bool skipblock2 = NO; while (--n >= 0) vt[n].r = n <= NMAGICREGS ? n : vregister(vt[n].rs); st.copied = NULL; st.sharedbindlists = NULL; st.vregindex = p->vregtypetab; if (fn->fndetails.structresult != NULL) fn->fndetails.structresult = FromGlobalBinderCopy(&st, fn->fndetails.structresult); fn->fndetails.argbindlist = FromGlobalBindListCopy(&st, argb_orig); for (ad = argdesc_(p); ad != NULL; ad = adcdr_(ad)) ad->argsubst = NULL; if (rc != NULL) { Inline_ArgSubstList *as = rc->argreplace; BindList **blp = &fn->fndetails.argbindlist; int ia_cantsubst = IA_Updated + IA_OddAccess + IA_UpdatedOutsideCore; for (ad = argdesc_(p); ad != NULL; ad = adcdr_(ad)) { /* Prune from the argument bindlist those arguments which we know can */ /* be substituted for */ BindList *bl = *blp; if (as == NULL) break; if (as->arg == ad->abl.globarg || as->arg == ad->abl.globnarrowarg) { Inline_ArgSubstList *thisas = as; bool subst = YES; as = cdr_(as); if (ad->abl.narrowtype != NULL && ((thisas->sort != T_Int && thisas->sort != T_Binder) || ad->abl.globnarrowarg == NULL)) subst = NO; else if (ad == argdesc_(p) && p->sort == IS_Ctor && !(ad->flags & (IA_Updated + IA_OddAccess))) { if (thisas->notnull) { if (thisas->sort == T_Plus && (OverlargeOffset(ad, thisas->replacement.ex) || (ad->flags & IA_OddUseForPlusInCore))) subst = NO; map = p->a.ctor; ia_cantsubst = IA_Updated + IA_OddAccess; } else { if (thisas->sort == T_Int && intval_(thisas->replacement.ex) == 0) skipblock2 = YES; if (ad->flags & IA_UpdatedOutsideCore) subst = NO; } } else if (p->sort == IS_Dtor && ad == adcdr_(argdesc_(p)) && !(ad->flags & ia_cantsubst) && thisas->sort == T_Int && intval_(thisas->replacement.ex) == 0) dtorlast = p->a.dtor; else if ((thisas->sort == T_Plus && (OverlargeOffset(ad, thisas->replacement.ex) || (ad->flags & IA_OddUseForPlusInCore))) || ad->flags & ia_cantsubst) subst = NO; if (subst) { *blp = bl->bindlistcdr; ad->argsubst = thisas; if (debugging(DEBUG_CG)) { cc_msg("Substitution for %s$b: ", thisas->sort==T_AdconV ? "*" : "", thisas->arg); pr_expr_nl(thisas->replacement.ex); } continue; } thisas->refsleft = YES; } blp = &bl->bindlistcdr; } } if (rc != NULL) { BindList *bl = BindListCopy(fn->fndetails.argbindlist); BindList *argbl = bl; n = length((List *)bl); rc->env = st.nullenv = (BindList *)nconc((List *)bl, (List *)rc->env); for (; --n >= 0; argbl = argbl->bindlistcdr) { Binder *b = argbl->bindlistcar; bindbl_(b) = argbl; bindstg_(b) |= b_bindaddrlist; } } else st.nullenv = NULL; fn->var_binders = FromGlobalBindListCopy(&st, fn->var_binders); fn->reg_binders = FromGlobalBindListCopy(&st, fn->reg_binders); { LabelNumber **labelindex = NewSynN(LabelNumber *, p->maxlabel); BlockHead *b = fn->top_block; BlockHead *globtop = b; BlockHead *blast = NULL, *bnew = NULL; Inline_ArgSubstList *sl; for (n = 1; n < p->maxlabel; n++) labelindex[n] = nextlabel(); fn->top_block = fn->bottom_block = NULL; for (; b != NULL; b = blkdown_(b), blast = bnew) if ( skipblock2 ? b != blkdown_(globtop) : map != NULL ? MapBitSet(map, (IPtr)blklab_(b)) : YES) { int32 restoload = 0; bool resvoided = YES; bnew = NewBind(BlockHead); *bnew = *b; blkup_(bnew) = blast; if (blast == NULL) fn->top_block = bnew; else blkdown_(blast) = bnew; if (blkflags_(b) & BLKSWITCH) { int32 n = blktabsize_(b); LabelNumber **sw_old = blktable_(b); LabelNumber **sw_new = NewBindN(LabelNumber *, n); while (--n >= 0) sw_new[n] = FromGlobalLabel(labelindex, rc, sw_old[n]); blktable_(bnew) = sw_new; } else { BlockHead *b1 = b; if (b == dtorlast) { b1 = bottom; blkflags_(bnew) &= ~BLK2EXIT; } else { if (skipblock2 && blast == NULL) b1 = blkdown_(b); if (blkflags_(b) & BLK2EXIT) blknext1_(bnew) = FromGlobalLabel(labelindex, rc, blknext1_(b)); } if (is_exit_label(blknext_(b1)) && rc != NULL) { restoload = (1L << rc->nresults) - 1; if (rc->nresults > 0 && rc->newresultregs[0] != GAP) resvoided = NO; } blknext_(bnew) = FromGlobalLabel(labelindex, rc, blknext_(b1)); } { LabelNumber *lab = FromGlobalLabel(labelindex, rc, blklab_(b)); blklab_(bnew) = lab; lab->block = bnew; } blkstack_(bnew) = FromGlobalSharedBindListCopy(&st, blkstack_(b)); { int32 n_in = blklength_(b), n_out = n_in, n; Icode *code_old = blkcode_(b); Icode *code_new; bool copied = NO; VRegnum discardload = GAP; int32 noopcount = 0; Inline_ArgDesc *ad; for (n = n_in; --n >= 0; ) { J_OPCODE op = code_old[n].op & J_TABLE_BITS; if (op == J_ADCON) { Binder *b = code_old[n].r3.b; if ((bindstg_(b) & bitofstg_(s_extern)) && !(bindstg_(b) & (b_undef|b_fnconst)) && !(binduses_(b) & (u_bss|u_constdata)) && b != datasegment && bindaddr_(b) != 0) { n_out++; } } } if (b == dtorlast) { n_out = n_out - 2 + blklength_(bottom); n_in = blklength_(bottom); code_old = blkcode_(bottom); } code_new = n_out == 0 ? (Icode *)DUFF_ADDR : NewBindN(Icode, n_out); blkcode_(bnew) = code_new; blklength_(bnew) = n_out; for (n = n_out; --n, --n_in >= 0; ) { J_OPCODE op = code_old[n_in].op; uint32 flags = code_old[n_in].flags; VRegInt r1 = code_old[n_in].r1, r2 = code_old[n_in].r2, r3 = code_old[n_in].r3, r4 = code_old[n_in].r4; J_OPCODE opx = op & J_TABLE_BITS; if (uses_r1(op)) r1.r = vt[r1.r].r; if (uses_r2(op)) r2.r = vt[r2.r].r; if (uses_r3(op)) r3.r = vt[r3.r].r; if (uses_r4(op)) r4.r = vt[r4.r].r; if (opx == J_SETSPENV) { if (r3.bl == r2.bl && !copied && rc != NULL) { /* m = r2 only when both are empty, just before function exits (deliberately not optimised out to give somewhere for CSE-introduced binders to be popped). */ n_out--; goto maybeswitchblock; } r3.bl = FromGlobalSharedBindListCopy(&st, r3.bl); r2.bl = FromGlobalSharedBindListCopy(&st, r2.bl); } else if (opx == J_SETSPGOTO) { r2.bl = FromGlobalSharedBindListCopy(&st, r2.bl); r3.l = FromGlobalLabel(labelindex, rc, r3.l); } else if (opx == J_STRV && (ad = ArgDesc_Find(r3.b, argdesc_(p))) != NULL && (sl = ad->argsubst) != NULL && sl->sort == T_Int) { op = J_MOVK; r3.i = intval_(sl->replacement.ex); } else if (opx == J_STRV && (ad = ArgDesc_Find(r3.b, argdesc_(p))) != NULL && (sl = ad->argsubst) != NULL && sl->sort == T_Binder && ad->abl.narrowtype != NULL) { r3.b = sl->replacement.b; } else if (opx == J_LDRV && (ad = ArgDesc_Find(r3.b, argdesc_(p))) != NULL && (sl = ad->argsubst) != NULL) { switch (sl->sort) { default: syserr("Inline_Restore"); break; case T_Binder: r3.b = sl->replacement.b; break; case T_Adcon: r3.b = sl->replacement.b; op = J_ADCON; break; case T_Int: op = J_MOVK, r3.i = intval_(sl->replacement.ex); break; case T_Plus: { Binder *b = exb_(arg1_(sl->replacement.ex)); int32 k = intval_(arg2_(sl->replacement.ex)); Icode *next1 = &code_new[n+1]; J_OPCODE nextop = next1->op & J_TABLE_BITS; if (n+1 < n_out) { if (j_is_ldr_or_str(nextop) && reads_r2(nextop) && !reads_r3(nextop) && next1->r2.r == r1.r) { #ifdef TARGET_LACKS_HALFWORD_STORE int32 k1; if (nextop == J_STRBK && n+3 < n_out && IsSTRWExpansion(next1, &k1)) { code_new[n+3].r3.i += k; } #endif r3.b = b; next1->r3.i += k; break; } else if (nextop == J_MOVR && next1->r3.r == r1.r) { r3.b = b; next1->op = J_ADDK; next1->r2.r = r1.r; next1->r3.i = k; break; } } if (loads_r1(op) && r1.r == discardload) { op = J_NOOP; noopcount++; discardload = GAP; } else r3.b = FromGlobalBinderCopy(&st, r3.b); break; } case T_AdconV: /* Substituting an ADCONV: try to combine it with subsequent */ /* loads and stores (turning them into VK variants) so that */ /* the variable isn't falsely seen to be address-taken. */ { int32 i = n; bool used = NO; r3.b = sl->replacement.b; while (++i < n_out) { Icode *next = &code_new[i]; J_OPCODE nextop = next->op & J_TABLE_BITS; if (j_is_ldr_or_str(nextop) && reads_r2(nextop) && !reads_r3(nextop) && next->r2.r == r1.r) { if (sl->size == MEM_NONE || sl->size != ad->accesssize) { #ifdef TARGET_LACKS_HALFWORD_STORE int32 k; if (nextop == J_STRBK && i+2 < n_out && IsSTRWExpansion(next, &k)) { Icode *next3 = &code_new[i+2]; next3->op = J_addvk(next3->op); next3->r2.i = next3->r3.i; next3->r3.b = r3.b; } #endif next->op = J_addvk(next->op); next->r2.i = next->r3.i; next->r3.b = r3.b; } else { #ifdef TARGET_LACKS_HALFWORD_STORE int32 k; if (nextop == J_STRBK && i+2 < n_out && IsSTRWExpansion(next, &k) && k == 0) { (next+1)->op = J_NOOP; (next+2)->op = J_NOOP; noopcount += 2; next->op = J_STRV+J_ALIGN4; next->r2.r = GAP; next->r3.b = r3.b; } else #endif if (nextop == J_LDRBK || nextop == J_LDRWK) { next->op = J_LDRV+J_ALIGN4; next->r2.r = GAP; next->r3.b = r3.b; } else if (nextop == J_STRWK || nextop == J_STRBK) { next->op = J_STRV+J_ALIGN4; next->r2.r = GAP; next->r3.b = r3.b; } else { next->op = J_addvk(next->op); next->r2.i = next->r3.i; next->r3.b = r3.b; } } } else if (reads_r1(nextop) && next->r1.r == r1.r || reads_r2(nextop) && next->r2.r == r1.r || reads_r3(nextop) && next->r3.r == r1.r || reads_r4(nextop) && next->r4.r == r1.r) used = YES; } if (used) op = J_ADCONV; else { op = J_NOOP; noopcount++; } } break; } } else if (opx == J_ADCON) { r3.b = FromGlobalBinderCopy(&st, r3.b); if ((bindstg_(r3.b) & bitofstg_(s_extern)) && !(bindstg_(r3.b) & (b_undef|b_fnconst)) && !(binduses_(r3.b) & (u_bss|u_constdata)) && r3.b != datasegment) { if (bindaddr_(r3.b) != 0) { INIT_IC(code_new[n], J_ADDK); code_new[n].r1 = r1; code_new[n].r2 = r1; code_new[n].r3.i = bindaddr_(r3.b); code_new[n].r4.r = GAP; n--; } r3.b = datasegment; } } else if (uses_stack(op) || opx == J_CALLK || opx == J_INIT || opx == J_INITF || opx == J_INITD) r3.b = FromGlobalBinderCopy(&st, r3.b); if (loads_r1(op)) { if (restoload != 0) { int i; if (isproccall_(op)) { restoload = 0; for (i = 0; i < rc->nresults; i++) rc->newresultregs[i] = rc->resultregs[i]; } else for (i = 0; i < rc->nresults; i++) if (r1.r == rc->resultregs[i]) { restoload &= ~regbit(i); if (!resvoided) { r1.r = rc->newresultregs[i]; blkflags_(b) |= BLKREXPORTED; } else { if (op == J_MOVR) discardload = r3.r; op = J_NOOP; noopcount++; } break; } } else if (r1.r == discardload) { if (!isproccall_(op)) { op = J_NOOP; noopcount++; } discardload = GAP; } } else if (uses_r1(op) && r1.r == discardload) discardload = GAP; copied = YES; INIT_IC(code_new[n], op); code_new[n].flags = flags; code_new[n].r1 = r1; code_new[n].r2 = r2; code_new[n].r3 = r3; code_new[n].r4 = r4; /* WD: quick HACK for the above code - broken for inline assembler */ /* does not discard moves (discardload), or voids results (resvoided) there doesn't seem to be any point in doing that anyway... */ if (rc != NULL) { RealRegUse use; int i; if (!isproccall_(op)) { if (updates_r1(op)) ResultRename_fixdef(code_new[n].r1.r, rc, &restoload); else if (loads_r1(op)) ResultRename_def(&code_new[n].r1.r, rc, &restoload); if (updates_r2(op)) ResultRename_fixdef(code_new[n].r2.r, rc, &restoload); else if (loads_r2(op)) ResultRename_def(&code_new[n].r2.r, rc, &restoload); } RealRegisterUse(&code_new[n], &use); for (i = 0; i < NMAGICREGS; i++) { if (member_RealRegSet(&use.def, i)) ResultRename_fixdef(i, rc, &restoload); /* TODO: need to report a syserr if one of the result registers will be corrupted! */ } blkflags_(b) |= BLKREXPORTED; } /* TODO: a real implementation would need 2 passes to renumber the registers, because * it needs to rename USES too. BROKEN for inline assembler anyway! */ maybeswitchblock : if (n_in == 0 && b == dtorlast) { n_in = blklength_(dtorlast) - 2; code_old = blkcode_(dtorlast); b = bottom; } } if (noopcount > 0) { int32 n = 0, n_in = 0; for (; n_in < n_out; n_in++) if (code_new[n_in].op != J_NOOP) { if (n != n_in) code_new[n] = code_new[n_in]; n++; } n_out = n; } blklength_(bnew) = n_out; } } blkdown_(blast) = NULL; fn->bottom_block = blast; } { Inline_ArgDesc *ad = (Inline_ArgDesc *)(fn->args); for (; ad != NULL; ad = adcdr_(ad)) if (ad->abl.globnarrowarg != NULL) ad->abl.instantiatednarrowarg = FromGlobalBinderCopy(&st, ad->abl.globnarrowarg); } { SynBindList *bl = st.copied; for (; bl != NULL; bl = bl->bindlistcdr) h0_(bl->bindlistcar) = s_binder; } { VRegnum n = p->maxreg; Inline_VRegIndex *vt = p->vregtypetab; while (!isany_realreg_(--n)) vt[n].rs = vregsort(vt[n].r); } } void Inline_Init() { saved_fns = NULL; } static void Inline_CompileOutOfLineCopy(Inline_SavedFn *fn) { char v[128]; cg_sub_reinit(); Inline_Restore(fn, NULL); currentfunction = fn->fndetails; top_block = fn->top_block; bottom_block = fn->bottom_block; if (debugging(DEBUG_CG)) { sprintf(v, "Out-of-line %s", symname_(fn->fndetails.symstr)); flowgraf_print(v, NO); } cg_topdecl2(fn->var_binders, fn->reg_binders); } void Inline_Tidy() { SavedFnList *p; for (;;) { bool emitted = NO; for (p = saved_fns; p != NULL; p = cdr_(p)) if ((p->outoflineflags & ol_used) && !(p->outoflineflags & ol_emitted)) { { char v[128+5]; #ifdef TARGET_IS_THUMB /* This must be redone in a more sensible way later */ strcpy(v, "x$t$"); #else strcpy(v, "x$i$"); #endif strcpy(v+4, symname_(p->fn.fndetails.symstr)); obj_setcommoncode(); codebuf_reinit1(v); } emitted = YES; p->outoflineflags |= ol_emitted; Inline_CompileOutOfLineCopy(&p->fn); } if (!emitted) break; } } void Inline_LoadState(FILE *f) { uint32 w[5]; int32 nfn; fread(w, sizeof(uint32), 1, f); nfn = w[0]; while (--nfn >= 0) { SavedFnList *sf = NewGlob(SavedFnList, SU_Inline); fread(sf, sizeof(SavedFnList), 1, f); cdr_(sf) = saved_fns; saved_fns = sf; sf->fn.fndetails.symstr = Dump_LoadedSym((IPtr)sf->fn.fndetails.symstr); { Binder *b = bind_global_(sf->fn.fndetails.symstr); if (b != NULL) bindinline_(b) = sf; } sf->fn.fndetails.structresult = Dump_LoadedBinder((IPtr)sf->fn.fndetails.structresult); sf->fn.fndetails.argbindlist = Dump_LoadBindList(f); sf->fn.var_binders = Dump_LoadBindList(f); sf->fn.reg_binders = Dump_LoadBindList(f); { Inline_ArgDesc **adp = &argdesc_(sf); int32 n; fread(w, sizeof(uint32), 1, f); for (n = w[0]; --n >= 0; ) { Inline_ArgDesc *p = NewGlob(Inline_ArgDesc, SU_Inline); *adp = p; adp = &adcdr_(p); fread(w, sizeof(uint32), 3, f); p->flags = w[0]; p->abl.globarg = Dump_LoadedBinder(w[1]); p->abl.globnarrowarg = Dump_LoadedBinder(w[2]); p->abl.narrowtype = Dump_LoadType(f); } *adp = NULL; } sf->vregtypetab = NewGlobN(Inline_VRegIndex, SU_Inline, sf->maxreg); fread(sf->vregtypetab, sizeof(Inline_VRegIndex), (size_t)sf->maxreg, f); if (sf->fn.firstblockignoresize > 0) { sf->fn.firstblockignore = NewGlobN(uint8, SU_Inline, sf->fn.firstblockignoresize); fread(sf->fn.firstblockignore, sizeof(uint8), MapSize(sf->fn.firstblockignoresize), f); } else sf->fn.firstblockignore = NULL; if (sf->sort == IS_Ctor) { sf->a.ctor = NewGlobN(uint8, SU_Inline, sf->maxlabel); fread(sf->a.ctor, sizeof(uint8), MapSize(sf->maxlabel), f); } else if (sf->sort == IS_Dtor) fread(&sf->a.dtor, sizeof(LabelNumber *), 1, f); fread(w, sizeof(uint32), 1, f); { int32 nb = w[0]; BlockHead *b, *prev = NULL; for (; --nb >= 0; prev = b) { Icode *p; int32 n; int32 nstring; StringSegList **stringindex; b = NewGlob(BlockHead, SU_Inline); blkup_(b) = prev; if (prev == NULL) sf->fn.top_block = b; else blkdown_(prev) = b; fread(w, sizeof(uint32), 5, f); blklength_(b) = w[0]; blkflags_(b) = w[1]; blknext1_(b) = (LabelNumber *)(IPtr)w[2]; blklab_(b) = (LabelNumber *)(IPtr)w[3]; blkstack_(b) = Dump_LoadedSharedBindList(w[4]); blkusedfrom_(b) = NULL; blkuse_(b) = 0; blknest_(b) = 0; if (blkflags_(b) & BLKSWITCH) { blktable_(b) = NewGlobN(LabelNumber *, SU_Inline, blktabsize_(b)); fread(blktable_(b), sizeof(LabelNumber *), (size_t)blktabsize_(b), f); } else fread(&blknext_(b), sizeof(LabelNumber *), 1, f); if (sf->sort == IS_Dtor && (LabelNumber *)sf->a.dtor == blklab_(b)) sf->a.dtor = b; fread(&nstring, sizeof(uint32), 1, f); stringindex = NewSynN(StringSegList *, nstring); for (n = 0; n < nstring; n++) stringindex[n] = Dump_LoadStrSeg(f); if (blklength_(b) == 0) blkcode_(b) = (Icode *)DUFF_ADDR; else { blkcode_(b) = NewGlobN(Icode, SU_Inline, blklength_(b)); fread(blkcode_(b), sizeof(Icode), (size_t)blklength_(b), f); for (n = blklength_(b), p = blkcode_(b); --n >= 0; p++) { J_OPCODE op = p->op & J_TABLE_BITS; if (op == J_SETSPENV) { p->r3.bl = Dump_LoadedSharedBindList(p->r3.i); p->r2.bl = Dump_LoadedSharedBindList(p->r2.i); } else if (op == J_SETSPGOTO) { p->r2.bl = Dump_LoadedSharedBindList(p->r2.i); } else if (uses_stack(op) || op == J_CALLK || op==J_ADCON || op == J_INIT || op == J_INITF || op == J_INITD) { p->r3.b = Dump_LoadedBinder(p->r3.i); } else if (op == J_STRING) { p->r3.s = stringindex[p->r3.i]; } } } } blkdown_(prev) = NULL; sf->fn.bottom_block = prev; } } saved_fns = (SavedFnList *)dreverse((List *)saved_fns); } #ifndef NO_DUMP_STATE void Inline_DumpState(FILE *f) { SavedFnList *p = saved_fns; uint32 w[5]; w[0] = length((List *)p); fwrite(w, sizeof(uint32), 1, f); for (; p != NULL; p = cdr_(p)) { SavedFnList sf = *p; BlockHead *b; sf.fn.fndetails.symstr = (Symstr *)(IPtr)Dump_SymRef(sf.fn.fndetails.symstr); sf.fn.fndetails.structresult = (Binder *)(IPtr)Dump_BinderRef(sf.fn.fndetails.structresult); fwrite(&sf, sizeof(SavedFnList), 1, f); Dump_BindList(sf.fn.fndetails.argbindlist, f); Dump_BindList(sf.fn.var_binders, f); Dump_BindList(sf.fn.reg_binders, f); { Inline_ArgDesc *ad = argdesc_(&sf); w[0] = length((List *)&ad->abl); fwrite(w, sizeof(uint32), 1, f); for (; ad != NULL; ad = adcdr_(ad)) { w[0] = ad->flags; w[1] = Dump_BinderRef(ad->abl.globarg); w[2] = Dump_BinderRef(ad->abl.globnarrowarg); fwrite(w, sizeof(uint32), 3, f); Dump_Type(ad->abl.narrowtype, f); } } fwrite(sf.vregtypetab, sizeof(Inline_VRegIndex), (size_t)sf.maxreg, f); if (sf.fn.firstblockignoresize > 0) { fwrite(sf.fn.firstblockignore, sizeof(uint8), MapSize(sf.fn.firstblockignoresize), f); } if (sf.sort == IS_Ctor) fwrite(sf.a.ctor, sizeof(uint8), MapSize(sf.maxlabel), f); else if (sf.sort == IS_Dtor) fwrite(&blklab_(sf.a.dtor), sizeof(LabelNumber *), 1, f); w[0] = 0; for (b = sf.fn.top_block; b != NULL; b = blkdown_(b)) w[0]++; fwrite(w, sizeof(uint32), 1, f); for (b = sf.fn.top_block; b != NULL; b = blkdown_(b)) { Icode *p; int32 n; uint32 nstring; w[0] = blklength_(b); w[1] = blkflags_(b); w[2] = (uint32)(IPtr)blknext1_(b); w[3] = (uint32)(IPtr)blklab_(b); w[4] = Dump_NoteSharedBindList(blkstack_(b)); fwrite(w, sizeof(uint32), 5, f); if (blkflags_(b) & BLKSWITCH) fwrite(blktable_(b), sizeof(LabelNumber *), (size_t)blktabsize_(b), f); else fwrite(&blknext_(b), sizeof(LabelNumber *), 1, f); for (nstring = 0, n = blklength_(b), p = blkcode_(b); --n >= 0; p++) if ((p->op & J_TABLE_BITS) == J_STRING) nstring++; fwrite(&nstring, sizeof(uint32), 1, f); for (nstring = 0, n = blklength_(b), p = blkcode_(b); --n >= 0; p++) if ((p->op & J_TABLE_BITS) == J_STRING) { Dump_StrSeg(p->r3.s, f); p->r3.i = nstring++; } for (n = blklength_(b), p = blkcode_(b); --n >= 0; p++) { J_OPCODE op = p->op & J_TABLE_BITS; Icode c = *p; if (op == J_SETSPENV) { c.r3.i = Dump_NoteSharedBindList(p->r3.bl); c.r2.i = Dump_NoteSharedBindList(p->r2.bl); } else if (op == J_SETSPGOTO) { c.r2.i = Dump_NoteSharedBindList(p->r2.bl); } else if (uses_stack(op) || op == J_CALLK || op==J_ADCON || op == J_INIT || op == J_INITF || op == J_INITD) { c.r3.i = Dump_BinderRef(p->r3.b); } fwrite(&c, sizeof(Icode), 1, f); } } } } #endif /* NO_DUMP_STATE */
stardot/ncc
mip/compiler.h
<gh_stars>0 /* * C compiler file compiler.h * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Advanced RISC Machines Limited, 1991-92. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef __compiler_h #define __compiler_h #include "host.h" #include "backchat.h" #define TOOLNAME armcc #include "toolbox.h" #include "tooledit.h" typedef struct { backchat_Messenger *send; void *handle; } BackChatHandler; extern BackChatHandler backchat; extern ToolEnv *cc_default_env; int Tool_EditEnv(ToolEnv *t, HWND wh); int Tool_OrderedEnvEnumerate( ToolEnv *t, char const *prefix, ToolEdit_EnumFn *f, void *arg); bool Tool_Configurable(ToolEnv *t, char const *name); Uint TE_Integer(ToolEnv *t, char const *name, Uint def); bool TE_HasValue(ToolEnv *t, char const *name, char const *val); Uint TE_Count(ToolEnv *t, char const *prefix); void cc_announce_error(char *s, int severity, char const *file, int32 line); void UpdateProgress(void); void TE_DecodeArgumentLine(ToolEnv *t, char const *s, bool ignoreerrors); void TE_NormaliseEtc(ToolEnv *t); /* The filename suffixes subject to inversion under RISC OS/MVS etc. */ #ifdef FORTRAN # define FNAME_INCLUDE_SUFFIXES "f F h H" # define FNAME_SUFFIXES "a A f F h H o O s S" # define LANG_EXTN 'f' # define LANG_UC_EXTN 'F' # define LANG_EXTN_STRING "f" #else #ifdef PASCAL # define FNAME_INCLUDE_SUFFIXES "p P h H" # define FNAME_SUFFIXES "a A p P h H o O s S" # define LANG_EXTN 'p' # define LANG_UC_EXTN 'P' # define LANG_EXTN_STRING "p" #else #ifdef BCPL # define FNAME_INCLUDE_SUFFIXES "b B h H" # define FNAME_SUFFIXES "a A b B h H o O s S" # define LANG_EXTN 'b' # define LANG_UC_EXTN 'B' # define LANG_EXTN_STRING "b" #else # define FNAME_INCLUDE_SUFFIXES "c C h H c++ C++ cpp CPP cp CP i I" # define FNAME_SUFFIXES "a A c C h H o O s S c++ C++ cpp CPP cp CP" # define LANG_EXTN 'c' # define LANG_UC_EXTN 'C' # define LANG_EXTN_STRING "c" #endif #endif #endif #include <time.h> /* for time_t */ extern time_t tmuse_front, tmuse_back; int ccom(ToolEnv *t, char const *in_file, char const *out_file, char const *list_file, char const *md_file); extern void driver_abort(char *message); extern void compiler_exit(int status); extern bool cistreq(const char *s1, const char *s2); /* s2 must be lower case */ extern bool cistrneq(const char *s1, const char *s2, size_t n); #ifdef FOR_ACORN extern bool cplusplus_preprocessing(void); #endif extern bool inputfromtty; #endif
stardot/ncc
cfe/fevsn.h
<filename>cfe/fevsn.h<gh_stars>0 #define FE_VERSION "500"
stardot/ncc
arm/coff.c
/* * C compiler file arm/coff.c * Copyright (C) Codemist Ltd, 1988 * Copyright (C) Advanced Risc Machines Limited, 1993 * 'COFF' (system V unix) output routines * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 13j * Checkin $Date$ * Revising $Author$ */ /* AM: Feb 90: add AUX items for sections. Fix bug in common refs */ /* (find #if (R_DIR32 == 17) below for detailed explanation). */ /* Memo: stuff CC_BANNER in the object file in the .comment section. */ /* Put the COFF style debug info in the file too. */ /* This will cause review of the ordering of symbols */ /* target.h shall specify: TARGET_HAS_COFF, target_coff_magic = <number>, */ /* and (optionally) target_coff_prefix. */ /* maybe (one day) also the target_coff_<relocations> below too. */ #ifndef __STDC__ # include <strings.h> # define SEEK_SET 0 #else # include <string.h> #endif #include <stddef.h> #include <time.h> /* see time() below */ #include "globals.h" /* loads host.h,options.h,target.h,defaults.h */ #include "mcdep.h" #include "mcdpriv.h" #include "aeops.h" #include "store.h" #include "codebuf.h" #include "regalloc.h" #include "util.h" #include "bind.h" /* evaluate */ #include "sem.h" /* alignoftype, sizeoftype, structfield */ #include "builtin.h" #include "xrefs.h" #include "errors.h" #include "simplify.h" #include "coff.h" /* Codemist private version */ #include "fname.h" /* The following values are suitable for the 88000 ocs, but act as */ /* suitable defaults. Values are best specified in 'target.h'. */ #ifndef R_DIR32 # define R_DIR32 133 /* absolute relocation. */ #endif #ifndef R_PCRLONG # define R_PCRLONG 129 /* pc relative relocation. */ #endif #ifndef R_REFHI # define R_REFHI 131 /* R_HVRT16 */ #endif #ifndef R_REFLO # define R_REFLO 132 /* R_LVRT16 */ #endif #ifndef target_coff_prefix # define target_coff_prefix "_" #endif /* We now follow 'as' and always generate a BSS section which is */ /* usually empty. There MAY be common ext. ref. problems otherwise. */ #ifdef TARGET_IS_STARDENT #define NSCNS 2 #else #define NSCNS 3 #endif #define N_TEXT 1 #define N_DATA 2 #define N_BSS 3 #define HDRSIZE (sizeof(struct filehdr) + NSCNS*sizeof(struct scnhdr)) #define xr_section xr_objflg #define xr_deleted xr_objflg1 /* The following #defines give the logical section origins. */ #define ORG_TEXT 0 #define ORG_DATA 0 #define ORG_BSS 0 #define SYM_FULLY_RELOCATED ((Symstr *)0) /* internal PCreloc ref */ static bool byte_reversing = 0; /* byte_reversing == (host_lsbytefirst != target_lsbytefirst). */ /* (But faster to test one static per word than 2 externs per word). */ /* Private interfaces to debug table generator */ static int32 dbg_fixup(ExtRef *syms, int32 symcount); static void dbg_outsymtab(void); static int32 dbg_lineinfo(void); static int32 obj_fwrite_cnt; #define ROR(x, n) (((x) << (32-(n))) | ((x) >> (n))) static unsigned32 TargetWord(unsigned32 w) { if (byte_reversing) { unsigned32 t = w ^ ROR(w, 16); t &= ~0xff0000; w = ROR(w, 8); return w ^ (t >> 8); } else return w; } static unsigned TargetHalf(unsigned32 w) { if (byte_reversing) { return (unsigned)(((w >> 8) & 0xff) | ((w & 0xff) << 8)); } else return (unsigned)w; } static void obj_fwrite(void *buff, int32 n, int32 m, FILE *f) { if (debugging(DEBUG_OBJ)) { int32 i; fprintf(f, "%.6lx:", (long)obj_fwrite_cnt); obj_fwrite_cnt += n*m; for (i=0; i<n*m; i++) fprintf(f, " %.2x", (int)((unsigned8 *)buff)[i]); fprintf(f, "\n"); } else if (n == 4 && byte_reversing) { /* word by word output */ unsigned32 v, t, *p, w; for (p = (unsigned32 *)buff; m > 0; --m, ++p) { v = *p; t = v ^ ROR(v, 16); t &= ~0xff0000; v = ROR(v, 8); w = v ^ (t >> 8); fwrite(&w, 4, 1, f); } } else fwrite(buff, (size_t)n, (size_t)m, f); } FILE *objstream; /* imports: codebase, dataloc */ static unsigned32 ncoderelocs, ndatarelocs, obj_symcount; static unsigned32 constdatabase; ExtRef *obj_symlist; CodeXref *codexrefs; static int32 obj_lnno; /* In general, COFF requires references to symbols which are defined */ /* in codeseg, dataseg or bssseg to be replaced by a reference to */ /* segment+offset. Hence the code for a C routine with an 'extern' */ /* reference is not complete until we know whether it was truly extern */ /* or merely 'forward'. So buffer the code (in codevec) from each fn */ /* into 'xcodevec' and then call relocate_code_refs_to_locals() before */ /* writing xcodevec into the COFF .o file. */ #define MAXCODESEGS 256 static int32 (*(xcodevec[MAXCODESEGS]))[CODEVECSEGSIZE], codesize; #ifdef TARGET_HAS_BYTE_INSTRUCTIONS #define xcode_byte_(q) ((unsigned8 *)(*xcodevec[(q)>>(CODEVECSEGBITS+2)])) \ [(q)&(CODEVECSEGSIZE*4-1)] #else #define xcode_inst_(q) (*xcodevec[(q)>>(CODEVECSEGBITS+2)]) \ [((q)>>2)&(CODEVECSEGSIZE-1)] #endif #define get_code(q) xcode_inst_(q) #define set_code(q,n) xcode_inst_(q)=n /* The following code is in flux and allows for the generic compiler */ /* interfaces to use byte addresses which are corrected here. It now */ /* occurs to AM that we could have used word addresses more, but this */ /* could also be a can of worms. Let's try this way FIRST. */ #ifdef TARGET_IS_ADENART # define machine_address_(v,f) ((v)/((f) & xr_code ? 3:8)) #else # define machine_address_(v,f) (v) #endif static void buffer_code(int32 *src, int32 nwords) { int32 *p; for (p = src; nwords > 0; --nwords) { int32 hi = codesize >> (CODEVECSEGBITS+2); int32 lo = (codesize >> 2) & (CODEVECSEGSIZE-1); if (lo == 0) { /* need another segment */ if (hi >= MAXCODESEGS) cc_fatalerr(coff_fatalerr_toobig); xcodevec[hi] = (int32(*)[CODEVECSEGSIZE]) GlobAlloc( SU_Other, sizeof(*xcodevec[0])); } (*xcodevec[hi])[lo] = *p++; codesize += 4; } } static int32 obj_checksym(Symstr *s); /* @@@ The code here is getting silly. X_JmpAddr is not really */ /* a PCreloc. */ static void relocate_code_refs_to_locals(void) { /* This proc. should soon callback to a routine in gen.c: */ CodeXref *cxr; for (cxr = codexrefs; cxr != NULL; cxr = cxr->codexrcdr) { Symstr *s = cxr->codexrsym; ExtRef *x = ((void)obj_checksym(s), symext_(s)); int32 codeoff = cxr->codexroff & 0xffffff; int32 w = get_code(codeoff); switch (cxr->codexroff & 0xff000000) { case X_PCreloc: /* on the MIPS also means X_JmpAddr -- rationalise */ /* pcrelative code ref (presumed to) to code. */ /* @@@ cast of array to code pointer causes the following */ /* syserr(). Needs fixing properly. */ if (!(x->extflags & xr_code)) syserr(syserr_coff_reloc); if (x->extflags & (xr_defloc | xr_defext)) { /* defined in this compilation unit so relocate... */ cxr->codexrsym = SYM_FULLY_RELOCATED; /* @@@ AM: before 'rationalising' this code, it is IMPORTANT to build */ /* in the 29000 or 88000 32 bits in 64 bits relocation modes. */ /* AM: note that in all the following cases any offset in the code is */ /* ignored and simply overwritten. Change this one day? */ #ifdef TARGET_IS_ARM /* On the ARM relocate a B or BL; offset in WORDs; prefetch 8 bytes. */ #define obj_codeupdate(n) \ set_code(codeoff, (w & 0xff000000) | (((n)-8) >> 2) & 0x00ffffff) #endif obj_codeupdate(x->extoffset-codeoff); } else { /* Branch to external symbol. Most Unices expect to be */ /* tight branch to self. (On the ARM, the Unix linker */ /* expects unrelocated branch to be -2 words, */ obj_codeupdate(0); } if (debugging(DEBUG_OBJ)) cc_msg("Fixup %.8lx extoff=%.8lx, codeoff=%.8lx, make %.8lx\n", (long)w, (long)x->extoffset, (long)codeoff, (long)get_code(codeoff)); break; case X_absreloc: case X_backaddrlit: /* abs ref to external */ /* Code here may need changing if you set ORG_TEXT &c to non-zero. */ if (x->extflags & (xr_defloc | xr_defext)) { /* code ref to local code or data via address literal... * (or clipper/vax absolute 32 bit branch). * Unix linker cannot cope with filling in the address literal * with the value of a locally defined symbol: we have to convert * it into a reference relative to v$codeseg or v$dataseg. * This process is completed by obj_checksym(). * AM: note that we do take notice of the old value here. */ if (x->extflags & xr_constdata) w += constdatabase; set_code(codeoff, w + x->extoffset); } break; } } } static void obj_writecode(void) { int i = 0; #if (alignof_double > 4) /* TARGET_ALIGNS_DOUBLES */ if (codesize & 7) { static int32 pad[] = {0,0,0}; buffer_code(pad, 1); /* Double word aligned */ } #endif relocate_code_refs_to_locals(); while ((codesize>>2) - CODEVECSEGSIZE*i > CODEVECSEGSIZE) obj_fwrite(xcodevec[i++], 4, CODEVECSEGSIZE, objstream); obj_fwrite(xcodevec[i], 4,(codesize>>2)-CODEVECSEGSIZE*i, objstream); if (ferror(objstream)) cc_fatalerr(driver_fatalerr_io_object); } void obj_codewrite(Symstr *name) { /* Called after each routine is compiled -- code_instvec_ (doubly */ /* indexed) has codep (multiple of 4) bytes of code. */ /* In BSD a.out, this has to be buffered to the end of compilation */ /* so that the BSD linker can be cow-towed to. */ /* #define COMPILING_ON_SMALL_MEMORY can be used to buffer on disc. */ int32 i, nwords; IGNORE(name); if (byte_reversing) { int32 n = codep, w; for (i = 0; i < n; i += 4) { w = totargetsex(code_inst_(i), code_flag_(i)); buffer_code(&w, 1); } } else for (i = 0, nwords = codep>>2; nwords > 0; ++i) { int32 seg = nwords > CODEVECSEGSIZE ? CODEVECSEGSIZE : nwords; buffer_code(code_instvec_(i), seg); nwords -= seg; } } /* the remaining fns are intended to be internal only */ /* In COFF, the data segment label is required to be .data etc. */ #define coffname_(s) ((s) == bindsym_(codesegment) ? ".text" : \ (s) == bindsym_(datasegment) ? ".data" : \ (s) == bindsym_(bsssegment) ? ".bss" : \ symname_(s)) /* TEMPHACK: */ typedef union AuxEnt { struct syment pad; struct { long int x_scnlen; unsigned short x_nreloc; unsigned short x_nlinno; } x_scn; } AuxEnt; typedef struct StringTabEntry StringTabEntry; struct StringTabEntry { StringTabEntry *cdr; char name[1]; }; static StringTabEntry *stringtab; static unsigned32 stringtabpos; static void obj_stab(char *name, int32 val, int sect, int type, int sclass, void *auxp) { size_t n = strlen(name), k = sclass != C_EXT || name[0]=='.' ? 0 : sizeof(target_coff_prefix)-1; struct syment v; memclr(&v, SYMESZ); if (debugging(DEBUG_OBJ)) cc_msg("sym %s ", name); if (n+k > SYMNMLEN) { /* NB: '>' (not '>=') is OK here */ /* do the long form, name in the string table */ StringTabEntry *p = (StringTabEntry *)SynAlloc((int32)sizeof(StringTabEntry)+n+k); if (k > 0) memcpy(p->name, target_coff_prefix, k); memcpy(&p->name[k], name, n+1); v.n_zeroes = 0; v.n_offset = TargetWord(stringtabpos); stringtabpos += (size_t)(n+k+1); cdr_(p) = stringtab; stringtab = p; } else { if (k > 0) strncpy(v.n_name, target_coff_prefix, k); strncpy(v.n_name+k, name, SYMNMLEN-k); } v.n_value = TargetWord(val); v.n_scnum = TargetHalf(sect); v.n_type = TargetHalf(type); /* not set yet */ v.n_sclass = sclass; v.n_numaux = auxp == NULL ? 0 : 1; obj_fwrite(&v, 1, SYMESZ, objstream); if (auxp != NULL) obj_fwrite(auxp, 1, SYMESZ, objstream); } /* TEMPHACK: */ static void SetSegAux(AuxEnt *p, int32 seglen, int32 nrelocs, int32 nlno) { memclr(p, sizeof(*p)); p->x_scn.x_scnlen = TargetWord(seglen); p->x_scn.x_nreloc = TargetHalf(nrelocs); p->x_scn.x_nlinno = TargetHalf(nlno); } static void obj_outsymtab(int32 mask, int32 maskedval) { ExtRef *x; for (x = obj_symlist; x != 0; x = x->extcdr) { Symstr *s = x->extsym; int32 flags = x->extflags; if ((flags & mask) == maskedval) { char *name = coffname_(s); /* The next line stores the value (= offset in segment) for code or */ /* data definitions, and stores zero for external refs, except for */ /* pcc-style common refs, in which it stores the length. */ int32 val = x->extoffset; /* note that C_EXTDEF is documented as "internal to C, use C_EXT". */ int sclass = flags & xr_defloc ? C_STAT : C_EXT; AuxEnt *auxp = NULL; AuxEnt aux; int sect; if (!(flags & xr_defloc+xr_defext)) sect = N_UNDEF; else if (flags & xr_code) sect = N_TEXT, val += ORG_DATA; else if (flags & xr_constdata) sect = N_TEXT, val += ORG_DATA+constdatabase; else if (flags & xr_bss) sect = N_BSS, val += ORG_BSS; else sect = N_DATA, val += ORG_DATA; /* TEMPHACK: */ if (s == bindsym_(codesegment)) SetSegAux(auxp = &aux, codesize, ncoderelocs, obj_lnno); /* TEMPHACK: */ if (s == bindsym_(datasegment)) SetSegAux(auxp = &aux, data.size, ndatarelocs, 0); /* TEMPHACK: */ if (s == bindsym_(bsssegment)) SetSegAux(auxp = &aux, bss_size, 0, 0); obj_stab(name, val, sect, T_NULL, sclass, auxp); } } } static void obj_outstringtab(void) { /* write the string table, preceded by its length */ obj_fwrite(&stringtabpos, sizeof(stringtabpos), 1, objstream); { StringTabEntry *p; stringtab = (StringTabEntry *)dreverse((List *)stringtab); for (p = stringtab; p != 0; p = cdr_(p)) obj_fwrite(p->name, 1, (int32)strlen(p->name)+1, objstream); } } static int32 obj_checksym(Symstr *s) { ExtRef *x = symext_(s); if (x != 0) { if (!(x->extflags & xr_defloc+xr_defext) || s==bindsym_(codesegment) || s==bindsym_(datasegment) || s==bindsym_(bsssegment)) /* honest external or segment defining symbol */ return x->extindex; else return obj_checksym(x->extflags & (xr_code+xr_constdata) ? bindsym_(codesegment) : x->extflags & xr_bss ? bindsym_(bsssegment) : bindsym_(datasegment)); } syserr(syserr_coff_checksym, s); return 0; } static void obj_wr_reloc(struct reloc *p, int r) { p->r_type = TargetHalf(r); /* NB note that sizeof(struct reloc) > RELSZ on many machines */ obj_fwrite(p, 1, RELSZ, objstream); ncoderelocs++; } static void obj_coderelocation() { CodeXref *x; struct reloc v; for (x = codexrefs; x!=NULL; x = x->codexrcdr) { Symstr *s = x->codexrsym; if (s == SYM_FULLY_RELOCATED) continue; v.r_vaddr = TargetWord((x->codexroff & 0xffffff) + ORG_TEXT); v.r_symndx = TargetWord(obj_checksym(s)); switch (x->codexroff & 0xff000000) { case X_PCreloc: /* PC rel ref to external */ if (debugging(DEBUG_OBJ)) cc_msg("pcreloc$r ", s); obj_wr_reloc(&v, R_PCRLONG); /* target_coff_pcrel? */ break; case X_absreloc: /* abs ref to external */ case X_backaddrlit: /* ditto, but literal */ if (debugging(DEBUG_OBJ)) cc_msg("addreloc$r ", s); obj_wr_reloc(&v, R_DIR32); /* target_coff_abs? */ break; default: syserr(syserr_coff_reloc1, (long)x->codexroff); break; } } } static int32 obj_datarelocation(DataXref *x, int32 offset) { struct reloc v; int32 n = 0; for (; x != NULL; x = x->dataxrcdr, n++) { Symstr *s = x->dataxrsym; /* all data relocs are implicitly X_absreloc so far */ if (debugging(DEBUG_OBJ)) cc_msg("data reloc $r ", s); v.r_type = TargetHalf(R_DIR32); /* target_coff_abs? */ v.r_vaddr = TargetWord(x->dataxroff+offset+ORG_DATA); /* & 0xffffff ? */ v.r_symndx = TargetWord(obj_checksym(s)); /* NB note that sizeof(struct reloc) > RELSZ on many machines */ obj_fwrite(&v, 1, RELSZ, objstream); } return n; } static void obj_writedata(DataInit *p) { /* follows gendc exactly! */ for (; p != 0; p = p->datacdr) { int32 rpt = p->rpt, sort = p->sort, len = p->len; unsigned32 val = p->val; switch (sort) { case LIT_LABEL: /* name only present for c.xxxasm */ break; default: syserr(syserr_coff_gendata, (long)sort); case LIT_BXXX: /* The following are the same as LIT_NUMBER */ case LIT_BBX: /* except for cross-sex compilation */ case LIT_BBBX: case LIT_BBBB: case LIT_HX: case LIT_HH: case LIT_BBH: case LIT_HBX: case LIT_HBB: if (byte_reversing) { unsigned32 t; val = totargetsex(val, (int)sort); t = val ^ ROR(val, 16); t &= ~0xff0000; val = ROR(val, 8); val = val ^ (t >> 8); } while (rpt-- != 0) obj_fwrite(&val, 1, len, objstream); break; case LIT_NUMBER: if (len != 4) syserr(syserr_coff_datalen, (long)len); /* beware: sex dependent... */ while (rpt-- != 0) obj_fwrite(&val, 4, 1, objstream); break; case LIT_ADCON: /* (possibly external) name + offset */ { Symstr *sv = (Symstr *)len; /* this reloc also in dataxrefs */ ExtRef *xr= symext_(sv); (void)obj_checksym(sv); if (xr->extflags & (xr_defloc|xr_defext)) { val += xr->extoffset; if (xr->extflags & xr_constdata) val += constdatabase; } /* beware: sex dependent... */ while (rpt-- != 0) obj_fwrite(&val, 4, 1, objstream); break; } case LIT_FPNUM: { FloatCon *fc = (FloatCon *)val; /* do we need 'len' when the length is in fc->floatlen?? */ if (len != 4 && len != 8) syserr(syserr_coff_data, (long)rpt, (long)len, fc->floatstr); /* The following strange code ensures that doubles are correctly */ /* sex-reversed if required to be - obj_fwrite() only reverses */ /* items of length 4... This is a trap for the unwary. */ while (rpt-- != 0) { obj_fwrite(&(fc->floatbin.irep[0]), 4, 1, objstream); if (len == 4) continue; obj_fwrite(&(fc->floatbin.irep[1]), 4, 1, objstream); } break; } } } } /* exported functions... */ int32 obj_symref(Symstr *s, int flags, int32 loc) { ExtRef *x; if ((x = symext_(s)) == 0) { /* saves a quadratic loop */ if (obj_symcount > 0x7fffffff) cc_fatalerr(coff_fatalerr_toomany); x = (ExtRef *)GlobAlloc(SU_Xref, sizeof(ExtRef)); x->extcdr = obj_symlist, x->extsym = s, x->extindex = obj_symcount++, x->extflags = 0, x->extoffset = 0; obj_symlist = symext_(s) = x; /* TEMPHACK: */ if (s == bindsym_(codesegment) || s == bindsym_(datasegment) || s == bindsym_(bsssegment)) { x->extflags |= xr_section; obj_symcount++; } } /* The next two lines cope with further ramifications of the abolition of */ /* xr_refcode/refdata in favour of xr_code/data without xr_defloc/defext */ /* qualification. This reduces the number of bits, but needs more */ /* checking in that a symbol defined as data, and then called via */ /* casting to a code pointer may acquire defloc+data and then get */ /* xr_code or'ed in. Suffice it to say this causes confusion. */ /* AM wonders if gen.c ought to be more careful instead. */ if (flags & (xr_defloc+xr_defext)) x->extflags &= ~(xr_code+xr_data); if (x->extflags & (xr_defloc+xr_defext)) flags &= ~(xr_code+xr_data); /* end of fix, but perhaps we should be more careful about mult. defs.? */ x->extflags |= flags; if (flags & xr_defloc+xr_defext) { /* private or public data or code */ x->extoffset = machine_address_(loc,flags); } else if ((loc > 0) && !(flags & xr_code) && !(x->extflags & xr_defloc+xr_defext)) { /* common data, not already defined */ /* -- put length in x->extoffset */ if (loc > x->extoffset) x->extoffset = machine_address_(loc,flags); } /* The next line returns the offset of a function in the codesegment */ /* if it has been previously defined -- this saves store on the arm */ /* and allows short branches on other machines. Otherwise it */ /* returns -1 for undefined objects or data objects. */ return ((x->extflags & (xr_defloc+xr_defext)) && (x->extflags & xr_code) ? x->extoffset : -1); } /* For fortran... */ void obj_common_start(Symstr *name) { /* There is no real support in COFF for common definitions (BLOCK */ /* DATA). What needs to be done is to turn the block name into */ /* an exported symbol in the normal data area (.data). */ labeldata(name); obj_symref(name, xr_data+xr_defext, data.size); } void obj_common_end(void) {} void obj_init() { ncoderelocs = 0, ndatarelocs = 0, obj_symcount = 0; obj_symlist = 0; data.xrefs = 0; codexrefs = 0; codesize = 0; /* remove */ stringtabpos = sizeof(stringtabpos); stringtab = NULL; obj_lnno = 0; byte_reversing = (target_lsbytefirst != host_lsbytefirst); /* codesegment and datasegment are arranged elsewhere */ obj_symref(bindsym_(bsssegment), xr_bss+xr_defloc, 0L); } void obj_header() { struct filehdr h; struct scnhdr s; if ((ncoderelocs | ndatarelocs) & ~(unsigned32)(unsigned short)-1) cc_fatalerr(coff_fatalerr_toomany); obj_fwrite_cnt = 0; h.f_magic = TargetHalf(target_coff_magic); h.f_nscns = TargetHalf(NSCNS); h.f_timdat = TargetWord(time(NULL)); /* hope unix format -- norcroft use too. */ h.f_symptr = TargetWord(HDRSIZE + codesize + data.size + /* @@@ round to multiple of 4? (RELSZ = 10) */ ncoderelocs*RELSZ + ndatarelocs*RELSZ + obj_lnno*6); h.f_nsyms = TargetWord(obj_symcount); h.f_opthdr = 0; /* no optional header */ h.f_flags = 0; /* default F_xxxx flags */ obj_fwrite(&h, 1, sizeof(h), objstream); /* code section header */ strncpy(s.s_name, ".text", sizeof(s.s_name)); s.s_paddr = s.s_vaddr = TargetWord(ORG_TEXT); s.s_size = TargetWord(codesize); s.s_scnptr = TargetWord(HDRSIZE); s.s_relptr = TargetWord(HDRSIZE + codesize + data.size); s.s_lnnoptr = TargetWord(obj_lnno == 0 ? 0 : HDRSIZE + codesize + data.size + ncoderelocs*RELSZ + ndatarelocs*RELSZ); s.s_nreloc = TargetHalf(ncoderelocs); s.s_nlnno = TargetHalf(obj_lnno); s.s_flags = TargetWord(STYP_TEXT); obj_fwrite(&s, 1, sizeof(s), objstream); /* data section header */ strncpy(s.s_name, ".data", sizeof(s.s_name)); s.s_paddr = s.s_vaddr = TargetWord(ORG_DATA); s.s_size = TargetWord(data.size); s.s_scnptr = TargetWord(HDRSIZE + codesize); s.s_relptr = TargetWord(HDRSIZE + codesize + data.size + ncoderelocs*RELSZ); s.s_lnnoptr = 0; /* no line number info */ s.s_nreloc = TargetHalf(ndatarelocs); s.s_nlnno = 0; /* no line number info */ s.s_flags = TargetWord(STYP_DATA); obj_fwrite(&s, 1, sizeof(s), objstream); /* bss section header */ strncpy(s.s_name, ".bss", sizeof(s.s_name)); s.s_paddr = s.s_vaddr = TargetWord(ORG_BSS); s.s_size = TargetWord(bss_size); s.s_scnptr = 0; s.s_relptr = 0; s.s_lnnoptr = 0; /* no line number info */ s.s_nreloc = 0; /* no relocations */ s.s_nlnno = 0; /* no line number info */ s.s_flags = TargetWord(STYP_BSS); obj_fwrite(&s, 1, sizeof(s), objstream); } void obj_trailer() { codexrefs = (CodeXref *)dreverse((List *)codexrefs); data.xrefs = (DataXref *)dreverse((List *)data.xrefs); constdata.xrefs = (DataXref *)dreverse((List *)constdata.xrefs); obj_symlist = (ExtRef *)dreverse((List *)obj_symlist); /* oldest = smallest numbered first */ obj_symcount = dbg_fixup(obj_symlist, obj_symcount); if (debugging(DEBUG_OBJ)) cc_msg("writecode\n"); constdatabase = codesize; obj_writecode(); obj_writedata(constdata.head); codesize += constdata.size; if (debugging(DEBUG_OBJ)) cc_msg("writedata\n"); obj_writedata(data.head); if (debugging(DEBUG_OBJ)) cc_msg("coderelocation\n"); obj_coderelocation(); ncoderelocs += obj_datarelocation(constdata.xrefs, constdatabase); if (debugging(DEBUG_OBJ)) cc_msg("datarelocation\n"); ndatarelocs = obj_datarelocation(data.xrefs, 0L); obj_lnno = dbg_lineinfo(); if (debugging(DEBUG_OBJ)) cc_msg("symtab\n"); dbg_outsymtab(); if (debugging(DEBUG_OBJ)) cc_msg("rewind\n"); rewind(objstream); /* works for hex format too */ if (debugging(DEBUG_OBJ)) cc_msg("rewriting header\n"); obj_header(); /* re-write header at top of file */ /* file now opened and closed in main(). */ } #ifdef TARGET_HAS_DEBUGGER /* Storage classes */ #define C_NULL 0 #define C_AUTO 1 /*#define C_EXT 2*/ /* extern (ref) (in coff.h) */ /*#define C_STAT 3*/ /* static (in coff.h) */ #define C_REG 4 #define C_EXTDEF 5 #define C_LABEL 6 #define C_ULABEL 7 /* undefined label (?) */ #define C_MOS 8 /* member of structure */ #define C_ARG 9 #define C_STRTAG 10 /* structure tag */ #define C_MOU 11 /* member of union */ #define C_UNTAG 12 /* union tag */ #define C_TPDEF 13 /* typedef */ #define C_USTATIC 14 /* unitialised static - what is this? */ #define C_ENTAG 15 /* enumeration tag */ #define C_MOE 16 /* member of enumeration */ #define C_REGPARM 17 /* register param */ #define C_FIELD 18 /* bitfield (presumably also implicitly MOS) */ #define C_BLOCK 100 #define C_FCN 101 #define C_EOS 102 /* end of structure (enumeration, union?) */ #define C_FILE 103 #define C_HIDDEN 106 /* static with possibly clashing name */ /* Section numbers */ #define N_DEBUG (-2) #define N_ABS (-1) /*#define N_UNDEF 0*/ /* in coff.h */ /*#define N_TEXT 1*/ /* see above */ /*#define N_DATA 2*/ /* see above */ /*#define N_BSS 3*/ /* see above */ /* fundamental types */ /*#define T_NULL 0*/ /* in coff.h */ #define T_LDOUBLE 1 #define T_CHAR 2 /* (signed) */ #define T_SHORT 3 #define T_INT 4 #define T_LONG 5 #define T_FLOAT 6 #define T_DOUBLE 7 #define T_STRUCT 8 #define T_UNION 9 #define T_ENUM 10 #define T_MOE 11 #define T_UCHAR 12 #define T_USHORT 13 #define T_UINT 14 #define T_ULONG 15 /* derived types */ #define DT_NON 0 #define DT_PTR 1 #define DT_FCN 2 #define DT_ARRAY 3 int usrdbgmask; static int32 anonindex; #define DbgAlloc(n) GlobAlloc(SU_Dbg, n) typedef struct DbgList DbgList; typedef struct { int w; unsigned8 modct, dimct; DbgList *tag; int32 *dims; } Dbg_Type; typedef struct StructElt StructElt; typedef struct EnumElt EnumElt; struct StructElt { StructElt *cdr; /* must be first for dreverse */ int32 val; char *name; Dbg_Type type; }; struct EnumElt { EnumElt *cdr; /* must be first for dreverse */ int32 val; char *name; }; typedef struct FileCoord FileCoord; struct FileCoord { FileCoord *cdr; int line; int32 codeaddr; }; #define DbgListVarSize(variant) \ ((size_t)(sizeof(p->car.variant)+offsetof(DbgList,car))) /* The following is the *internal* data structure in which debug info. */ /* is buffered. */ #define S_Undef 16 typedef enum { Ignore, File, Proc, EndProc, BlockStart, BlockEnd, Var, Type, Enum, Union, Struct, UndefEnum = Enum+S_Undef, UndefUnion = Union+S_Undef, UndefStruct = Struct+S_Undef, UndefVar = Var+S_Undef } DbgListSort; struct DbgList { DbgList *cdr; DbgListSort sort; int32 index; union { struct { char *name; DbgList *next; } File; struct { Dbg_Type type; int stgclass; Symstr *name; unsigned8 oldstyle; int sourcepos; int32 filepos; int32 entryaddr, bodyaddr; /* see dbg_bodyproc */ DbgList *end; /* corresponding EndProc item */ FileCoord *linelist; } Proc; struct { int sourcepos; int32 endaddr; char *fileentry; } EndProc; struct { Dbg_Type type; int stgclass; Symstr *name; int32 location; int section; int sourcepos; } Var; struct { int32 entries; int32 size; bool named; union { int32 anonindex; char *name; } tag; union { StructElt *s; EnumElt *e; } elts; } Tag; struct { union { DbgList *next; int32 codeaddr; } s; DbgList *p; /* block starts only: previous block start if */ /* not yet closed, else block end */ } Block; } car; }; static DbgList *locdbglist, *globdbglist, *statdbglist, *dbglistproc; static DbgList *dbglistblockstart; static DbgList *dbglistfile; static void CheckFile(char *f) { if (dbglistfile == NULL || dbglistfile->car.File.name != f) { if (locdbglist == NULL || locdbglist != dbglistfile || statdbglist != NULL) { /* A file containing something of interest (otherwise lose it) */ DbgList *p = (DbgList *)DbgAlloc(DbgListVarSize(File)); locdbglist = (DbgList *)nconc((List *)statdbglist, (List *)locdbglist); statdbglist = NULL; cdr_(p) = locdbglist; p->sort = File; p->index = 0; p->car.File.next = NULL; if (dbglistfile != NULL) dbglistfile->car.File.next = p; locdbglist = p; dbglistfile = p; } dbglistfile->car.File.name = f; } } VoidStar dbg_notefileline(FileLine fl) { if (usrdbg(DBG_LINE) && dbglistproc != NULL) { FileCoord *p, *l = dbglistproc->car.Proc.linelist; /* @@@ beware - odd use of #line *MAY* (check) set off the syserr() */ if (l != NULL && l->line > fl.l) syserr(syserr_debugger_line); p = (FileCoord *)DbgAlloc(sizeof(FileCoord)); cdr_(p) = l; p->line = fl.l; p->codeaddr = -1; dbglistproc->car.Proc.linelist = p; return (VoidStar)p; } return DUFF_ADDR; } static DbgList *dbglistscope; /* The 'dbgaddr' arg has type 'void *' to keep the debugger types local to */ /* this file. This does not make it any less of a (ANSI approved) hack. */ void dbg_addcodep(VoidStar dbgaddr, int32 codeaddr) { if (dbgaddr == NULL) { /* J_INFOSCOPE */ /* c.flowgraf outputs a J_INFOSCOPE immediately after calling * dbg_scope, to mark the relevant code address. */ if (debugging(DEBUG_Q)) cc_msg("-- scope at 0x%lx\n", codeaddr); { DbgList *next, *p = dbglistscope; for (; p != NULL; p = next) { next = p->car.Block.s.next; p->car.Block.s.codeaddr = codeaddr; } dbglistscope = NULL; } } else if (usrdbg(DBG_LINE)) { FileCoord *p = (FileCoord *)dbgaddr; if (debugging(DEBUG_Q)) cc_msg("%p (line %u) @ %.6lx\n", p, p->line, (long)codeaddr); /* The following test avoids setting nextincode/codeaddr twice */ /* This is currently needed in case FileLine's are duplicated. */ if (p->codeaddr == -1) p->codeaddr = codeaddr; } } static int32 dbg_lineinfo(void) { DbgList *p = locdbglist; struct { int32 addr; int16 line; } lineno; int32 count = 0; if (usrdbg(DBG_LINE)) for (; p != NULL; p = cdr_(p)) { if (p->sort == Proc) { int startline = p->car.Proc.sourcepos; int lastline = startline; int32 addr = 0; FileCoord *coord = (FileCoord *)dreverse((List *)p->car.Proc.linelist); lineno.addr = TargetWord(p->index); lineno.line = 0; obj_fwrite(&lineno, 1, 6, objstream); count++; for (; coord != NULL; coord = cdr_(coord)) if (coord->line > lastline && coord->codeaddr > addr) { addr = coord->codeaddr; lastline = coord->line; lineno.addr = TargetWord(addr); lineno.line = TargetHalf((int32)lastline - startline); obj_fwrite(&lineno, 1, 6, objstream); count++; } } } return count; } /* End of file/line co-ordinate code */ static int32 AuxEntryCount(Dbg_Type *t) { return t->dimct != 0 ? 1 : t->tag != NULL ? 1 : 0; } static void TypeRep(TypeExpr *, Dbg_Type *, DbgList **); static void StructEntry(DbgList *p, TagBinder *b, SET_BITMAP sort, int32 size, DbgList **list) { ClassMember *l = tagbindmems_(b); StructElt *elts = NULL; int32 count = 0; StructPos sp; structpos_init(&sp, b); for (; l != 0; l = memcdr_(l)) { structfield(l, sort, &sp); if (memsv_(l)) { /* memsv is 0 for padding bit fields */ StructElt *el = (StructElt *)DbgAlloc(sizeof(StructElt)); cdr_(el) = elts; el->val = sp.woffset; TypeRep(sp.bsize != 0 ? te_int : memtype_(l), &el->type, list); el->name = symname_(memsv_(l)); elts = el; count += 1 + AuxEntryCount(&el->type); } } p->car.Tag.size = size; p->car.Tag.elts.s = (StructElt *)dreverse((List *)elts); p->car.Tag.entries = count; } static void EnumEntry(DbgList *p, TagBinder *b) { BindList *l = tagbindenums_(b); EnumElt *elts = NULL; int32 count = 0; for (; l != NULL; l = l->bindlistcdr, count++) { EnumElt *el = (EnumElt *)DbgAlloc(sizeof(EnumElt)); Binder *elt = l->bindlistcar; cdr_(el) = elts; el->name = symname_(bindsym_(elt)); el->val = bindenumval_(elt); elts = el; } p->car.Tag.entries = count; p->car.Tag.elts.e = (EnumElt *)dreverse((List *)elts); } static DbgList *StructRep(TagBinder *b, int32 size, DbgList **list) { DbgList *p = (DbgList *)b->tagbinddbg; if (p == NULL) { DbgListSort sort = (attributes_(b) & bitoftype_(s_enum)) ? Enum : (attributes_(b) & bitoftype_(s_union)) ? Union : Struct; p = (DbgList*)DbgAlloc(DbgListVarSize(Tag)); p->sort = (attributes_(b) & TB_DEFD) ? sort : (DbgListSort)(sort+S_Undef); p->index = -1; p->car.Tag.elts.e = NULL; if (isgensym(tagbindsym_(b))) { p->car.Tag.named = NO; p->car.Tag.tag.anonindex = anonindex++; } else { p->car.Tag.named = YES; p->car.Tag.tag.name = symname_(tagbindsym_(b)); } cdr_(p) = *list; *list = p; b->tagbinddbg = (int32)p; } else if ((attributes_(b) & TB_DEFD) && (p->sort & S_Undef)) /* Previously forward referenced and now defined */ p->sort = (DbgListSort)(p->sort & ~S_Undef); else return p; if (attributes_(b) & bitoftype_(s_enum)) EnumEntry(p, b); else StructEntry(p, b, attributes_(b) & CLASSBITS, size, list); return p; } #define SetDerivedType(p, n) (((p)->w |= (n) << ((p)->modct*2+4)), (p)->modct++) #define SetBaseType(p, n) ((p)->w |= (n)) static void TypeRep_Struct(TypeExpr *x, Dbg_Type *typep, int tagtype, DbgList **list) { TagBinder *b = typespectagbind_(x); int32 size = attributes_(b) & TB_DEFD ? sizeoftype(x) : 0; typep->tag = StructRep(b, size, list); SetBaseType(typep, tagtype); } static void TypeRep(TypeExpr *x, Dbg_Type *typep, DbgList **list) { int32 dim[4], size = 0; int dimct = 0; typep->modct = 0; typep->w = 0; typep->tag = NULL; for (;; x = typearg_(x)) { x = princtype(x); /* lose intermediate typedefs */ switch (h0_(x)) { case t_content: case t_ref: /* @@@ OK? */ SetDerivedType(typep, DT_PTR); break; case t_subscript: SetDerivedType(typep, DT_ARRAY); if (dimct == 0) size = sizeoftype(x); dim[dimct++] = typesubsize_(x) == NULL ? 1 : evaluate(typesubsize_(x)); break; case t_fnap: SetDerivedType(typep, DT_FCN); break; case s_typespec: { SET_BITMAP m = typespecmap_(x); switch (m & -m) { /* LSB - unsigned32/long etc. are higher */ case bitoftype_(s_char): { int32 mcr = mcrepoftype(x); SetBaseType(typep, (mcr & MCR_SORT_MASK) == MCR_SORT_SIGNED ? T_CHAR : T_UCHAR); goto ExitLoop; } case bitoftype_(s_int): if (m & BITFIELD) syserr(syserr_dbg_bitfield); { int32 mcr = mcrepoftype(x); int32 n = mcr & MCR_SIZE_MASK; SetBaseType(typep, (mcr & MCR_SORT_MASK) == MCR_SORT_SIGNED ? (n == 2 ? T_SHORT : T_INT) : (n == 2 ? T_USHORT : T_UINT)); goto ExitLoop; } case bitoftype_(s_double): SetBaseType(typep, (m & bitoftype_(s_short)) ? T_FLOAT : T_DOUBLE); goto ExitLoop; case bitoftype_(s_enum): TypeRep_Struct(x, typep, T_ENUM, list); goto ExitLoop; case bitoftype_(s_struct): case bitoftype_(s_class): TypeRep_Struct(x, typep, T_STRUCT, list); goto ExitLoop; case bitoftype_(s_union): TypeRep_Struct(x, typep, T_UNION, list); goto ExitLoop; case bitoftype_(s_void): SetBaseType(typep, T_NULL); /* ? no T_VOID */ goto ExitLoop; default: break; } } /* drop through */ default: syserr(syserr_dbg_typerep, (VoidStar)x, (long)typespecmap_(x)); SetBaseType(typep, T_NULL); goto ExitLoop; } } ExitLoop: typep->dimct = dimct; if (dimct == 0) typep->dims = NULL; else { typep->dims = (int32 *)DbgAlloc(((int32)dimct+1)*sizeof(int32)); typep->dims[0] = size; memcpy(&typep->dims[1], &dim[0], dimct*sizeof(int32)); } } static void AddVar(Symstr *name, int sourcepos, int stgclass, int base, int32 addr, TypeExpr *type, int32 undef, DbgList **list) { DbgList *p = (DbgList *)DbgAlloc(DbgListVarSize(Var)); p->sort = (DbgListSort)(Var+undef); p->car.Var.stgclass = stgclass; p->car.Var.sourcepos = sourcepos; p->car.Var.location = addr; p->car.Var.name = name; p->car.Var.section = base; p->cdr = *list; *list = p; TypeRep(type, &p->car.Var.type, list); } void dbg_topvar(Symstr *name, int32 addr, TypeExpr *t, int stgclass, FileLine fl) { if (usrdbg(DBG_PROC)) { int base = N_UNDEF; int stg = (stgclass & DS_REG) ? C_REG : (stgclass & DS_EXT) ? C_EXT: C_STAT; if (stgclass & DS_BSS) base = N_BSS; else if (stgclass & DS_CODE) base = N_TEXT; else if (!(stgclass & DS_REG) && (stgclass & (DS_EXT+DS_UNDEF)) != DS_EXT+DS_UNDEF) base = N_DATA; if (debugging(DEBUG_Q)) cc_msg("top var $r %x @ %.6lx\n", name, stgclass, (long)addr); CheckFile(fl.f); { DbgList **list = stgclass & DS_EXT ? &globdbglist : &statdbglist; int32 undef = stgclass & DS_UNDEF ? S_Undef : 0; if (stgclass != 0 && stg != C_REG) { DbgList *p; for (p = *list ; p != NULL ; p = cdr_(p)) if ( (p->sort == UndefVar || p->sort == Var) && p->car.Var.stgclass == stg && p->car.Var.name == name) { if (!undef) { p->sort = Var; p->car.Var.location = addr; p->car.Var.section = base; p->car.Var.sourcepos = fl.l; } return; } } AddVar(name, fl.l, stg, base, addr, t, undef, list); } } } void dbg_type(Symstr *name, TypeExpr *t, FileLine fl) { /* This only gets called on top-level types */ DbgList *p = (DbgList*) DbgAlloc(DbgListVarSize(Var)); Dbg_Type type; if (debugging(DEBUG_Q)) cc_msg("type $r\n", name); CheckFile(fl.f); TypeRep(t, &type, &globdbglist); if (!isgensym(name)) { p->sort = Type; p->car.Var.name = name; p->car.Var.type = type; p->car.Var.sourcepos = fl.l; p->cdr = globdbglist; globdbglist = p; } } static DbgList *locvars; void dbg_proc(Symstr *name, TypeExpr *t, bool ext, FileLine fl) { if (usrdbg(DBG_ANY)) { DbgList *p = (DbgList*) DbgAlloc(DbgListVarSize(Proc)); if (debugging(DEBUG_Q)) cc_msg("startproc $r\n", name); CheckFile(fl.f); t = princtype(t); p->sort = Proc; if (h0_(t) != t_fnap) syserr(syserr_dbg_proc); TypeRep(t, &p->car.Proc.type, &locdbglist); p->car.Proc.oldstyle = typefnaux_(t).oldstyle; p->car.Proc.sourcepos = fl.l; p->car.Proc.filepos = fl.filepos; p->car.Proc.entryaddr = 0; /* fill in at dbg_enterproc */ p->car.Proc.bodyaddr = 0; /* fill in at dbg_bodyproc */ p->car.Proc.end = 0; /* fill in at dbg_endproc */ p->car.Proc.name = name; p->car.Proc.stgclass = ext ? C_EXT : C_STAT; p->car.Proc.linelist = NULL; p->cdr = locdbglist; /* do this last (typerep above) */ dbglistproc = locdbglist = p; /* so can be filled in */ locvars = NULL; } } void dbg_enterproc(void) { if (usrdbg(DBG_ANY)) { DbgList *p = dbglistproc; if (p == 0 || p->sort != Proc || p->car.Proc.entryaddr != 0) syserr(syserr_dbg_proc1); if (debugging(DEBUG_Q)) cc_msg("enter $r @ %.6lx\n", p->car.Proc.name, (long)codebase); p->car.Proc.entryaddr = codebase; } } /* The following routine records the post-entry codeaddr of a proc */ void dbg_bodyproc(void) { if (usrdbg(DBG_ANY)) { DbgList *p = dbglistproc; if (p == 0 || p->sort != Proc || p->car.Proc.bodyaddr != 0) syserr(syserr_dbg_proc1); if (debugging(DEBUG_Q)) cc_msg("body $r @ %.6lx\n", p->car.Proc.name, (long)(codebase+codep)); p->car.Proc.bodyaddr = codebase+codep; } } void dbg_return(int32 addr) { IGNORE(addr); } void dbg_xendproc(FileLine fl) { if (usrdbg(DBG_ANY)) { DbgList *q = dbglistproc; DbgList *p = (DbgList*) DbgAlloc(DbgListVarSize(EndProc)); if (q == 0 || q->sort != Proc || q->car.Proc.end != 0) syserr(syserr_dbg_proc1); if (debugging(DEBUG_Q)) cc_msg("endproc $r @ %.6lx\n", q->car.Proc.name, (long)(codebase+codep)); q->car.Proc.end = p; p->sort = EndProc; p->car.EndProc.sourcepos = fl.l; p->car.EndProc.endaddr = codebase+codep; p->car.EndProc.fileentry = fl.f; p->cdr = locdbglist; locdbglist = p; dbglistproc = NULL; } } /* dbg_locvar() registers the name and line of a declaration, and internalises * the type. Location info cannot be added until after register allocation. * See also dbg_scope which completes. * (Type internalisation cannot be done then, because by that time the tree * has evaporated). * Also remember that dead code elimination may remove some decls. */ void dbg_locvar(Binder *b, FileLine fl) { Symstr *name = bindsym_(b); if (usrdbg(DBG_VAR)) { if (isgensym(name)) { if (bindstg_(b) & bitofstg_(s_typedef)) { Dbg_Type type; TypeRep(bindtype_(b), &type, &locdbglist); } } else if (!(bindstg_(b) & bitofstg_(s_extern))) { if (debugging(DEBUG_Q)) cc_msg("note loc var $b\n", b); AddVar((Symstr *)b, fl.l, 0, NULL, 0, bindtype_(b), S_Undef, &locvars); } } } static DbgList *FindLocVar(Binder *b) { DbgList *p, **pp = &locvars; for (; (p = *pp) != NULL; pp = &cdr_(p)) if (p->sort == UndefVar && (Binder *)p->car.Var.name == b) { *pp = cdr_(p); return p; } return NULL; } void dbg_locvar1(Binder *b) { Symstr *name = bindsym_(b); int base = N_UNDEF; DbgList *p = FindLocVar(b); int stgclass; int stgclassname; int32 addr = bindaddr_(b); if (p == NULL || p->car.Var.sourcepos == -1) { if (debugging(DEBUG_Q)) cc_msg(" omitted"); return; /* invented variable name (e.g. s_let) */ } cdr_(p) = locdbglist; locdbglist = p; p->sort = Var; p->car.Var.name = name; switch (bindstg_(b) & PRINCSTGBITS) { case bitofstg_(s_typedef): if (debugging(DEBUG_Q)) cc_msg(" <typedef>"); p->sort = Type; return; case bitofstg_(s_static): stgclass = C_HIDDEN, stgclassname = 'S'; base = (bindstg_(b) & u_constdata) ? N_TEXT : (bindstg_(b) & u_bss) ? N_BSS : N_DATA; break; case bitofstg_(s_auto): if (bindxx_(b) != GAP) { stgclass = (addr & BINDADDR_MASK) == BINDADDR_ARG ? C_REGPARM : C_REG; stgclassname = 'R', addr = register_number(bindxx_(b)); } else switch (addr & BINDADDR_MASK) { case BINDADDR_ARG: stgclass = C_ARG, stgclassname = 'A', addr = local_fpaddress(addr); break; case BINDADDR_LOC: stgclass = C_AUTO, stgclassname = 'P', addr = local_fpaddress(addr); break; case 0: /* probably declared but not used case (where addr is still a bindlist) */ p->sort = Ignore; if (bindstg_(b) & b_bindaddrlist) { if (debugging(DEBUG_Q)) cc_msg(" unused - omitted"); return; } /* otherwise, fall into internal error case */ default: syserr(syserr_dbg_table, name, (long)bindstg_(b), (long)addr); return; } break; default: syserr(syserr_dbg_table, name, (long)bindstg_(b), (long)addr); return; } if (debugging(DEBUG_Q)) cc_msg(" %c %lx", stgclassname, (long)addr); p->car.Var.stgclass = stgclass; p->car.Var.location = addr; p->car.Var.section = base; } bool dbg_scope(BindListList *newbll, BindListList *oldbll) { int32 entering = length((List *)newbll) - length((List *)oldbll); if (entering == 0) return NO; if (entering < 0) { BindListList *t = newbll; newbll = oldbll, oldbll = t; } if (length((List *)oldbll) > 0) { BindListList *bll = newbll; DbgList *last = NULL; for (bll = newbll; bll != oldbll; bll = bll->bllcdr) { if (bll == 0) syserr(syserr_dbg_scope); if (bll->bllcar != 0) { DbgList *p = (DbgList *)DbgAlloc(DbgListVarSize(Block)); dbglistscope = p; cdr_(p) = locdbglist; if (entering > 0) { p->sort = BlockStart; p->car.Block.p = dbglistblockstart; dbglistblockstart = p; } else { DbgList *q = dbglistblockstart; p->sort = BlockEnd; p->car.Block.p = NULL; dbglistblockstart = q->car.Block.p; q->car.Block.p = p; } p->car.Block.s.next = last; /* filled in soon by INFOSCOPE */ locdbglist = p; last = p; } } } if (debugging(DEBUG_Q)) cc_msg("scope %ld\n", entering); for (; newbll != oldbll; newbll = newbll->bllcdr) { SynBindList *bl; if (newbll == 0) syserr(syserr_dbg_scope); for (bl = newbll->bllcar; bl; bl = bl->bindlistcdr) { Binder *b = bl->bindlistcar; if (bindstg_(b) & b_dbgbit) continue; /* for this and next line */ bindstg_(b) |= b_dbgbit; /* see end of routine cmt */ if (debugging(DEBUG_Q)) cc_msg(" %s $b", entering>=0 ? "binding" : "unbinding", b); if (entering >= 0) dbg_locvar1(b); if (debugging(DEBUG_Q)) cc_msg("\n"); } } return YES; /* Ask for INFOSCOPE item to get called back more or less immediately */ /* from the local cg (INFOSCOPE item) to fill in the codeaddr */ } /* Dummy procedure not yet properly implemented, included here to keep in */ /* step with dbx.c */ void dbg_commblock(Binder *b, SynBindList *members, FileLine fl) { IGNORE(b); IGNORE(members); IGNORE(fl); } static union { char c[18]; unsigned8 b[18]; unsigned16 h[9]; unsigned32 w[5]; } aux; static void ClearAux() { memset(&aux, 0, 18); } static void SetNextIndex(DbgList *p, int n) { aux.w[3] = (p == NULL) ? 0 : TargetWord(p->index+n); } static void SetSourcePos(int32 n) { aux.h[2] = TargetHalf(n); } static void SetStructSize(DbgList *p) { aux.h[3] = TargetHalf(p->car.Tag.size); } static void SetStructRef(DbgList *p) { aux.w[0] = TargetWord(p->index); SetStructSize(p); } static void *TypeAuxEntry(Dbg_Type *t, int pos) { if (AuxEntryCount(t) == 0) return NULL; ClearAux(); if (t->tag != NULL) SetStructRef(t->tag); if (t->dimct != 0) { int i = 0; for (; i <= t->dimct; i++) aux.h[3+i] = TargetHalf(t->dims[i]); SetSourcePos(pos); } return &aux; } static int32 globindex; typedef enum { ne_all, ne_def, ne_undef } NEType; static void WriteEntries(DbgList *p, NEType flag) { for (; p != NULL; p = cdr_(p)) if (flag == ne_all || (flag == ne_def ? p->sort != UndefVar : p->sort == UndefVar)) switch (p->sort) { default: syserr(syserr_dbg_write, (long)p->sort); break; case File: ClearAux(); { UnparsedName un; fname_parse(p->car.File.name, "c C h H", &un); un.plen = un.vlen = 0; un.vol = un.path = NULL; fname_unparse(&un, FNAME_AS_NAME, aux.c, 15); } obj_stab(".file", p->car.File.next == NULL ? globindex : p->car.File.next->index, N_DEBUG, T_NULL, C_FILE, &aux); break; case Proc: ClearAux(); TypeAuxEntry(&p->car.Proc.type, 0); aux.w[1] = TargetWord(p->car.Proc.end->car.EndProc.endaddr - p->car.Proc.entryaddr); aux.w[2] = TargetWord(p->car.Proc.filepos); aux.h[8] = TargetHalf(p->car.Proc.oldstyle ? 14 : 15); /* Normal arithmetic promotions, 64 bit IEEE fp (what does this mean?) */ SetNextIndex(p->car.Proc.end, 2); obj_stab(symname_(p->car.Proc.name), p->car.Proc.entryaddr, N_TEXT, p->car.Proc.type.w, p->car.Proc.stgclass, &aux); ClearAux(); SetSourcePos(p->car.Proc.sourcepos); SetNextIndex(p->car.Proc.end, 2); obj_stab(".bf", p->car.Proc.bodyaddr, N_TEXT, T_NULL, C_FCN, &aux); break; case EndProc: ClearAux(); SetSourcePos(p->car.EndProc.sourcepos); obj_stab(".ef", p->car.EndProc.endaddr, N_TEXT, T_NULL, C_FCN, &aux); break; case UndefVar: obj_stab(symname_(p->car.Var.name), 0, N_UNDEF, p->car.Var.type.w, C_EXT, TypeAuxEntry(&p->car.Var.type, p->car.Var.sourcepos)); break; case Var: obj_stab(symname_(p->car.Var.name), p->car.Var.location, p->car.Var.section, p->car.Var.type.w, p->car.Var.stgclass, TypeAuxEntry(&p->car.Var.type, p->car.Var.sourcepos)); break; case Type: obj_stab(symname_(p->car.Var.name), 0, N_DEBUG, p->car.Var.type.w, C_TPDEF, TypeAuxEntry(&p->car.Var.type, p->car.Var.sourcepos)); break; case Struct: case Union: case UndefStruct: case UndefUnion: { char b[16]; char *name; int t, cl; if (p->sort == Struct || p->sort == UndefStruct) t = T_STRUCT, cl = C_STRTAG; else t = T_UNION, cl = C_UNTAG; if (p->car.Tag.named) name = p->car.Tag.tag.name; else { sprintf(b, ".%ldfake", p->car.Tag.tag.anonindex); name = b; } ClearAux(); SetStructSize(p); SetNextIndex(cdr_(p), 0); obj_stab(name, 0, N_DEBUG, t, cl, &aux); { StructElt *q = p->car.Tag.elts.s; for (; q != NULL; q = cdr_(q)) obj_stab(q->name, q->val, N_ABS, q->type.w, C_MOS, TypeAuxEntry(&q->type, 0)); } ClearAux(); SetStructRef(p); obj_stab(".eos", p->car.Tag.size, N_ABS, T_NULL, C_EOS, &aux); break; } case Enum: { char b[16]; char *name; if (p->car.Tag.named) name = p->car.Tag.tag.name; else { sprintf(b, ".%ldfake", p->car.Tag.tag.anonindex); name = b; } ClearAux(); SetStructSize(p); SetNextIndex(cdr_(p), 0); obj_stab(name, 0, N_DEBUG, T_ENUM, C_ENTAG, &aux); { EnumElt *q = p->car.Tag.elts.e; for (; q != NULL; q = cdr_(q)) obj_stab(q->name, q->val, N_ABS, T_MOE, C_MOE, NULL); } ClearAux(); SetStructRef(p); obj_stab(".eos", p->car.Tag.size, N_ABS, T_NULL, C_EOS, &aux); break; } case BlockStart: ClearAux(); SetNextIndex(p->car.Block.p, 2); obj_stab(".bb", p->car.Block.s.codeaddr, N_TEXT, T_NULL, C_BLOCK, &aux); break; case BlockEnd: ClearAux(); obj_stab(".eb", p->car.Block.s.codeaddr, N_TEXT, T_NULL, C_BLOCK, &aux); break; } } static void FixDbgList(DbgList *p) { for (; p != NULL; p = cdr_(p)) { if (p->sort == UndefVar) { ExtRef *x = symext_(p->car.Var.name); if (x != NULL && (x->extflags & (xr_defloc+xr_defext))) { p->sort = Var; p->car.Var.location = x->extoffset; p->car.Var.section = x->extflags & xr_bss ? N_BSS : N_DATA; } } if (p->sort == Proc || p->sort == Var || p->sort == UndefVar) { ExtRef *x = symext_(p->car.Var.name); if (x != NULL) x->extflags |= xr_deleted; } } } static void RenumberExtRef(Symstr *sym, int32 index) { ExtRef *x = symext_(sym); if (x != NULL) { if (!(x->extflags & xr_deleted)) syserr("Missed duplicate symbol"); x->extindex = index; } } static int32 NumberEntries(DbgList *p, int32 index, NEType flag) { for (; p != NULL; p = cdr_(p)) { if (flag == ne_all || (flag == ne_def ? p->sort != UndefVar : p->sort == UndefVar)) { p->index = index; switch (p->sort) { case Ignore: break; case Proc: RenumberExtRef(p->car.Proc.name, index); index += 4; break; /* .bf entry too */ case BlockStart: case BlockEnd: case File: case EndProc: index += 2; break; case UndefVar: case Var: RenumberExtRef(p->car.Var.name, index); /* and fall through */ case Type: index += 1 + AuxEntryCount(&p->car.Var.type); break; case Enum: index += 2 + p->car.Tag.entries + 2; break; case UndefUnion: case UndefStruct: case Union: case Struct: { StructElt *q = p->car.Tag.elts.s; index += 4; /* tag + .eos */ for (; q != NULL; q = cdr_(q)) index += 1+AuxEntryCount(&q->type); break; } default: syserr("%d in NumberEntries", p->sort); } } } return index; } static int32 RenumberSyms(ExtRef *x, int32 index, int32 mask, int32 maskedval) { for (; x != NULL; x = x->extcdr) if ((x->extflags & mask) == maskedval) { x->extindex = index++; if (x->extflags & xr_section) index++; } return index; } static int32 dbg_fixup(ExtRef *symlist, int32 index) { /* Mark symbols with entries in symlist also present in a dbglist. If symbols in a dbglist are marked as undefined, but the symlist entry is marked as defined, fix up position and storage class in the dbglist entry (bss and tentatives: maybe someone should call dbg_topvar when the placement finally gets made). Number the symbols in dbglists, and the remaining unmarked symbols in symlist (locdbglist, then defloc things in symlist (should be just sections), then defined things in globdbglist, then defext things in symlist, then undefined things in globdbglist then symlist). Rewrite the index of marked symbols in symlist. */ if (usrdbg(DBG_ANY)) { locdbglist = (DbgList *)dreverse(nconc((List *)statdbglist, (List *)locdbglist)); globdbglist = (DbgList *)dreverse((List *)globdbglist); FixDbgList(locdbglist); FixDbgList(globdbglist); index = NumberEntries(locdbglist, 0, ne_all); globindex = index = RenumberSyms(symlist, index, xr_deleted+xr_defloc+xr_defext, xr_defloc); index = NumberEntries(globdbglist, index, ne_def); index = RenumberSyms(symlist, index, xr_deleted+xr_defloc+xr_defext, xr_defext); index = NumberEntries(globdbglist, index, ne_undef); return RenumberSyms(symlist, index, xr_deleted+xr_defloc+xr_defext, 0); } else return index; } static void dbg_outsymtab() { if (usrdbg(DBG_ANY)) { WriteEntries(locdbglist, ne_all); obj_outsymtab(xr_deleted+xr_defloc+xr_defext, xr_defloc); WriteEntries(globdbglist, ne_def); obj_outsymtab(xr_deleted+xr_defloc+xr_defext, xr_defext); WriteEntries(globdbglist, ne_undef); obj_outsymtab(xr_deleted+xr_defloc+xr_defext, 0); } else obj_outsymtab(0, 0); obj_outstringtab(); } void dbg_init(void) { anonindex = 0; locdbglist = statdbglist = globdbglist = NULL; dbglistfile = dbglistproc = dbglistblockstart = NULL; dbglistscope = NULL; } #endif /* TARGET_HAS_DEBUGGER */ /* end of coffobj.c */
stardot/ncc
cfe/sem.c
/* * sem.c: semantic analysis phase of the C/C++ compiler * Copyright (C) Codemist Ltd, 1988-1992 * Copyright (C) Acorn Computers Ltd., 1988-1990. * Copyright (C) Advanced RISC Machines Limited, 1991-1992. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 167 * Checkin $Date$ * Revising $Author$ */ /* @@@ worry about the type of: const struct { int a[10]; } x; &x.a; */ /* in pcc mode. */ /* New routine 'princtype' which acts like old prunetype for users who */ /* just wish to the 'shape' of a type and not its qualifiers. */ /* AM Aug 88: Overflow during constant reduction (ANSI Dec 88, section */ /* 3.4) is now trapped. It currently gives only a cc_warn message in */ /* spite of it being a 'constraint violation'. This is because AM is */ /* a little fearful of faulting (e.g.) 1<<31, (char)257, -1u, etc. */ /* It may be that these messages are a little aggressive, let's see. */ /* Currently, explicit casts give no warning. */ /* Find all strings of the form '_overflow' to study. */ /* There is also the problem of 'static a = 1 || 1000000*1000000;'. */ /* AM believe the draft spec to be ambiguous here. */ /* Hence the use of cc_ansi_warn not cc_ansi_rerr which sadly deletes */ /* the object file. */ /* Nov 88: Rework FEATURE_SIGNED_CHAR so it is ansi-conformant too. */ /* Nov 88: Rework optional double alignment, see TARGET_ALIGNS_DOUBLES. */ #ifndef _SEM_H #include <string.h> /* for memset and strcmp */ #include "globals.h" #include "sem.h" #include "bind.h" #include "aetree.h" #include "builtin.h" #include "aeops.h" #include "store.h" #include "errors.h" #include "util.h" /* for padsize */ #include "simplify.h" #include "vargen.h" #ifdef PASCAL /*ECN*/ #include "syn.h" /* No comments please, its already under the axe */ #include "lib.h" #include "synbind.h" #include "passem.h" #endif /* and for C-only compilers... */ #define cpp_mkbinaryorop(op,a,b) 0 #define cpp_ptrcast(a,b,c,d,e) 0 #define cpp_ptrtomemcast(a,b,c,d,e) 0 #define cpp_mkcast(op,ep,tr) 0 #define nullptr(cl) 0 #define ovld_resolve_addr(a, t) 0 #define ovld_resolve_addr_2(op, t,l,b) ((Binder *)0) #define exprlist_of_default_args(d, i) ((ExprList *)0) #define pointerkeepnull(ee,e,gen) 0 #define common_pointer_type(op,t1,e1,newe1,t2,e2,newe2,common) 0 #define common_reference_type(op,t1,e1,newe1,t2,e2,newe2,common) 0 #define allowable_boolean_conversion(a) 0 #define call_dependency_type(a,b) 0 #define call_dependency_val(a,b) 0 #define is_comparable_specialization(a,b) 0 #endif /* _SEM_H */ #define exprdotmemfn_(p) arg2_(p) /* Discussion on "int" and "signed int". In most cases these are */ /* identical, hence rather tortuous code in equivtype (find all */ /* occurrences of s_signed below). However, they differ in bitfield */ /* context ("signed" selects signed bitfield, plain implementation */ /* dependent signed/unsigned) and hence typedef context. Hence syn.c */ /* cannot simply normalise so that all int's are signed. */ /* Note similarly "signed short" == short and "signed long" == long. */ /* #define'ing SIGNEDNESS_MATTERS can cause this not to happen. */ /* However, "char", "signed char" and "unsigned char" all differ. */ #define addrsignmap_ (TARGET_ADDRESSES_UNSIGNED ? \ bitoftype_(s_int)|bitoftype_(s_unsigned) : \ bitoftype_(s_int)|bitoftype_(s_signed)) /* The following macro is used to default the signedness for 'plain' */ /* char and 'plain' int bit fields. */ #define issignedchar_(m) ((m) & bitoftype_(s_signed) || \ (feature & FEATURE_SIGNED_CHAR && !((m) & bitoftype_(s_unsigned)))) Expr *errornode; /* memo: re-insert check on fn returning fn!!! */ /* AM aug-88: Allow expansion of offsetof to be compile-time constant. */ /* BIG thing to do soon: get correct op in error message for things like 3[4], !(struct ...). */ /* AM 6-2-87: check args to printf/scanf! */ /* AM 24-6-86: Treat 'float' as 'short double' internally. */ /* forward references */ static Expr *mkassign(AEop op, Expr *a, Expr *b); static Expr *mkaddr(Expr *a); static Expr *mkincdec(AEop op, Expr *a); static Expr *bitfieldvalue(Expr *ebf, SET_BITMAP m, Expr *ewd); #define orig_(p) arg1_(p) #define compl_(p) arg2_(p) /* type-like things... */ extern void typeclash(AEop op) { cc_err(sem_err_typeclash, op); } /* Type manipulation -- these are becoming more of an abstract type. */ /* Exact routine partition in flux. */ #define QUALIFIER_MASK CVBITS TypeExpr *princtype(TypeExpr *t) /* Remove 'typedef's from top of type. Ignore any qualifiers on the */ /* typedef to the type so qualified. */ /* FW: What is the rationale for this? */ { Binder *b; while (isprimtype_(t,s_typedefname)) { if (debugging(DEBUG_TYPE)) cc_msg("Pruning typedef...\n"); b = typespecbind_(t); t = bindtype_(b); } return t; } static SET_BITMAP typedef_qualifiers(TypeExpr *x) { SET_BITMAP q = 0; while (isprimtype_(x, s_typedefname)) { Binder *b = typespecbind_(x); q |= typespecmap_(x) & QUALIFIER_MASK; x = bindtype_(b); } return q; } SET_BITMAP qualifiersoftype(TypeExpr *x) { SET_BITMAP q; while (h0_(x) == t_subscript) x = typearg_(x); q = typedef_qualifiers(x); x = princtype(x); while (h0_(x) == t_subscript) x = typearg_(x); /* AM would like to put typespecmap_ and typeptrmap_ in same place. */ return q | QUALIFIER_MASK & ((h0_(x) == s_typespec || h0_(x) == t_unknown) ? typespecmap_(x) : h0_(x) == t_content || h0_(x) == t_ref || h0_(x) == t_fnap ? typeptrmap_(x) : 0); } SET_BITMAP recursivequalifiers(TypeExpr *x) { SET_BITMAP q = 0; for (;;) { while (h0_(x) == t_subscript) x = typearg_(x); q |= typedef_qualifiers(x); x = princtype(x); while (h0_(x) == t_subscript) x = typearg_(x); if (h0_(x) == t_content || h0_(x) == t_ref) { q |= (QUALIFIER_MASK & typeptrmap_(x)); x = typearg_(x); continue; } else if (h0_(x) == t_fnap) { q |= (QUALIFIER_MASK & typeptrmap_(x)); } else if (h0_(x) == s_typespec) { q |= (QUALIFIER_MASK & typespecmap_(x)); } return q; } } #define qualifier_subset(t1, t2) (qualifiers_lost(t1, t2) == 0) static SET_BITMAP qualifiers_lost(TypeExpr *t1, TypeExpr *t2) { SET_BITMAP m1 = qualifiersoftype(t1), m2 = qualifiersoftype(t2); return m1 & ~m2; } static TypeExpr *mkqualifiedtype_1(TypeExpr *t, SET_BITMAP qualifiers, SET_BITMAP unqualifiers) { TypeExpr *p, *q, *r; if (qualifiers == 0 && unqualifiers == 0 || h0_(t) == t_ovld) return t; /* @@@ AM mumble! */ p = r = NULL; for (;;) { /* should there be a routine to clone top-of-a-type? */ q = h0_(t) == t_fnap ? mkTypeExprfn(t_fnap, typearg_(t), typeptrmap_(t), typefnargs_(t), &typefnaux_(t)) : mk_typeexpr1(h0_(t), typearg_(t), (Expr *)typespecbind_(t)); if (r == NULL) r = q; else typearg_(p) = q; p = q; switch (h0_(q)) { default: syserr(syserr_mkqualifiedtype, h0_(t)); case t_unknown: case s_typespec: /* NB. this may place the type on another typedef */ typespecmap_(q) = (typespecmap_(q) | qualifiers) & ~unqualifiers; return r; case t_content: case t_ref: case t_fnap: /* C++ const (member) functions */ typeptrmap_(q) = (typeptrmap_(q) | qualifiers) & ~unqualifiers; return r; case t_subscript: /* this next line probably indicates that space for a */ /* qualifier map field in an array type would be useful. */ t = typearg_(t); break; } } } extern TypeExpr *mkqualifiedtype(TypeExpr *t, SET_BITMAP qualifiers) { return mkqualifiedtype_1(t, qualifiers, (SET_BITMAP)0); } TypeExpr *prunetype(TypeExpr *t) /* Remove 'typedef's from top of type. Add any qualifiers on the */ /* typedef to the type so qualified -- these are assumed to be */ /* relatively rare (maybe one day re-implement). */ { return mkqualifiedtype(princtype(t), typedef_qualifiers(t)); } bool isvolatile_type(TypeExpr *x) { return (qualifiersoftype(x) & bitoftype_(s_volatile)) != 0; } bool isunaligned_type(TypeExpr *x) { if (qualifiersoftype(x) & bitoftype_(s_unaligned)) return YES; x = princtype(x); if isclasstype_(x) return (tagbindbits_(typespectagbind_(x)) & TB_UNALIGNED) != 0; return NO; } bool pointerfree_type(TypeExpr *t) { t = princtype(t); switch (h0_(t)) { case t_content: case t_ref: return NO; case t_subscript: return pointerfree_type(typearg_(t)); case s_typespec: if (typespecmap_(t) & CLASSBITS) { ClassMember *l = tagbindmems_(typespectagbind_(t)); for (; l != 0; l = memcdr_(l)) if (!pointerfree_type(memtype_(l))) return NO; } default: return YES; } } #define typeisbitfield_(m) (m & BITFIELD) bool isbitfield_type(TypeExpr *t) { t = princtype(t); /* Beware: BITFIELD should never qualify a typedef (syn.c ensures) */ /* (BITFIELD can only occur at the top level in types taken from */ /* struct/unions). Else princtype() risks skipping a 'BITFIELD'. */ return (h0_(t) == s_typespec && (typespecmap_(t) & BITFIELD)); } /* The call to unbitfield_type() replaces a use of 'te_int'. */ TypeExpr *unbitfield_type(TypeExpr *t) { /* Return the corresponding simple type, for a pseudo-cast in */ /* assignment and initialisation, for e.g. implicit cast err/warn. */ if (h0_(t) == s_typespec) { SET_BITMAP m = typespecmap_(t); if (typeisbitfield_(m)) #ifdef ONE_DAY_SOON /* including C++? */ return primtype2_(m & ~BITFIELD, typespectagbind_(t)); #endif return m & bitoftype_(s_enum) ? primtype2_(m & ~BITFIELD, typespectagbind_(t)) : int_islonglong_(m) ? te_llint : te_int; } syserr(syserr_unbitfield, t); return te_int; } static TypeExpr *bf_promotedtype2( SET_BITMAP m, int32 sparebits, TypeExpr *signedtype, TypeExpr *unsignedtype) { if (issignedchar_(m) || (sparebits != 0 && !(feature & FEATURE_PCC))) return signedtype; else return unsignedtype; } /* Merge unbitfield_type() and bf_promotedtype()? */ static TypeExpr *bf_promotedtype(TypeExpr *t, int32 size) { /* caller ensures that 't' is a s_typespec of BITFIELD. */ /* promote: enum bit fields to enum, else int/unsigned int. */ /* Maybe long bit fields (in C++) should promote to long. */ if (h0_(t) == s_typespec) { SET_BITMAP m = typespecmap_(t); if (typeisbitfield_(m)) return (m & bitoftype_(s_enum)) ? primtype2_(m & ~BITFIELD, typespectagbind_(t)) : int_islonglong_(m) ? bf_promotedtype2(m, 8 * sizeof_longlong - size, te_llint, te_ullint) : (m & bitoftype_(s_long)) ? bf_promotedtype2(m, 8 * sizeof_long - size, te_lint, te_ulint) : bf_promotedtype2(m, 8 * sizeof_int - size, te_int, te_uint); } syserr(syserr_bf_promote, t); return te_int; } bool isvoidtype(TypeExpr *t) { t = princtype(t); return (h0_(t) == s_typespec && (typespecmap_(t) & bitoftype_(s_void))); } /* Note: true for 'void*' and 'void*const' but not 'const void*' */ bool isptrtovoidtype(TypeExpr *t) { t = princtype(t); return h0_(t) == t_content && equivtype(typearg_(t), te_void); } static bool indexable(TypeExpr *t) { t = princtype(t); /* can ignore typedef qualifiers. */ return (h0_(t) == t_content /* but not x after 'int A::*x' etc. */ && h0_(princtype(typearg_(t))) != t_coloncolon ); } static bool isptrtomember(TypeExpr *t) { t = princtype(t); /* can ignore typedef qualifiers. */ return (h0_(t) == t_content && h0_(princtype(typearg_(t))) == t_coloncolon); } /* For the two following functions/macros, t must satisfy indexable() */ #define indexee(t) (typearg_(princtype(t))) #define strideofindexee(t) (sizeoftype(indexee(t))) static bool indexer(TypeExpr *t) { /* the type reading routine 'or's the 'int' bit in if we read unsigned/signed/short/long and no honest type. Moreover, we assume 'unary coercions' to be done - so no char/enum. */ t = princtype(t); /* can ignore typedef qualifiers. */ return isprimtypein_(t,bitoftype_(s_int)|bitoftype_(s_bool)); } static bool sameenum(TypeExpr *a, TypeExpr *b) { a = princtype(a), b = princtype(b); return isprimtype_(a,s_enum) && isprimtype_(b,s_enum) && typespectagbind_(a) == typespectagbind_(b); } /* AE-tree oriented things... */ TypeExpr *typeofexpr(Expr *x) { AEop op; TypeExpr *t; switch (op = h0_(x)) { case s_binder: t = bindtype_(exb_(x)); break; case s_member: if (bindparent_(exb_(x)) == NULL) syserr("Orphan member $b", exb_(x)); /* Note that we can't do the next line for t_ovld (in s_binder above). */ t = (TypeExpr *)syn_list3(t_coloncolon, bindtype_(exb_(x)), bindparent_(exb_(x))); break; case s_floatcon: /* perhaps slave all three combinations - or put a type_ field in s_floatcon */ t = exf_(x)->floatlen == bitoftype_(s_double) ? te_double : primtype_(exf_(x)->floatlen); break; case s_int64con: t = (int64map_(x) & bitoftype_(s_unsigned)) ? te_ullint : te_llint; break; case s_string: { int32 n = 0; StringSegList *p; for (p = exs_(x)->strseg; p != 0; p = p->strsegcdr) n += p->strseglen; #ifdef PASCAL /*ECN*/ t = mkArrayType(te_char, mkintconst(te_int, n+1, 0), mkOrdType(bitoftype_(s_int), s_ellipsis, te_int, lit_one, mkintconst(te_int, n, 0)), b_packed); #else t = mk_typeexpr1(t_subscript, te_stringchar, mkintconst(te_int,n+1,0)); #endif } break; #ifdef EXTENSION_UNSIGNED_STRINGS case s_ustring: { int32 n = 0; StringSegList *p; for (p = exs_(x)->strseg; p != 0; p = p->strsegcdr) n += p->strseglen; t = mk_typeexpr1(t_subscript, te_ustringchar, mkintconst(te_int,n+1,0)); } break; #endif case s_wstring: { int32 n = 0; StringSegList *p; for (p = exs_(x)->strseg; p != 0; p = p->strsegcdr) n += p->strseglen; t = mk_typeexpr1(t_subscript, te_wstringchar, mkintconst(te_int, n/sizeof_wchar + 1, 0)); } break; case s_error: /* @@@ remove soon? */ t = te_int; break; /* for sizeof() or sizeof(1.0%2.0) */ #ifdef PASCAL /*ECN*/ case s_set: #endif case s_typespec: case s_integer: t = type_(x); break; default: if (hastypefield_(op)) { t = type_(x); break; } syserr(syserr_typeof, (long)op); t = te_int; break; } /* The clever macro for debugging() means that the next line generates */ /* no code if ENABLE_TYPE is not #defined. */ if (debugging(DEBUG_TYPE)) { eprintf("Type of "); pr_expr(x); eprintf(" is "); pr_typeexpr_nl(t, 0); } return t; } /* @@@ contemplate a routine 'TypeExpr -> AEop' to avoid 2-level switches and make code more representation independent */ SET_BITMAP typeofenumcontainer(TagBinder *tb) { static SET_BITMAP const a[] = { bitoftype_(s_char), bitoftype_(s_short)|bitoftype_(s_int), bitoftype_(s_int), bitoftype_(s_long)|bitoftype_(s_int), bitoftype_(s_unsigned)|bitoftype_(s_char), bitoftype_(s_unsigned)|bitoftype_(s_short)|bitoftype_(s_int), bitoftype_(s_unsigned)|bitoftype_(s_int), bitoftype_(s_unsigned)|bitoftype_(s_long)|bitoftype_(s_int) }; return a[(tagbindbits_(tb) & TB_CONTAINER) >> TB_CONTAINER_SHIFT]; } static int32 alignofclass(TagBinder *b) { int32 n = alignof_struct; if (tagbindbits_(b) & TB_UNALIGNED) return 1; /* Short circuit the code if it can never update 'n': */ if (alignof_max > alignof_struct) { ClassMember *l = tagbindmems_(b); /* This code should never be called when the struct/union is not defined, */ /* but, even if it is no harm will occur as then l==0. (!TB_DEFD) */ /* Note we can safely treat bit field members as non-bit field members. */ for (; l != 0; l = memcdr_(l)) if (is_datamember_(l)) n = max(n, alignoftype(memtype_(l))); } return n; } /* Beware alignoftype(t_ref) == alignoftype(t_content). */ int32 alignoftype(TypeExpr *x) /* Gives mininum alignment (power of 2) for object of type. The current view is given in mip/defaults.h. Arrays get aligned as members (ANSI require). "alignof_double" may be set to 4 or 8 in target.h. Internal contents of structs are always examined, to give the struct the alignment of the most strictly aligned member (or alignof_struct, if that's stricter). Bitfields are treated as requiring the alignment of the type of the member (or its container if the type is an enumeration): in strict ansi mode, always alignof_int, since some signedness of int is the only permitted type. Minimal alignment of alignof_struct (normally 4) means "sizeof(struct {char x}[6])" is normally 24. (But alignof_struct is user-alterable). */ { SET_BITMAP m; Binder *b; switch (h0_(x)) { case s_typespec: m = typespecmap_(x); switch (m & -m) /* LSB - unsigned/long etc. are higher */ { case bitoftype_(s_typedefname): b = typespecbind_(x); return alignoftype(bindtype_(b)); case bitoftype_(s_char): return 1; case bitoftype_(s_enum): m = typeofenumcontainer(typespectagbind_(x)); if (m & bitoftype_(s_char)) return 1; /* drop through */ case bitoftype_(s_bool): case bitoftype_(s_int): return int_decodealign_(m); case bitoftype_(s_double): return m & bitoftype_(s_short) ? alignof_float : m & bitoftype_(s_long) ? alignof_ldble : alignof_double; case bitoftype_(s_struct): case bitoftype_(s_class): case bitoftype_(s_union): return alignofclass(typespectagbind_(x)); case bitoftype_(s_void): /* pure cowardice */ cc_rerr(sem_rerr_sizeof_void); return alignof_int; default: break; } case t_unknown: /* same as te_void */ return alignof_int; default: syserr(syserr_alignoftype, (long)h0_(x), (long)typespecmap_(x)); case t_content: case t_ref: return alignof_ptr; case t_subscript: return alignoftype(typearg_(x)); } } /* NB. this (structfield()) MUST be kept in step with initstaticvar (q.v.). Everyone else (sizeoftype, findfield, dbg_structrep) needing to know about position and size of fields in structures uses this function. */ void structpos_init(StructPos *p, TagBinder *tb) { p->n = p->bitoff = 0; p->padded = NO; /* this initialization is special in that static data mem gets described almost as if it is a s_member. */ p->bsize = 0; /* tb is NULL for call from debug-table generator to handle undefined */ /* structs */ p->nopadding = tb != NULL && (tagbindbits_(tb) & TB_UNALIGNED) != 0; p->endofcontainer = 0; } static int32 sizeofintegraltype(TypeExpr *x, SET_BITMAP m) { switch (m & -m) /* LSB - unsigned/long etc. are higher */ { case bitoftype_(s_char): break; case bitoftype_(s_enum): m = typeofenumcontainer(typespectagbind_(x)); if (m & bitoftype_(s_char)) break; /* drop through */ case bitoftype_(s_bool): case bitoftype_(s_int): return int_decodelength_(m); } return 1; } bool structfield(ClassMember *l, int32 sort, StructPos *p) { /* 2nd arg should probably be a bool (struct/class vs union). */ int32 n = p->n, bitoff = p->bitoff; TypeExpr *te = memtype_(l); p->padded = NO; if (!is_datamember_(l)) return NO; /*if (istypevar(te)) { p->woffset = 0; return YES; }*/ if (isbitfield_type(te)) { /* Bitfields are packed into objects having the type of the member */ /* (for enumerations, the type of the enumeration's container). */ /* In strict ANSI C, this is always (some sign of) int. */ int32 k = membits_(l); int32 sizeofcontainer = sizeofintegraltype(te, typespecmap_(te)); int32 szmask = sizeofcontainer*8 - 1; int32 boff; if (bitoff == 0) { int32 oldn = n; n = padsize(n, alignof_member); /* min member alignment */ if (oldn != n) p->padded = YES; p->endofcontainer = n + sizeofcontainer; if ((n & (alignof_int-1)) != 0) { /* though a field's container may start on any boundary, */ /* the structpos representation requires bit offset within */ /* the containing int. */ bitoff = (n & (alignof_int-1)) * 8; n &= ~(alignof_int-1); } } /* A zero-sized bifield in ANSI mode says "pack no more here". */ /* (We now interpret as "no more into this container", rather than */ /* "no more into this word"). */ /* We ignore this directive if nothing has yet been packed. */ if (k == 0 && bitoff > 0) { int32 endofcontainer = (bitoff + szmask) & ~szmask; k = endofcontainer - bitoff; } /* If this bitfield would overflow its container, start a new one */ if (((bitoff & szmask) + k) > (szmask+1)) { int32 end; bitoff = (bitoff + szmask + 1) & ~szmask; if (bitoff >= 8 * sizeof_int) { int32 words = bitoff / (8 * sizeof_int); n += words * sizeof_int; bitoff -= words * (8 * sizeof_int); } end = n + (bitoff/8) + sizeofcontainer; /* If we're packing from the opposite end of the container, */ /* containers can't be allowed to overlap */ if (feature & FEATURE_REVERSE_BITFIELDS) end = p->endofcontainer; if (end > p->endofcontainer) p->endofcontainer = end; } else { int32 wordbits = sizeofcontainer == sizeof_longlong ? 8 * sizeof_longlong : 8 * sizeof_int; if (bitoff >= wordbits) { n += (bitoff / (8 * sizeof_int)) * sizeof_int; bitoff = 0; p->endofcontainer = n + sizeofcontainer; } } if (feature & FEATURE_REVERSE_BITFIELDS) { /* Pack from the opposite end of the container */ int32 endcontaineroffset = (p->endofcontainer & (alignof_int-1)) * 8; int32 containerbits = sizeofcontainer * 8; int32 startcontaineroffset = endcontaineroffset - containerbits; boff = endcontaineroffset - (bitoff - startcontaineroffset + k); } else boff = bitoff; p->woffset = n, p->boffset = boff, p->bsize = k, p->typesize = 0; if (sort != bitoftype_(s_union)) bitoff += k; } else { if (bitoff != 0) { /* The unused part of a trailing bitfield container is allowed */ /* to overlap non-bitfield fields */ if (feature & FEATURE_REVERSE_BITFIELDS) n = p->endofcontainer; else n += (bitoff+7) / 8; bitoff = 0; } #ifdef PASCAL /*ECN*/ n = l->offset; #else if (!p->nopadding) { int32 oldn = n; n = padsize(n, alignof_member); /* min member alignment */ n = padsize(n, alignoftype(te)); if (oldn != n) p->padded = YES; } #endif p->woffset = n, p->boffset = 0, p->bsize = 0; if ((attributes_(l) & CB_BASE) && tagbindmems_(typespectagbind_(princtype(te))) == NULL) p->typesize = 0; else p->typesize = sizeoftype(te); if (sort != bitoftype_(s_union)) n += p->typesize; } p->n = n, p->bitoff = bitoff; return YES; } int32 sizeofclass(TagBinder *b, bool *padded) { ClassMember *l; int32 n = 0; bool pad = NO; if (tagbindbits_(b) & TB_OPAQUE) cc_rerr(sem_rerr_sizeof_opaque, b); if (tagbindbits_(b) & TB_SIZECACHED) { int32 n = b->cachedsize; if (n < 0) { if (padded != NULL) *padded = YES; return -n; } else { if (padded != NULL) *padded = NO; return n; } } if (!(tagbindbits_(b) & (TB_DEFD|TB_UNDEFMSG))) { cc_err(sem_err_sizeof_struct, b); tagbindbits_(b) |= TB_UNDEFMSG; } if (tagbindbits_(b) & bitoftype_(s_union)) { for (l = tagbindmems_(b); l != 0; l = memcdr_(l)) if (is_datamemberoranon_(l)) { TypeExpr *te = memtype_(l); if (isbitfield_type(te)) n = max(n, sizeofintegraltype(te, typespecmap_(te))); else n = max(n, sizeoftype(te)); memwoff_(l) = 0; } /* Use the next line for C too? OK by ANSI. */ if (n == 0) n = 1; /* empty C++ union. */ n = padsize(n, alignofclass(b)); /* often alignof_struct */ } else { StructPos p; structpos_init(&p, b); for (l = tagbindmems_(b); l != 0; l = memcdr_(l)) { if (!structfield(l, bitoftype_(s_struct), &p)) { if (is_datamemberoranon_(l)) memwoff_(l) = p.woffset; continue; } memboff_(l) = (uint8)p.boffset; membits_(l) = (uint8)p.bsize; memwoff_(l) = p.woffset; pad = pad | p.padded; if (p.n > n) n = p.n; } #ifdef PASCAL /*ECN*/ p.n = n; #endif if (p.bitoff != 0) p.n = p.endofcontainer; /* Use the next line for C too? OK by ANSI. */ if (p.n == 0) p.n = 1; /* empty C++ struct. */ if (p.nopadding) n = p.n; else { n = padsize(p.n, alignofclass(b)); /* often alignof_struct */ if (n != p.n) pad = YES; if (pad && padded != NULL) *padded = YES; } } if (tagbindbits_(b) & TB_DEFD) { b->cachedsize = pad ? -n : n; tagbindbits_(b) |= TB_SIZECACHED; } return n; } /* Beware sizeoftype(t_ref) == sizeoftype(t_content). */ /* syn.c(cpp_sizeoftype) takes care of C++ rules about sizeof. */ int32 sizeoftypenotepadding(TypeExpr *x, bool *padded) { SET_BITMAP m; switch (h0_(x)) { case t_unknown: /* treated as void but without the diagnostic. */ return 1; case s_typespec: m = typespecmap_(x); if (m & BITFIELD) cc_rerr(sem_rerr_sizeof_bitfield); switch (m & -m) /* LSB - unsigned/long etc. are higher */ { case bitoftype_(s_char): if (m & BITFIELD) cc_rerr(sem_rerr_sizeof_bitfield); return 1; case bitoftype_(s_enum): if (m & BITFIELD) cc_rerr(sem_rerr_sizeof_bitfield); m = typeofenumcontainer(typespectagbind_(x)); if (m & bitoftype_(s_char)) return 1; /* drop through */ case bitoftype_(s_bool): case bitoftype_(s_int): if (m & BITFIELD) cc_rerr(sem_rerr_sizeof_bitfield); return int_decodelength_(m); case bitoftype_(s_double): return (m & bitoftype_(s_short)) ? sizeof_float : (m & bitoftype_(s_long)) ? sizeof_ldble : sizeof_double; case bitoftype_(s_struct): case bitoftype_(s_class): case bitoftype_(s_union): return sizeofclass(typespectagbind_(x), padded); case bitoftype_(s_typedefname): return sizeoftype(bindtype_(typespecbind_(x))); case bitoftype_(s_void): cc_rerr(sem_rerr_sizeof_void); return 1; default: break; } default: syserr(syserr_sizeoftype, (long)h0_(x), (long)typespecmap_(x)); case t_subscript: { int32 n = sizeoftype(typearg_(x)); if (typesubsize_(x)) n *= (h0_(typesubsize_(x)) == s_binder && is_template_arg_binder(typesubsize_(x))) ? 1 : evaluate(typesubsize_(x)); /* pretensions, don't matter cos there is no template obj anyway. */ else typesubsize_(x) = globalize_int(1), cc_rerr(sem_rerr_sizeof_array); return n; } case t_coloncolon: /* For int A::*x; ... x+1; ... and sizeof(B::b). */ return sizeoftype(typearg_(x)); case t_ovld: case t_fnap: cc_rerr(sem_rerr_sizeof_function); /* drop through */ case t_content: case t_ref: return sizeof_ptr; } } bool sizeoftypelegal(TypeExpr *x) { SET_BITMAP m; x = princtype(x); switch (h0_(x)) { case s_typespec: m = typespecmap_(x); if (m & BITFIELD) return NO; switch (m & -m) /* LSB - unsigned/long etc. are higher */ { case bitoftype_(s_struct): case bitoftype_(s_class): case bitoftype_(s_union): if (tagbindbits_(typespectagbind_(x)) & (TB_DEFD|TB_UNDEFMSG)) return YES; break; case bitoftype_(s_void): break; default: return YES; } break; case t_subscript: if (typesubsize_(x) != 0 && h0_(typesubsize_(x)) != s_binder) return YES; break; case t_coloncolon: /* For int A::*x; ... x+1; ... and sizeof(B::b). */ return sizeoftypelegal(typearg_(x)); case t_ovld: case t_fnap: break; case t_content: case t_ref: return YES; } return NO; } /* the C rules on type equivalence mean that equivtype does not have to worry about circularity */ /* equivtype notionally returns a boolean, but the true case is separated */ /* into result 2, identical (LISP equal) and result 1, merely equivalent. */ /* BEWARE: now (maybe temporarily) differing qualifiers on fn args can */ /* still give result 2. */ /* AM: @@@ In the long term, equivtype should also compute the unified */ /* type of t1 and t2, but beware store lifetime use, and cacheing. */ static int equivtype_4(TypeExpr *t1, TypeExpr *t2, SET_BITMAP m1, SET_BITMAP m2, bool widenformals) { int sofar = 2; for (;; (t1 = typearg_(t1), t2 = typearg_(t2))) { m1 |= typedef_qualifiers(t1), m2 |= typedef_qualifiers(t2); t1 = princtype(t1), t2 = princtype(t2); if (h0_(t1) != h0_(t2)) return 0; switch (h0_(t1)) { case s_typespec: m1 |= typespecmap_(t1), m2 |= typespecmap_(t2); #define CLASSORSTRUCT (bitoftype_(s_class)|bitoftype_(s_struct)) if (m1 & CLASSORSTRUCT) m1 |= CLASSORSTRUCT; if (m2 & CLASSORSTRUCT) m2 |= CLASSORSTRUCT; #undef CLASSORSTRUCT /* this next line does a lot: 1) it checks same basic type (struct/unsigned int/etc) via set equality on type specifiers. 2) it tests pointer equality on tag binders. 3) it relies on typespecbind_() being 0 for simple types */ return (m1 == m2 && (typespecbind_(t1) == typespecbind_(t2) || (LanguageIsCPlusPlus && is_comparable_specialization(t1, t2)))) ? sofar : #ifndef SIGNEDNESS_MATTERS /* the 1 result here is slight paranoia re typedefs */ (m1 & m2 & bitoftype_(s_int) && (m1 & ~bitoftype_(s_signed)) == (m2 & ~bitoftype_(s_signed))) ? 1 : #endif 0; case t_coloncolon: if (typespecbind_(t1) != typespecbind_(t2)) return 0; continue; /* now check elt types, with qualifiers */ case t_unknown: return (t1 == t2 && m1 == m2) ? 2 : 1; case t_content: case t_ref: /* two pointers match if they have the same const/volatile */ /* attribute and point to compatible types. Ditto refs. */ #ifdef PASCAL /*ECN*/ if (t1 == t2) return 2; #endif if ((m1|typeptrmap_(t1)) != (m2|typeptrmap_(t2))) return 0; m1 = m2 = 0; continue; case t_subscript: /* should check sizes (if any) match */ { Expr *e1 = typesubsize_(t1), *e2 = typesubsize_(t2); /* masquerade as open arrays */ if (e1 && h0_(e1) == s_binder) e1 = NULL; if (e2 && h0_(e2) == s_binder) e2 = NULL; if (e1 != 0 && e2 != 0) { if (evaluate(e1) != evaluate(e2)) return 0; } else { if (e1 != e2) sofar = 1; } } continue; /* now check elt types, with qualifiers */ case t_fnap: /* Latest ANSI draft (Dec 88) is finally precise about type */ /* equivalence. Note that allowing () to be equivalent to non-() */ /* things makes 'equivtype' not an equivalence relation!!! */ { /* check arg types match... */ FormTypeList *d1 = typefnargs_(t1), *d2 = typefnargs_(t2); bool old1 = (t1->fnaux.oldstyle != 0); bool old2 = (t2->fnaux.oldstyle != 0); if (maxargs_(t1) != maxargs_(t2) || minargs_(t1) != minargs_(t2) || t1->fnaux.variad != t2->fnaux.variad || t1->fnaux.flags != t2->fnaux.flags || t1->fnaux.oldstyle != t2->fnaux.oldstyle) sofar = 1; /* The next 3 lines ensure "int f(); int f(x) char x; {}" is OK, but */ /* that "int f(); int f(char x) {}" and "int f(); int f(int x,...) {}" */ /* give the required ANSI errors. */ if (fntypeisvariadic(t1) != fntypeisvariadic(t2)) return 0; if (d1 == 0 && maxargs_(t1) == 999) d1 = d2, old1 = 1; if (d2 == 0 && maxargs_(t2) == 999) d2 = d1, old2 = 1; while (d1 && d2) { TypeExpr *ft1 = d1->fttype, *ft2 = d2->fttype; /* Function and array types were promoted to pointers by rd_declrhslist */ if (old1 || widenformals) ft1 = promoted_formaltype(ft1); if (old2 || widenformals) #if 0 { TypeExpr *promoted = promoted_formaltype(ft2); if (old2 && !old1 && (feature & FEATURE_PCC) && !qualfree_equivtype(ft1, promoted)) cc_pccwarn("type $t doesn't match promoted type", ft1); else ft2 = promoted; } #else ft2 = promoted_formaltype(ft2); #endif switch (qualfree_equivtype(ft1, ft2)) { default: return 0; case 1: sofar = 1; case 2: d1 = cdr_(d1), d2 = cdr_(d2); } } /* * Check either both fn's have or omit '...' */ if (d1 != d2) return 0; } if ((m1|typeptrmap_(t1)) != (m2|typeptrmap_(t2))) return 0; m1 = m2 = 0; continue; /* now check results */ default: syserr(syserr_equivtype, (long)h0_(t1)); return 0; } } } /* equivtype notionally returns a boolean, but the true case is separated */ /* into result 2, identical (LISP equal) and result 1, merely equivalent. */ /* BEWARE: now (maybe temporarily) differing qualifiers on fn args can */ /* still give result 2. */ int equivtype(TypeExpr *t1, TypeExpr *t2) { return equivtype_4(t1, t2, 0, 0, NO); } /* @@@ I wish the use of this was documented! */ int widened_equivtype(TypeExpr *t1, TypeExpr *t2) { return equivtype_4(t1, t2, 0, 0, !(feature & FEATURE_FUSSY) && !(config & CONFIG_UNWIDENED_NARROW_ARGS)); } /* BEWARE: there is a sordid little ambiguity/accident in the Dec 88 */ /* ANSI draft (see equality ops (ignoring qualifiers) and type */ /* qualifiers on array types) concerned with t1 (or t2) being a const */ /* qualified array via typedef) and the other an array of const. */ int qualfree_equivtype(TypeExpr *t1, TypeExpr *t2) { /* forcing ON all qualifiers effectively ignores them. */ return equivtype_4(t1, t2, QUALIFIER_MASK, QUALIFIER_MASK, NO)/* != 0*/; /* HCM see above (case t_fnap of equivtype_4) why normalising the */ /* result to 0/1 isn't a good idea */ } static FormTypeList *compositetypelist(FormTypeList *d1, FormTypeList *d2, bool old1, bool old2); /* t3 = compositetype(t1,t2) forms the composite type of t1 and t2 */ /* into t3, if t1 and t2 are compatible(equivtype), otherwise it */ /* returns 0. See ANSI draft. */ /* In implementation, the routine tries to return t1 if this is the */ /* composite type to save store. */ /* 'u' is set if top-level qualifiers are merely to be unioned. */ /* 'm1' and 'm2' keep up with typedefs which have been pruned -- note */ /* the behaviour for arrays (t_subscript). */ static TypeExpr *compositetype_5(TypeExpr *t1, TypeExpr *t2, SET_BITMAP m1, SET_BITMAP m2, bool u) { TypeExpr *t3; if (t1 == t2 && m1 == m2) return t1; m1 |= typedef_qualifiers(t1), m2 |= typedef_qualifiers(t2); t1 = princtype(t1), t2 = princtype(t2); if (h0_(t1) != h0_(t2)) return 0; switch (h0_(t1)) { case s_typespec: m1 |= typespecmap_(t1), m2 |= typespecmap_(t2); if (u) m1 |= m2 & QUALIFIER_MASK, m2 |= m1 & QUALIFIER_MASK; /* this next line does a lot: 1) it checks same basic type (struct/unsigned int/etc) via set equality on type specifiers. 2) it tests pointer equality on tag binders. 3) it relies on typespecbind_() being 0 for simple types */ if (!(m1 == m2 && typespecbind_(t1) == typespecbind_(t2) #ifndef SIGNEDNESS_MATTERS || (m1 & m2 & bitoftype_(s_int) && ((m1^m2) & ~bitoftype_(s_signed)) == 0) #endif )) return 0; return #ifdef REUSE typespecmap_(t1) == m1 ? t1 : typespecmap_(t2) == m1 ? t2 : #endif primtype2_(m1, typespecbind_(t1)); case t_content: case t_ref: m1 |= typeptrmap_(t1), m2 |= typeptrmap_(t2); if (u) m1 |= m2 & QUALIFIER_MASK, m2 |= m1 & QUALIFIER_MASK; if (m1 != m2) return 0; t3 = compositetype_5(typearg_(t1),typearg_(t2),0,0,0); return t3 == 0 ? 0 : #ifdef REUSE t3 == typearg_(t1) && m1 == typeptrmap_(t1) ? t1 : #endif mk_typeexpr1(h0_(t1), typearg_(t1), (Expr *)(IPtr)m1); case t_subscript: { Expr *e1 = typesubsize_(t1), *e2 = typesubsize_(t2), *e3; if (e1 && h0_(e1) == s_binder) e1 = NULL; if (e2 && h0_(e2) == s_binder) e2 = NULL; if (e1 != 0 && e2 != 0) { if (evaluate(e1) != evaluate(e2)) return 0; } e3 = e1 ? e1 : e2; t3 = compositetype_5(typearg_(t1),typearg_(t2),m1,m2,u); return t3 == 0 ? 0 : #ifdef REUSE t3 == typearg_(t1) && e3 == e1 && m1 == 0 ? t1 : #endif mk_typeexpr1(t_subscript, typearg_(t1), (Expr *)e3); } case t_fnap: { TypeExprFnAux s; FormTypeList *d1 = typefnargs_(t1), *d2 = typefnargs_(t2), *d3; bool old1 = (t1->fnaux.oldstyle != 0); bool old2 = (t2->fnaux.oldstyle != 0); int32 max1 = maxargs_(t1), max2 = maxargs_(t2), max3 = max1; m1 |= typeptrmap_(t1), m2 |= typeptrmap_(t2); if (u) m1 |= m2 & QUALIFIER_MASK, m2 |= m1 & QUALIFIER_MASK; if (m1 != m2) return 0; /* The code here mirrors that in equivtype(). */ if (fntypeisvariadic(t1) != fntypeisvariadic(t2)) return 0; if (d1 == 0 && max1 == 999) d1 = d2, old1 = 1, max3 = max2; if (d2 == 0 && max2 == 999) d2 = d1, old2 = 1, max3 = max1; if (d1 == 0 && d2 == 0) d3 = 0; else { d3 = compositetypelist(d1,d2,old1,old2); if (d3 == 0) return 0; } t3 = compositetype_5(typearg_(t1),typearg_(t2),0,0,0); return t3 == 0 ? 0 : #ifdef REUSE /* t3 == typearg_(t1) && d3 == d1 && ... ? t1 : */ #endif mkTypeExprfn(t_fnap, t3, m1, d3, packTypeExprFnAux(s, (int)length((List *)d3), /* vestige */ (int)max3, 0, /* variad: not special */ 0, /* oldstyle: new */ 0 /* flags: none */ )); } default: syserr(syserr_compositetype, (long)h0_(t1)); return 0; } } static TypeExpr *qualunion_compositetype(TypeExpr *t1, TypeExpr *t2) { return compositetype_5(t1,t2,0,0,1); } static FormTypeList *compositetypelist(FormTypeList *d1, FormTypeList *d2, bool old1, bool old2) { if (d1==0 || d2==0) return 0; { TypeExpr *ft1 = d1->fttype, *ft2 = d2->fttype, *tc; FormTypeList *d3; /* Function and array types were promoted to pointers by rd_declrhslist */ if (old1) ft1 = promoted_formaltype(ft1); if (old2) ft2 = promoted_formaltype(ft2); tc = qualunion_compositetype(ft1, ft2); if (tc == 0) return 0; d3 = mkFormTypeList(0, d1->ftname, tc, d1->ftdefault ? d1->ftdefault : d2->ftdefault); if (cdr_(d1) != 0 || cdr_(d2) != 0) { FormTypeList *d4 = compositetypelist(cdr_(d1), cdr_(d2), old1, old2); if (d4 == 0) return 0; cdr_(d3) = d4; } return d3; } } /* lubtype() and friends return a type if OK, or give an error message and return 0. Worry that they are still rather ragged. Note that 'the usual unary coercions' omit 'char' and (possibly) float. BEWARE: result type is ASSUMED to be princtype'd by caller. Since result is an r-value qualifiers are irrelevant. */ static TypeExpr *lubtype(AEop op, TypeExpr *t1, TypeExpr *t2) /* Take care of 'the usual coercions' for e.g. s_times. Relations are done separately, as are the pointer cases of s_plus */ { TypeExpr *x1 = princtype(t1), *x2 = princtype(t2); SET_BITMAP m1 = typespecmap_(x1), m2 = typespecmap_(x2); if (h0_(x1) == s_typespec && h0_(x2) == s_typespec && (m1 & ARITHTYPEBITS) != 0 && (m2 & ARITHTYPEBITS) != 0) { if ((m1 | m2) & bitoftype_(s_double)) { if (!floatableop_(op)) /* % << >> etc. */ { typeclash(op); return 0; } /* The 2 next lines fix a bug in pre-1.60a versions whereby */ /* (long)op(double) was incorrectly treated as (long double). */ if (is_longdouble_(m1) || is_longdouble_(m2)) return te_ldble; if (is_double_(m1) || is_double_(m2)) return te_double; /* the next line is an ANSI draft (May 86) feature. In the PCC case coerceunary would have ensured that any such arguments would have already been coerced to double */ return te_float; } /* the next line is an ANSI special case */ if (op == s_leftshift || op == s_rightshift) return x1; if ((m1 | m2) & bitoftype_(s_long)) { int32 l1 = int_decodelength_(m1), l2 = int_decodelength_(m2); if (l1 == l2) { /* Both operands the same size (at least long): result type */ /* is unsigned if either operand is, else signed */ if ((m1 | m2) & bitoftype_(s_unsigned)) return l1 == sizeof_long ? te_ulint : te_ullint; else return l1 == sizeof_long ? te_lint : te_llint; } /* One operand is longer than the other, the longer operand */ /* is at least long. ANSI rule says the result is unsigned */ /* if the longer operand is, else signed (regardless of the */ /* signedness of the other operand) */ /* shouldn't the PCC rule say if either operand is unsigned, */ /* so is the result? The old (pre-longlong) code didn't */ { int32 l = l1; SET_BITMAP m = m1; if (l2 > l1) { l = l2; m = m2; } if (m & bitoftype_(s_unsigned)) return l == sizeof_long ? te_ulint : te_ullint; else return l == sizeof_long ? te_lint : te_llint; } #if 0 /* @@@ save for possible later warn on <unsigned>op<signed> */ /* as recommended to implementers by ANSI. */ >>>> if ((m1^m2) & bitoftype_(s_unsigned) && >>>> (op == s_div || op == s_rem || /* s_rightshift done above */ >>>> op == s_less || op == s_lessequal || >>>> op == s_greater || op == s_greaterequal)) >>>> /* This warning combats AM (and others?) getting confused */ >>>> /* that "-1L < 5U" is true. NO longer true (Oct 88). */ >>>> cc_warn(sem_warn_unsigned, op); #endif } if ((m1 | m2) & bitoftype_(s_unsigned)) return te_uint; return te_int; /* only case left */ } /* If one of them is a type var, it does not matter what we return. */ if (istypevar(x1) || istypevar(x2)) return x1; /* Apr 92: some old error recovery retired here... */ typeclash(op); return 0; } /* patch up for special treatment of types of formal parameters at defn */ TypeExpr *modify_formaltype(TypeExpr *t) { TypeExpr *t1 = princtype(t); switch (h0_(t1)) { case t_fnap: /* turn f() to (*f)() */ return ptrtotype_(t); case t_subscript: /* turn a[] to *a */ /* We also turn a const array (only via typedef) into a */ /* pointer to const components. Beware, ANSI is unclear. */ return ptrtotype_(mkqualifiedtype(typearg_(t1), typedef_qualifiers(t))); default: return t; } } /* patch up for special treatment of argument types for overloading */ TypeExpr *modify_actualtype(TypeExpr *t, const Expr *e) { TypeExpr *t1 = princtype(t); IGNORE(e); switch (h0_(t1)) { case s_typespec: if (typespecmap_(t1) & BITFIELD) /* should this add "unsigned" to plain 'short', 'int' and 'long'? draft is unclear --sad */ return primtype2_(typespecmap_(t1) & ~BITFIELD, typespectagbind_(t1)); else return t; case t_fnap: /* turn f() to (*f)() */ return ptrtotype_(t); case t_subscript: /* turn a[] to *a */ /* We also turn a const array (only via typedef) into a */ /* pointer to const components. Beware, ANSI is unclear. */ return ptrtotype_(mkqualifiedtype(typearg_(t1), typedef_qualifiers(t))); default: return t; } } /* For safety w.r.t. prototype and non-prototype forms, we pass all short ints/chars and floats as repectively ints and doubles and do callee narrowing. */ TypeExpr *promoted_formaltype(TypeExpr *t) { TypeExpr *t1 = princtype(t); /* can ignore typedef qualifiers? */ if (h0_(t1) == s_typespec) { SET_BITMAP m1 = typespecmap_(t1); if (is_float_(m1)) return te_double; /* Should FEATURE_PCC do anything here re unsigned preserving? */ if (m1 & bitoftype_(s_char)) /* turn 'char' to 'int'. */ return te_int; if (m1 & bitoftype_(s_int)) /* turn 'short' to 'int'. */ return int_isshort_(m1) ? (sizeof_short==sizeof_int && m1 & bitoftype_(s_unsigned) ? te_uint:te_int) : t; return t; } return t; } TypeExpr *widen_formaltype(TypeExpr *t) { return (config & CONFIG_UNWIDENED_NARROW_ARGS) ? t : promoted_formaltype(t); } /* printf/scanf format checker... (belongs in a separate file?) */ typedef enum { FMT_INT, FMT_LINT, FMT_LLINT, FMT_FLT, FMT_PTR } FmtSort; static void fmt1chk(char *buf, int bufp, Expr *arg, FmtSort sort, int argindex) { TypeExpr *t = princtype(typeofexpr(arg)); switch (h0_(t)) { case t_content: if (sort == FMT_PTR) return; break; case s_typespec: { SET_BITMAP m = typespecmap_(t); if ((m & bitoftype_(s_int) && sort == (FmtSort) /* cast to silence gcc */ (int_islonglong_(m) ? FMT_LLINT : (m & bitoftype_(s_long)) ? FMT_LINT: FMT_INT)) /* In C enums coerceunary() to ints. We suppress this, so that C++ is */ /* easy (and so that we can warn as ANSI suggest, but we need to allow */ /* printf("%d", enumconst) in C (although not C++? -- unclear). */ /* See also the uses of COERCE_ARG in mkfnap()/coerceunary. */ || ( !(feature & FEATURE_CPP) ? ((m & bitoftype_(s_enum)) && sort == FMT_INT) : 0 ) || ((m & bitoftype_(s_double)) && sort == FMT_FLT)) return; } break; } cc_warn(sem_warn_format_type, t, (int)bufp, argindex, buf); } #ifdef STRING_COMPRESSION static unsigned short int compression_info[128] = { 0x6520, 0x7468, 0x7320, 0x696e, 0x2081, 0x6420, 0x7420, 0x616e, 0x6572, 0x6f6e, 0x6f72, 0x656e, 0x8480, 0x6172, 0x7265, 0x7469, 0x6585, 0x616c, 0x6982, 0x6f6d, 0x8367, 0x746f, 0x6669, 0x7920, 0x6573, 0x6f66, 0x6120, 0x2c20, 0x7374, 0x8f89, 0x6174, 0x6368, 0x6582, 0x2020, 0x6563, 0x6f75, 0x6393, 0x656c, 0x8a20, 0x7488, 0x8785, 0x8764, 0x9420, 0x6163, 0x8180, 0x616d, 0x6564, 0xa46d, 0x966c, 0x9520, 0x6578, 0x5468, 0x6c20, 0x7769, 0x726f, 0x7365, 0x6465, 0x6162, 0x6c69, 0x756c, 0x7573, 0x6469, 0x9920, 0x756d, 0x8820, 0x668a, 0xb581, 0x7368, 0x7369, 0x8465, 0x6c6f, 0x7370, 0x6e6f, 0x7768, 0x8d80, 0x7572, 0x6d61, 0x9d20, 0x8b86, 0xb96c, 0x8720, 0x6974, 0x8320, 0x5c73, 0xb380, 0x2ea1, 0x6182, 0x8b74, 0x756e, 0x708e, 0x6280, 0x6f6c, 0x7375, 0x8b20, 0xafa9, 0x6173, 0x9873, 0x9f20, 0x70b6, 0x7574, 0x7691, 0xafa8, 0x7293, 0x6ead, 0x8e63, 0x66a6, 0x9120, 0x6167, 0x652e, 0x6986, 0x998c, 0x8d67, 0x4966, 0x6f70, 0x696c, 0x6574, 0xb866, 0xc3a5, 0x6389, 0xb080, 0x6186, 0x656d, 0x9062, 0xe475, 0x6164, 0xa269, 0x6c97, 0x66e6 }; #define REPEAT_CH 29 #define REPEAT_SP 30 #define LITERAL_CHAR 31 static bool compress_fmt(String *fmt) { StringSegList *z; char *s; int i, j, l; unsigned k; int ba, bb; int c; if (var_cc_private_flags & 32768) return 0; for (z = fmt->strseg; z; z = z->strsegcdr) { s = z->strsegbase; l = z->strseglen; for (j = 0 ; j < l;) { c = s[j]; k = j + 1; while (k < l && c == s[k]) k++; if (k - j > 3 || (c == ' ' && k - j > 2)) { s[j++] = (c == ' ') ? REPEAT_SP : REPEAT_CH; s[j] = k - j; j++; if (c != ' ') s[j++] = c; memcpy(&s[j], &s[k], l-k); l -= k-j; } else j++; } z->strseglen = l; } for (z = fmt->strseg; z; z = z->strsegcdr) { s = z->strsegbase; l = z->strseglen; for (i = 0; i < 128; i++) { k = compression_info[i]; ba = k >> 8; bb = k & 0xff; for (j = 1; j < l; j++) { if (s[j-1] == '%') { do { c = s[j]; j++; if (c == '%' || c == 'c' || c == 'd' || c == 'e' || c == 'f' || c == 'g' || c == 'i' || c == 'n' || c == 'o' || c == 'p' || c == 's' || c == 'u' || c == 'x') break; } while (j < l); } else if (s[j-1] == ba && s[j] == bb) { s[j-1] = i+128; l -= 1; memcpy(&s[j], &s[j+1], l-j); } } } z->strseglen = l; } return 1; } #endif static bool fmtchk(String *fmt, ExprList *l, int32 flavour, int fmtindex) { /* flavour=1 => s/f/printf, flavour=2 => s/f/scanf - see stdio.h pragma */ /* fmtindex = argument number of the format string argument */ /* returns TRUE if no floating point will be used & printf case */ StringSegList *z; int state = 0; int nformals = 0, nactuals = fmtindex; bool no_fp_conversions = (flavour == 1); char buf[20]; int bufp = 1; /* 0..20 */ FmtSort xint = FMT_INT; for (z = fmt->strseg; z!=NULL; z = z->strsegcdr) { char *s = z->strsegbase; int32 len = z->strseglen; while (len-- > 0) { int ch = char_untranslation(*s++); #ifndef NO_SELF_CHECKS /* The following lines augment printf checks to cover cc_err, syserr &c */ /* via #pragma -v3 present in mip/globals.h. */ /* #define'ing NO_SELF_CHECKS disables this and saves about 100 bytes. */ if (ch == '$' && flavour == 3 && state == 0) { /* the next line is ugly because it assumes string not split */ if (char_untranslation(*s) != 'l') /* 'l' => use curlex */ { nformals++; if (l != NULL) nactuals++, l = cdr_(l); } } else #endif if (ch == '%') bufp=1, buf[0]=ch, state = state==0 ? 1 : 0, xint = FMT_INT; else if (state != 0) switch ((bufp<20 ? buf[bufp++] = ch:0), ch) { case '*': if (flavour==2) { state = 9; break; } nformals++; if (l) { fmt1chk(buf, bufp, exprcar_(l), FMT_INT, ++nactuals); l = cdr_(l); } break; case '.': break; case '+': case '-': case ' ': case '#': state = state==1 ? 2 : 99; break; case 'l': if (xint == FMT_LINT) xint = FMT_LLINT; else xint = FMT_LINT; /* drop through */ case 'h': case 'L': /* not treated properly yet */ state = state < 5 ? 5 : 99; break; case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': case 'c': if (state == 9) { state = 0; break; } /* scanf suppressed */ nformals++; if (l != NULL) { fmt1chk(buf, bufp, exprcar_(l), flavour==2 ? FMT_PTR : ch=='c' ? FMT_INT:xint, ++nactuals); l = cdr_(l); } state = 0; break; case 'f': case 'e': case 'E': case 'g': case 'G': no_fp_conversions = 0; if (state == 9) { state = 0; break; } /* scanf suppressed */ nformals++; if (l != NULL) { fmt1chk(buf, bufp, exprcar_(l), flavour==2 ? FMT_PTR:FMT_FLT, ++nactuals); l = cdr_(l); } state = 0; break; case 's': case 'p': case 'n': if (state == 9) { state = 0; break; } /* scanf suppressed */ nformals++; if (l != NULL) { fmt1chk(buf, bufp, exprcar_(l), FMT_PTR, ++nactuals); l = cdr_(l); } state = 0; break; case '[': if (state == 9) { state = 0; break; } /* scanf suppressed */ if (flavour==2) /* scanf only */ { /* check well-formed one day */ nformals++; if (l != NULL) { fmt1chk(buf, bufp, exprcar_(l), FMT_PTR, ++nactuals); l = cdr_(l); } state = 0; break; } /* else drop through */ default: if ('0'<=ch && ch<='9') break; cc_warn(sem_warn_bad_format, (int)ch); state = 0; break; } } } if (state != 0) cc_warn(sem_warn_incomplete_format); nactuals += length(l) - fmtindex; if (nactuals != nformals) switch (nformals) { case 0: cc_warn(sem_warn_format_nargs_0, (long)nactuals); break; case 1: cc_warn(sem_warn_format_nargs_1,(long)nactuals); break; default: cc_warn(sem_warn_format_nargs_n, (long)nformals, (long)nactuals); break; } return no_fp_conversions; } static Expr *formatcheck(Expr *e, ExprList *l, FormTypeList *d, int32 flavour) { Expr *fmt = NULL; ExprList *ll = l; int fmtindex = 0; #ifdef STRING_COMPRESSION bool no_fp; bool compress; #endif for (; d != NULL && ll != NULL; d = cdr_(d), ll = cdr_(ll)) { fmt = exprcar_(ll); fmtindex++; } if (d == NULL && fmt != NULL) { for (;;) { switch (h0_(fmt)) { case s_invisible: fmt = compl_(fmt); continue; case s_cast: case s_addrof: fmt = arg1_(fmt); continue; #ifdef STRING_COMPRESSION case s_string: no_fp = fmtchk(exs_(fmt), ll, flavour, fmtindex); /* Here we had a printf, sprintf or fprintf where the format string was */ /* a literal string that showed that no floating point conversions would */ /* be required. Convert to a call to _printf, _sprintf or _fprintf, which */ /* are restricted (smaller) versions of the relevant library functions. */ /* NB that this conversion is enabled by a #pragma present in <stdio.h> */ /* and so will not confuse users who avoid #pragma and who redefine */ /* their own printf etc without the benefit of the standard header file. */ /* The following test gives false (hence no "else syserr()") for calls */ /* like (**printf)("hi"); we could catch this, but not really worth it. */ if (h0_(e) == s_invisible && h0_(orig_(e)) == s_binder) { Symstr *fname = bindsym_(exb_(orig_(e))); /* @@@ Why be paranoid to avoid sharing the sim.printf(s_addrof)?? */ /* Can simplify() corrupt otherwise? */ /* Review the names 'printf' for C++ name munging too. */ compress = (flavour == 1 && compress_fmt(exs_(fmt))); if (compress || no_fp) { if (fname == sim.yprintf) { if (compress) e = mkaddr(arg1_(no_fp ? sim.xprintf_z : sim.yprintf_z)); else e = mkaddr(arg1_(sim.xprintf)); } else if (fname == sim.yfprintf) { if (compress) e = mkaddr(arg1_(no_fp ? sim.xfprintf_z : sim.yfprintf_z)); else e = mkaddr(arg1_(sim.xfprintf)); } else if (fname == sim.ysprintf) { if (compress) e = mkaddr(arg1_(no_fp ? sim.xsprintf_z : sim.ysprintf_z)); else e = mkaddr(arg1_(sim.xsprintf)); } } /* this is a valid drop through place, for */ /* scanf, eprintf (norcroft internal) &c. */ } break; #else case s_string: if (fmtchk(exs_(fmt), ll, flavour, fmtindex)) /* Here we had a printf, sprintf or fprintf where the format string was */ /* a literal string that showed that no floating point conversions would */ /* be required. Convert to a call to _printf, _sprintf or _fprintf, which */ /* are restricted (smaller) versions of the relevant library functions. */ /* NB that this conversion is enabled by a #pragma present in <stdio.h> */ /* and so will not confuse users who avoid #pragma and who redefine */ /* their own printf etc without the benefit of the standard header file. */ /* The following test gives false (hence no "else syserr()") for calls */ /* like (**printf)("hi"); we could catch this, but not really worth it. */ { if (h0_(e) == s_invisible && h0_(orig_(e)) == s_binder) { Symstr *fname = bindsym_(exb_(orig_(e))); /* @@@ Why be paranoid to avoid sharing the sim.printf(s_addrof)?? */ /* Can simplify() corrupt otherwise? */ /* Review the names 'printf' for C++ name munging too. */ if (fname == sim.yprintf) e = mkaddr(arg1_(sim.xprintf)); else if (fname == sim.yfprintf) e = mkaddr(arg1_(sim.xfprintf)); else if (fname == sim.ysprintf) e = mkaddr(arg1_(sim.xsprintf)); /* this is a valid drop through place, for */ /* scanf, eprintf (norcroft internal) &c. */ } } break; #endif /* * The warning message generated here will arise only if the -fussy -ansi * switches are set and indicates that a printf/scanf has been given where * the a format that is not a literal string and so which can not be checked * for validity by the compiler. It is also necessary in this case to * link to the version of printf (etc) that supports floating point * conversions even in cases where store could have been saved by using * the integer-only version. */ default: if (1<=flavour && flavour<=3 && (feature & (FEATURE_PCC|FEATURE_FUSSY)) == FEATURE_FUSSY) cc_warn(sem_warn_uncheckable_format); break; } break; } } return e; } /* l-value like stuff ... */ /* The need for skip_invisible is largely because of the nastiness */ /* of storing information about the sort of field selection (bitfield */ /* or C++ member fn) in the s_dot node, which can be protected by */ /* an s_invisible (e.g. when 'this->a' is written just as 'a'). */ Expr *skip_invisible(Expr *e) { for (;;) if (h0_(e) == s_invisible) e = compl_(e); else if (h0_(e) == s_evalerror) e = arg1_(e); else return e; } Expr *skip_invisible_or_cast(Expr *e) { for (;;) if (h0_(e) == s_invisible) e = compl_(e); else if (h0_(e) == s_evalerror) e = arg1_(e); else if (h0_(e) == s_cast) e = arg1_(e); else return e; } #define allowvolatile 1 #define allowcontents 2 #define allowpostinc 4 static bool isverysimplelvalue(Expr *e, int flags) { while (h0_(e) == s_dot) e = arg1_(e); /* x.a.b is simple if x is ... */ /* and lvalues do not have casts */ if ((flags & allowcontents) && h0_(e) == s_content) e = arg1_(e); if (h0_(e) == s_binder) return (flags & allowvolatile) || !isvolatile_type(bindtype_(exb_(e))); else if (h0_(e) == s_content && h0_(arg1_(e)) == s_integer) return (flags & allowvolatile) || !isvolatile_type(typearg_(princtype(type_(arg1_(e))))); else if ((flags & allowpostinc) && h0_(e) == s_displace) return isverysimplelvalue(arg1_(e), 0); else return NO; } static bool issimplevalue_i(Expr *e, int flags) { AEop op; e = skip_invisible_or_cast(e); op = h0_(e); return op == s_integer || op == s_int64con || isverysimplelvalue(e, flags) || (op == s_addrof && isverysimplelvalue(skip_invisible_or_cast(arg1_(e)), flags | allowcontents)) || ( (op == s_times || op == s_plus || op == s_minus || op == s_div || op == s_rem || op == s_leftshift || op == s_rightshift || op == s_and) && issimplevalue_i(arg1_(e), flags) && issimplevalue_i(arg2_(e), flags)) || ( (op == s_neg || op == s_bitnot || op == s_boolnot) && issimplevalue_i(arg1_(e), flags)); } bool issimplevalue(Expr *e) /* @@@ should be static! */ { return issimplevalue_i(e, 0); } static bool issimplelvalue_i(Expr *e, int flags) { while (h0_(e) == s_dot) e = skip_invisible_or_cast(arg1_(e)); if (isverysimplelvalue(e, allowvolatile)) return YES; else if (h0_(e) == s_content) { e = skip_invisible_or_cast(arg1_(e)); if ( isverysimplelvalue(e, flags) || ( (h0_(e) == s_plus || h0_(e) == s_minus) && issimplevalue_i(arg1_(e), flags) && issimplevalue_i(arg2_(e), flags) ) ) return YES; } return NO; } bool issimplelvalue(Expr *e) /* @@@ should be static! */ { return issimplelvalue_i(e, 0); } static Expr *RemovePostincs(Expr *e, Expr **incs) { switch h0_(e) { case s_integer: case s_binder: return e; case s_displace: { Expr *inc = mk_expr2(s_assign, type_(e), arg1_(e), arg2_(e)); *incs = (*incs == 0) ? inc : mkbinary(s_comma, *incs, inc); return arg1_(e); } case s_cast: case s_content: case s_addrof: { Expr *a1 = skip_invisible(arg1_(e)); Expr *newa1 = RemovePostincs(a1, incs); return (a1 == newa1) ? e: mk_expr1(h0_(e), type_(e), newa1); } case s_dot: /* s_arrow gone? */ { Expr *a1 = skip_invisible(arg1_(e)); Expr *newa1 = RemovePostincs(a1, incs); return (a1 == newa1) ? e: mk_exprwdot(s_dot, type_(e), newa1, exprdotoff_(e)); } case s_times: case s_div: case s_rem: case s_leftshift: case s_rightshift: case s_and: case s_plus: case s_minus: { Expr *a1 = skip_invisible(arg1_(e)), *a2 = skip_invisible(arg2_(e)); Expr *newa1 = RemovePostincs(a1, incs), *newa2 = RemovePostincs(a2, incs); return (a1 == newa1 && a2 == newa2) ? e : mk_expr2(h0_(e), type_(e), newa1, newa2); } /* @@@ AM: I am not convinced by these routines and even less convinced */ /* that they should appear here in sem. simplify.c must be better. */ case s_dotstar: /* s_arrowstar gone? */ default: pr_expr(e); syserr("help"); return e; } } /* Expression AE tree node creators and associated functions */ Expr *mkintconst(TypeExpr *te, int32 n, Expr *e) { /* Assumes a te_int in case of a t_unknown. */ return mk_expr2(s_integer, (istypevar(te))? te_int : te, (Expr *)(IPtr)n, e); } static Expr *mkinvisible(TypeExpr *t, Expr *olde, Expr *newe) /* The purpose of s_invisible nodes in the tree is to compile one thing */ /* whilst retaining the original expression for error messages. */ /* Thus ++x can compile as x=x+1 but produce an error about ++ in &++x. */ /* @@@ beware: most calls guard with oldop != newop && newop != s_error */ { /* The next line may be useful one day... */ /* if (h0_(newe) == s_error) return errornode; */ /* but we'd have to remove argument 't'. */ /* s_integer nodes have a special invisible representation: */ if (h0_(newe) == s_integer) return mkintconst(t, intval_(newe), olde); /* how about: if (h0_(newe) == h0_(olde)) return newe; ?? */ return mk_expr2(s_invisible, t, olde, newe); } /* ensurelvalue() the is the lvalue checking (and coercing, for C++ */ /* t_ref's) routine analogous to coerceunary() which coerces and checks */ /* rvalues. */ /* It has two phases -- first it must check from the type info */ /* that e is not a array, function or other 'const' type. */ /* However, note that & can still be applied to such things. */ /* This is the difference between lvalue and modifiable lvalue. */ /* Note also that in PCC given 'int a[10]' then &a has type (int *), the */ /* same as 'a' in expression context, whereas ANSI say it is 'int (*)[10]). */ /* which is more uniform (and always puts a * on the type). */ /* The ANSI choice reduces confusion in multi-dimensional arrays. */ /* The following example may help: * struct { int r[7], s[7] } x; * f() { printf("%d\n", &x.s - &x.r); * printf("%d\n", x.s - x.r); } * under ANSI prints 1 then 7, under PCC 7 then 7. */ /* Secondly it must check that the expression really can be an lvalue -- */ /* care must be taken for things like (e.a.b.c). */ /* It currently either returns its arg unchanged, or errornode. LIE C++ */ /* In C++ (LanguageIsCPlusPlus) it converts refs to indirections... */ /* /* but not all callers are fixed to use this properly yet.. */ Expr *ensurelvalue(Expr *e, AEop op) { Expr *x; if ((h0_(e) == s_binder || h0_(e) == s_member && op != s_addrof) && attributes_(exb_(e)) & CB_ANON) e = mkfieldselector(s_dot, (Expr *)realbinder_(exb_(e)), (ClassMember *)bindsym_(exb_(e))); /* The s_addrof/s_member case is done in mkaddr (q.v.). */ if (h0_(e) == s_error) return errornode; { TypeExpr *t = princtype(typeofexpr(e)); if (h0_(t) == t_ref) { TypeExpr *t2 = typearg_(t); e = mkinvisible(t2, e, mk_expr1(s_content,t2,e)); /* map a ref to a implicit content thereby losing t_ref. */ /* maybe we should use a form of coerceunary? */ /* @@@ recall [ES,p138,l-1] suggests t2 may be fn/array! */ } } { TypeExpr *t = typeofexpr(e); while (h0_(t) == t_coloncolon) t = typearg_(t); if (op != s_addrof && op != s_init && (qualifiersoftype(t) & bitoftype_(s_const))) cc_rerr(sem_rerr_assign_const, e); if (op == s_addrof && isbitfield_type(t)) { cc_err(sem_err_bitfield_address); return errornode; } t = princtype(t); if (h0_(t) == t_subscript || h0_(t) == t_fnap || h0_(t) == t_ovld) { if (op != s_addrof) { cc_err(sem_err_lvalue, e); return errornode; } /* This code catches things like &(a.b) where "struct {int b[4];} a" */ /* but, oh misfortune, that is just what happens inside the macro */ /* for offsetof(). Ah well. */ if (feature & FEATURE_PCC) cc_warn(sem_warn_addr_array, e); /* remember &(f().m) with m an array member is OK! */ } } for (x = e;;) switch (h0_(x)) { case s_member: /* Always valid as member -- there are no enumconst s_member's */ /* (s_binder used) or register members. */ /* Maybe could fix the implicit 'this' here though. */ return e; case s_binder: { Binder *b = exb_(x); if (isenumconst_(b)) /* will always be seen via a s_integer nodes */ { cc_err(sem_err_lvalue1, b); return errornode; } /* make sure it's not a nullbinder */ if (bindsym_(b) != NULL && !(bindstg_(b) & ~u_referenced)) { cc_err(sem_err_template_nontype_storage, b); return errornode; } if (op == s_addrof) { if (bindstg_(b) & bitofstg_(s_register)) { /* In spite of the real PCC giving a hard error, */ /* for taking a reg var address (or at least */ /* generating bad code); PCC mode gives a */ /* (suppressible) warning! Makefiles beware. */ if (!LanguageIsCPlusPlus) cc_pccwarn(sem_rerr_addr_regvar, b); bindstg_(b) &= ~bitofstg_(s_register); } if (bindstg_(b) & b_globalregvar) { cc_err(sem_err_addr_globalvar, b); return errornode; } bindstg_(b) |= b_addrof; if ((bindstg_(b) & u_constdata) && !(bindstg_(b) & b_generated)) vg_generate_deferred_const(b); if (debugging(DEBUG_TYPE)) cc_msg("addrof $b\n", b); } return e; } case_s_any_string /* &"abc" seems legal */ case s_subscript: case s_arrow: case s_content: return e; case s_comma: /* CPlusPlus only, introduced for side-effects*/ if (LanguageIsCPlusPlus) { x = arg2_(x); break; } else goto defaultcase; case s_dot: case s_qualdot: if (h0_(type_(x)) == t_ovld) /* exprdotmemfn */ x = exprdotmemfn_(x); else x = arg1_(x); break; case s_arrowstar: /* don't believe [ES,p71,l-1]! */ return e; case s_dotstar: /* don't believe [ES,p71,l-1]! */ x = arg1_(x); break; case s_assign: if (LanguageIsCPlusPlus) x = arg1_(x); else goto defaultcase; break; case s_invisible: #if !defined(ensurelvalue_s_invisible) #define ensurelvalue_s_invisible (void)0; #endif ensurelvalue_s_invisible return ((h0_(ensurelvalue(orig_(x), op)) == s_error) ? errornode : e); break; case s_integer: if (intorig_(x) != 0) /* i.e. if previously simplified */ { x = intorig_(x); break; /* only to give correct error message */ } /* drop through */ defaultcase: default: /* The next line could improve s_integer to s_boolean/s_character. */ /* see the cases in mkvoided(). */ if (!istypevar(typeofexpr(x))) cc_err(sem_err_lvalue2, h0_(x)); return errornode; case s_cond: /* needs fixing */ if (!LanguageIsCPlusPlus) cc_rerr(sem_err_lvalue2, h0_(x)); /* But otherwise treat as C++ */ { Expr *e1 = arg2_(x); Expr *e2 = arg3_(x); while (h0_(e1) == s_cast) e1 = arg1_(e1); while (h0_(e2) == s_cast) e2 = arg1_(e2); if (ensurelvalue(e1, s_addrof) == errornode || ensurelvalue(e2, s_addrof) == errornode) return errornode; else return e; } case s_cast: /* @@@ LDS: I hope this all works... */ /* Casts in l-values get special error fixup code since pcc allows. The fix */ /* is ugly: If the context is ++ or -- (pre- or post) then the cast expr */ /* will later have its address taken, so here we lie about the operator to */ /* force b_addrof in any binders recursively encountered... */ /* AM: bug here: (float)x = 1; syserrs. */ cc_pccwarn(sem_rerr_lcast); if (feature & FEATURE_PCC) { if (monadneedslvalue_(op)) op = s_addrof; return ((h0_(ensurelvalue(arg1_(x), op)) == s_error) ? errornode : e); } else return errornode; } } Expr *mk1fnap(Expr *fn, ExprList *args) { TypeExpr *t = princtype(typeofexpr(fn)); /* typedefs irrelevant */ /* @@@ someone is also paranoid here about sharing of &sim.fns. */ /* No sense in an invisible node when the whole functioon call wasn't */ /* what was written. */ fn = mk_expr1(s_addrof, ptrtotype_(t), fn); return mk_expr2(s_fnap, typearg_(t), fn, (Expr *)args); } /* The following routine tidies up pre-existing code, later improve for */ /* other lengths of floating point. */ static void fltrep_to_widest(DbleBin *dest, FloatCon *src) { /* Consider extending this interface for long double > double. */ if (sizeof_double == 4 || sizeof_float < sizeof_double && src->floatlen & bitoftype_(s_short)) fltrep_widen(&src->floatbin.fb, dest); else flt_move(dest, &src->floatbin.db); } static FloatCon *fltrep_from_widest( DbleBin *src, SET_BITMAP flag, char *floatstr) { /* Consider extending this interface for long double > double. */ /* Binary representation is definitive, but keep any text form. */ FloatCon *m = real_of_string(floatstr ? floatstr : "<expr>", 0); m->floatlen = flag; if (sizeof_double == 4 || sizeof_float < sizeof_double && flag & bitoftype_(s_short)) { int status = fltrep_narrow(src, &m->floatbin.fb); if (status > flt_ok) flt_report_error(status); } else flt_move(&m->floatbin.db, src); return m; } #define mk_expr2_ptr(op,t,a,b) trydiadreduce(mk_expr2(op,t,a,b),addrsignmap_) #define isboolean_(op) ((op)==s_andand || (op)==s_oror) static bool isknownzero(Expr *e) { e = skip_invisible_or_cast(e); return (h0_(e) == s_integer && intval_(e) == 0) || (h0_(e) == s_int64con && int64val_(e).i.lo == 0 && int64val_(e).i.hi == 0); } static bool isunsignedtypespec(SET_BITMAP m) { return ((m & bitoftype_(s_unsigned)) || ((m & -m) == bitoftype_(s_char) && !(m & bitoftype_(s_signed)) && !(feature & FEATURE_SIGNED_CHAR))); } static bool iswidenedunsigned(Expr *e) /*/* this doesn't notice unsigned bitfields yet */ { int32 origwidth; TypeExpr *t = princtype(typeofexpr(e)); if (!isintegraltype_(t)) return false; origwidth = sizeoftype(t); if (origwidth == 1) return false; for (;;) if (h0_(e) == s_invisible) e = compl_(e); else if (h0_(e) == s_evalerror) e = arg1_(e); else if (h0_(e) == s_cast) { e = arg1_(e); t = princtype(typeofexpr(e)); if (!isintegraltype_(t)) return false; if (isunsignedtypespec(typespecmap_(t)) && sizeoftype(t) < origwidth) return true; } else { t = princtype(typeofexpr(e)); break; } return isintegraltype_(t) && isunsignedtypespec(typespecmap_(t)) && sizeoftype(t) < origwidth; } static Expr *MarkError(Expr *e, Expr *errorexpr, msg_t msg) { /* We now never produce either errors or warnings from within constant */ /* folding. Instead, we save in a s_evalerror node the identity of the */ /* message we would have produced, and leave the caller to generate it */ /* (as an error if it's a constant expression, else as a warning) */ if (errorexpr == NULL) return e; return mk_expr3(s_evalerror, typeofexpr(e), e, errorexpr, (Expr *)msg); } static Expr *trydiadreduce(Expr *c, SET_BITMAP flag) { AEop op = h0_(c); Expr *a = arg1_(c), *b = arg2_(c); Expr *errorexpr = NULL; msg_t errormsg = NULL; if (h0_(a) == s_evalerror) { errorexpr = arg2_(a); errormsg = (msg_t)arg3_(a); a = arg1_(a); } if (h0_(b) == s_evalerror) { errorexpr = arg2_(b); errormsg = (msg_t)arg3_(b); b = arg1_(b); } /* h0_(b) == s_int64con has already been turned into h0_(b) == s_integer */ /* by mkbinary */ if ((op == s_leftshift || op == s_rightshift) && h0_(b) == s_integer) { uint32 n = intval_(b); if (n >= (uint32)(8 * int_decodelength_(flag))) /* see ANSI spec, valid shifts are 0..31 */ if (errorexpr == NULL) { errormsg = sem_errwarn_bad_shift; errorexpr = c; } if (n == 0 && h0_(a) != s_integer) /* int case reduced below */ /* the s_invisible node allows detection of "(x<<0)=1" lvalue error */ return mkinvisible(type_(c), c, a); } if ((op == s_div || op == s_rem) && isknownzero(b)) { int32 n = intval_(b); if (n == 0 && errorexpr == NULL) { errormsg = sem_errwarn_divrem_0; errorexpr = c; } } /* The rationale here is that unsigned values are in the range 0, 1, .. */ /* and so a proper discrimination for counters is either n==0 vs. n!=0 */ /* or n==0 vs. n>0. Anything that might suggest that negative values */ /* might exist is WRONG, thus n<0, n<=0, n>=0, 0<=n, 0>n, 0>=n will all */ /* lead to diagnostics here. */ if (isinequality_(op)) { if (((flag & bitoftype_(s_unsigned)) || iswidenedunsigned(a)) && isknownzero(b)) { /* n op 0 */ if (op == s_less) { errormsg = sem_errwarn_ucomp_0_false; errorexpr = c; } else if (op == s_greaterequal) { errormsg = sem_errwarn_ucomp_0_true; errorexpr = c; } else if (op == s_lessequal) { errormsg = sem_errwarn_ucomp_0; errorexpr = c; } } else if (((flag & bitoftype_(s_unsigned)) || iswidenedunsigned(b)) && isknownzero(a)) { /* 0 op n */ if (op == s_greater) { errormsg = sem_errwarn_ucomp_0_false; errorexpr = c; } else if (op == s_lessequal) { errormsg = sem_errwarn_ucomp_0_true; errorexpr = c; } else if (op == s_greaterequal) { errormsg = sem_errwarn_ucomp_0; errorexpr = c; } } } /* The following two lines reduce (e.g.) (2 || 1/0) to 1. Similar code */ /* exists in mkcond() (q.v.). @@@ However, it would seem that they can */ /* contravene the ANSI draft in that they also reduce */ /* int x[(2 || (0,1))] to int x[1], which silently misses a constraint */ /* violation that the comma operator shall not appear in const exprs. */ /* Similarly x[2 || f()]. AM thinks the ANSI draft is a mess here. */ /* Note: mktest() has transformed (e.g.) (3.4 || e) to (3.4!=0 || e). */ if (op == s_oror && h0_(a) == s_integer && intval_(a) != 0) return MarkError(mkintconst(type_(c),1,c), errorexpr, errormsg); if (op == s_andand && h0_(a) == s_integer && intval_(a) == 0) return MarkError(mkintconst(type_(c),0,c), errorexpr, errormsg); if (h0_(a) == s_integer && h0_(b) == s_integer && (flag & bitoftype_(s_unsigned))) { unsigned32 m = intval_(a), n = intval_(b), r; bool ok = YES; /* * All this is HORRID if I have a 64 bit machine and I happen to have * allowed unsigned32 to be a 64 bit datatype. */ m = just32bits_(m); n = just32bits_(n); /* force to 32 bits if unsigned32 is 64 bits wide */ switch (op) { case s_plus: r = just32bits_(m+n); ok = r>=m && r>=n; break; case s_minus: r = just32bits_(m-n); ok = r<=m; break; case s_times: r = just32bits_(m*n); ok = m==0 || r/m==n; break; case s_div: if (n==0) return c; r = m/n; break; case s_rem: if (n==0) return c; r = m%n; break; case s_power: return c; case s_and: r = m&n; break; case s_or: r = m|n; break; case s_xor: r = m^n; break; case s_andand: r = m&&n; break; case s_oror: r = m||n; break; case s_leftshift: r = just32bits_(m<<n); ok = (r>>n) == m; break; case s_rightshift: r = m>>n; break; case s_equalequal: r = m==n; break; case s_notequal: r = m!=n; break; case s_less: r = m<n; break; case s_lessequal: r = m<=n; break; case s_greater: r = m>n; break; case s_greaterequal:r = m>=n; break; default: syserr(syserr_trydiadicreduce, (long)op); return c; } r = widen32bitint_(r); if (sizeof_int == 2) { if (!(flag & bitoftype_(s_long)) && (r & 0xffff0000)) r &= 0x0000ffff, ok = NO; } if (!ok && errorexpr == NULL) { errormsg = sem_errwarn_udiad_overflow; errorexpr = c; } return MarkError(mkintconst(type_(c),r,c), /* always has a type_ field */ errorexpr, errormsg); } if (h0_(a) == s_integer && h0_(b) == s_integer) { int32 m = intval_(a), n = intval_(b), r; bool ok = YES; /* @@@ The next lines assume that host 'int' overflow wraps round silently. */ switch (op) { case s_plus: r = m+n; r = widen32bitint_(r); ok = (m^n) < 0 || (m|n|r) >= 0 || (m&n&r) < 0; break; case s_minus: r = m-n; r = widen32bitint_(r); ok = (n>=0 ? r<=m : r>m); break; case s_times: r = m*n; r = widen32bitint_(r); ok = m==0 || n==0 || (m^n^r) >= 0 && r/m == n; break; case s_div: if (n==0) return c; /* The only case where division can give overflow is when the greatest */ /* possible negative number is divided by -1. I.e. iff n,m,r all -ve. */ if (m == ~0x7fffffff && n == -1) r = m, ok = 0; else r = m/n, ok = 1; break; /* Interesting ANSI question: what should effect of */ /* (signed)0x80000000%-1 be? Mathematically 0, but maybe the division */ /* overflowed and so we got a trap. See if ANSI boobed! */ case s_rem: if (n==0) return c; r = m%n; break; case s_power: return c; case s_and: r = m&n; break; case s_or: r = m|n; break; case s_xor: r = m^n; break; case s_andand: r = m&&n; break; case s_oror: r = m||n; break; case s_leftshift: r = m<<n; r = widen32bitint_(r); ok = signed_rightshift_(r,n)==m; break; case s_rightshift: r = TARGET_RIGHTSHIFT(m,n); break; case s_equalequal: r = m==n; break; case s_notequal: r = m!=n; break; case s_less: r = m<n; break; case s_lessequal: r = m<=n; break; case s_greater: r = m>n; break; case s_greaterequal:r = m>=n; break; default: syserr(syserr_trydiadicreduce1, (long)op); return c; } r = widen32bitint_(r); if (sizeof_int == 2) { if (!(flag & bitoftype_(s_long)) && r != (int16)r) r = (int16)r, ok = NO; } if (!ok && errorexpr == NULL) { errormsg = sem_errwarn_diad_overflow; errorexpr = c; } return MarkError(mkintconst(type_(c),r,c), errorexpr, errormsg); } if ((h0_(a) == s_integer || h0_(a) == s_int64con) && (h0_(b) == s_integer || h0_(b) == s_int64con) && (flag & bitoftype_(s_unsigned))) { uint64 av, bv, rv, tv; I64_Status ok = i64_ok; uint32 n; if (h0_(a) == s_integer) I64_IToU(&av, intval_(a)); else av = int64val_(a).u; if (h0_(b) == s_integer) I64_IToU(&bv, intval_(b)); else bv = int64val_(b).u; switch (op) { case s_plus: ok = I64_UAdd(&rv, &av, &bv); break; case s_minus: ok = I64_USub(&rv, &av, &bv); break; case s_times: ok = I64_UMul(&rv, &av, &bv); break; case s_div: ok = I64_UDiv(&rv, &tv, &av, &bv); break; case s_rem: ok = I64_UDiv(&tv, &rv, &av, &bv); break; case s_and: I64_And((int64 *)&rv, (int64 *)&av, (int64 *)&bv); break; case s_or: I64_Or((int64 *)&rv, (int64 *)&av, (int64 *)&bv); break; case s_xor: I64_Eor((int64 *)&rv, (int64 *)&av, (int64 *)&bv); break; case s_leftshift: ok = I64_UToI(&n, &bv); ok = ok | I64_Lsh((int64 *)&rv, (int64 *)&av, n); break; case s_rightshift: ok = I64_UToI(&n, &bv); ok = ok | I64_URsh(&rv, &av, n); break; case s_equalequal: return mkintconst(type_(c), I64_UComp(&av, &bv) == 0, c); case s_notequal: return mkintconst(type_(c), I64_UComp(&av, &bv) != 0, c); case s_less: return mkintconst(type_(c), I64_UComp(&av, &bv) < 0, c); case s_lessequal: return mkintconst(type_(c), I64_UComp(&av, &bv) <= 0, c); case s_greater: return mkintconst(type_(c), I64_UComp(&av, &bv) > 0, c); case s_greaterequal:return mkintconst(type_(c), I64_UComp(&av, &bv) >= 0, c); default: syserr(syserr_trydiadicreduce, (long)op); return c; } if (ok != i64_ok && errorexpr == NULL) { errormsg = sem_errwarn_udiad_overflow; errorexpr = c; } return MarkError((Expr *)mkint64const(flag, (int64 *)&rv), errorexpr, errormsg); } if ((h0_(a) == s_integer || h0_(a) == s_int64con) && (h0_(b) == s_integer || h0_(b) == s_int64con)) { int64 av, bv, rv, tv; I64_Status ok = i64_ok; uint32 n; if (h0_(a) == s_integer) I64_IToS(&av, intval_(a)); else av = int64val_(a).i; if (h0_(b) == s_integer) I64_IToS(&bv, intval_(b)); else bv = int64val_(b).i; switch (op) { case s_plus: ok = I64_SAdd(&rv, &av, &bv); break; case s_minus: ok = I64_SSub(&rv, &av, &bv); break; case s_times: ok = I64_SMul(&rv, &av, &bv); break; case s_div: ok = I64_SDiv(&rv, &tv, &av, &bv); break; case s_rem: ok = I64_SDiv(&tv, &rv, &av, &bv); break; case s_and: I64_And(&rv, &av, &bv); break; case s_or: I64_Or(&rv, &av, &bv); break; case s_xor: I64_Eor(&rv, &av, &bv); break; case s_leftshift: ok = I64_UToI(&n, (uint64 *)&bv); ok = ok | I64_Lsh(&rv, &av, n); break; case s_rightshift: ok = I64_UToI(&n, (uint64 *)&bv); ok = ok | I64_SRsh(&rv, &av, n); break; case s_equalequal: return mkintconst(type_(c), I64_SComp(&av, &bv) == 0, c); case s_notequal: return mkintconst(type_(c), I64_SComp(&av, &bv) != 0, c); case s_less: return mkintconst(type_(c), I64_SComp(&av, &bv) < 0, c); case s_lessequal: return mkintconst(type_(c), I64_SComp(&av, &bv) <= 0, c); case s_greater: return mkintconst(type_(c), I64_SComp(&av, &bv) > 0, c); case s_greaterequal:return mkintconst(type_(c), I64_SComp(&av, &bv) >= 0, c); default: syserr(syserr_trydiadicreduce, (long)op); return c; } if (ok != i64_ok && errorexpr == NULL) { errormsg = sem_errwarn_diad_overflow; errorexpr = c; } return MarkError((Expr *)mkint64const(flag, &rv), errorexpr, errormsg); } if ((h0_(a) == s_integer && is_template_arg_binder(b)) || (is_template_arg_binder(a) && h0_(b) == s_integer)) { Expr *e = (h0_(a) == s_integer) ? a : b; errorexpr = (e == a) ? b : a; return MarkError(mkintconst(type_(c), isrelational_(op) ? 1 : intval_(e), c), errorexpr, errormsg); } a = skip_invisible(a); b = skip_invisible(b); if (h0_(a) == s_floatcon && h0_(b) == s_floatcon) { DbleBin d,e,r; int status; fltrep_to_widest(&d, exf_(a)); fltrep_to_widest(&e, exf_(b)); switch (op) { case s_plus: status = flt_add(&r,&d,&e); break; case s_minus: status = flt_subtract(&r,&d,&e); break; case s_times: status = flt_multiply(&r,&d,&e); break; case s_div: status = flt_divide(&r,&d,&e); break; case s_power: return c; #define SEM_FLTCMP(op) mkintconst(type_(c),flt_compare(&d,&e) op 0,c); case s_equalequal: return SEM_FLTCMP(==); case s_notequal: return SEM_FLTCMP(!=); case s_less: return SEM_FLTCMP(<); case s_lessequal: return SEM_FLTCMP(<=); case s_greater: return SEM_FLTCMP(>); case s_greaterequal: return SEM_FLTCMP(>=); #undef SEM_FLTCMP default: syserr(syserr_trydiadicreduce2, (long)op); return c; } if (status > flt_ok) { if (status == flt_very_small) flt_report_error(status); else { if (errorexpr == NULL) { errormsg = sem_errwarn_fp_overflow; errorexpr = c; } /* improve */ return MarkError(mk_expr2(op, type_(c), a, b), errorexpr, errormsg); } } /* Safety, I presume (possibly can remove things like volatile?): */ flag &= bitoftype_(s_double)|bitoftype_(s_short)|bitoftype_(s_long); { FloatCon *m = fltrep_from_widest(&r, flag, 0); return MarkError(mkinvisible(type_(c), c, (Expr *)m), errorexpr, errormsg); } } if ((flag & bitoftype_(s_int)) && int_islonglong_(flag)) { Expr *fname, *revfname; if (flag & bitoftype_(s_unsigned)) switch (op) { case s_plus: revfname = fname = sim.lladd; break; case s_minus: revfname = sim.llrsb; fname = sim.llsub; break; case s_times: revfname = fname = sim.llmul; break; case s_div: revfname = sim.llurdv; fname = sim.lludiv; break; case s_rem: revfname = sim.llurrem; fname = sim.llurem; break; case s_and: revfname = fname = sim.lland; break; case s_or: revfname = fname = sim.llor; break; case s_xor: revfname = fname = sim.lleor; break; case s_leftshift: revfname = NULL; fname = sim.llshiftl; break; case s_rightshift: revfname = NULL; fname = sim.llushiftr; break; case s_equalequal: revfname = fname = sim.llcmpeq; break; case s_notequal: revfname = fname = sim.llcmpne; break; case s_less: revfname = sim.llucmpgt; fname = sim.llucmplt; break; case s_lessequal: revfname = sim.llucmpge; fname = sim.llucmple; break; case s_greater: revfname = sim.llucmplt; fname = sim.llucmpgt; break; case s_greaterequal:revfname = sim.llucmple; fname = sim.llucmpge; break; default: syserr(syserr_fp_op, (long)op); revfname = fname = NULL; /* To keep compiler quiet */ } else switch (op) { case s_plus: revfname = fname = sim.lladd; break; case s_minus: revfname = sim.llrsb; fname = sim.llsub; break; case s_times: revfname = fname = sim.llmul; break; case s_div: revfname = sim.llsrdv; fname = sim.llsdiv; break; case s_rem: revfname = sim.llsrrem; fname = sim.llsrem; break; case s_and: revfname = fname = sim.lland; break; case s_or: revfname = fname = sim.llor; break; case s_xor: revfname = fname = sim.lleor; break; case s_leftshift: revfname = NULL; fname = sim.llshiftl; break; case s_rightshift: revfname = NULL; fname = sim.llsshiftr; break; case s_equalequal: revfname = fname = sim.llcmpeq; break; case s_notequal: revfname = fname = sim.llcmpne; break; case s_less: revfname = sim.llscmpgt; fname = sim.llscmplt; break; case s_lessequal: revfname = sim.llscmpge; fname = sim.llscmple; break; case s_greater: revfname = sim.llscmplt; fname = sim.llscmpgt; break; case s_greaterequal:revfname = sim.llscmple; fname = sim.llscmpge; break; default: syserr(syserr_fp_op, (long)op); revfname = fname = NULL; /* To keep compiler quiet */ } if (revfname != NULL && h0_(b) == s_fnap) { /* (invisible nodes have been removed from the head of a and b) */ Expr *e = a; a = b; b = e; fname = revfname; } return MarkError(mk1fnap(fname, mkExprList2(a, b)), errorexpr, errormsg); } { Expr *fname = NULL, *revfname = NULL; if (software_floats_enabled && is_float_(flag)) switch(op) { /* It may be that raising to a power will be done by a library call that will be introduced later, and so I do not need to map it onto a function call here... whatever else it seems a bit ugly, but it does not make any difference to C, only Fortran */ case s_plus: revfname = fname = sim.fadd; break; case s_minus: revfname = sim.frsb; fname = sim.fsubtract; break; case s_times: revfname = fname = sim.fmultiply; break; case s_div: revfname = sim.frdiv; fname = sim.fdivide; break; case s_power: return c; /* probably wrong */ case s_equalequal: revfname = fname = sim.fequal; break; case s_notequal: revfname = fname = sim.fneq; break; case s_less: revfname = sim.fgreater; fname = sim.fless; break; case s_lessequal: revfname = sim.fgeq; fname = sim.fleq; break; case s_greater: revfname = sim.fless; fname = sim.fgreater; break; case s_greaterequal:revfname = sim.fleq; fname = sim.fgeq; break; default: syserr(syserr_fp_op, (long)op); revfname = fname = NULL; /* To keep compiler quiet */ } else if (software_doubles_enabled && is_anydouble_(flag)) switch(op) { case s_plus: revfname = fname = sim.dadd; break; case s_minus: revfname = sim.drsb; fname = sim.dsubtract; break; case s_times: revfname = fname = sim.dmultiply; break; case s_div: revfname = sim.drdiv; fname = sim.ddivide; break; case s_power: return c; /* probably wrong */ case s_equalequal: revfname = fname = sim.dequal; break; case s_notequal: revfname = fname = sim.dneq; break; case s_less: revfname = sim.dgreater; fname = sim.dless; break; case s_lessequal: revfname = sim.dgeq; fname = sim.dleq; break; case s_greater: revfname = sim.dless; fname = sim.dgreater; break; case s_greaterequal:revfname = sim.dleq; fname = sim.dgeq; break; default: syserr(syserr_fp_op, (long)op); revfname = fname = NULL; /* To keep compiler quiet */ } if (revfname != NULL && h0_(b) == s_fnap) { /* (invisible nodes have been removed from the head of a and b) */ Expr *e = a; a = b; b = e; fname = revfname; } if (fname != NULL) return MarkError(mk1fnap(fname, mkExprList2(a, b)), errorexpr, errormsg); } return errorexpr == NULL ? c : MarkError(mk_expr2(op, type_(c), a, b), errorexpr, errormsg); } static Expr *trymonadreduce(AEop op, Expr *a, Expr *c, SET_BITMAP flag) { Expr *errorexpr = NULL; msg_t errormsg = NULL; if (h0_(a) == s_evalerror) { errorexpr = arg2_(a); errormsg = (msg_t)arg3_(a); a = arg1_(a); } if (h0_(a) == s_integer) { unsigned32 m = intval_(a), r; bool ok = YES; switch (op) /* BEWARE: 2's complement means signed == unsigned */ { case s_monplus: r = m; break; case s_neg: r = 0-m; if (!(flag & bitoftype_(s_unsigned))) ok = (int32)(m&r&0x80000000) == 0; break; case s_bitnot: r = ~m; break; case s_boolnot: r = !m; break; default: syserr(syserr_trymonadicreduce, (long)op); case s_content: return c; } r = widen32bitint_(r); if (sizeof_int == 2) { if (flag & bitoftype_(s_unsigned)) { if (!(flag & bitoftype_(s_long)) && (r & 0xffff0000)) r &= 0x0000ffff, ok = NO; } else { if (!(flag & bitoftype_(s_long)) && r != (unsigned32)(int16)r) r = (int16)r, ok = NO; } } if (!ok && errorexpr == NULL) { errormsg = (flag & bitoftype_(s_unsigned)) ? sem_errwarn_umonad_overflow : sem_errwarn_monad_overflow; } return MarkError(mkintconst(type_(c),r,c), errorexpr, errormsg); } if (h0_(a) == s_int64con) { int64 av = int64val_(a).i; int64 rv; I64_Status ok = i64_ok; switch (op) { case s_monplus: rv = av; break; case s_neg: ok = I64_Neg(&rv, &av); break; case s_bitnot: I64_Not(&rv, &av); break; default: syserr(syserr_trymonadicreduce1, (long)op); return c; } if (ok != i64_ok && errorexpr == NULL) { errormsg = (flag & bitoftype_(s_unsigned)) ? sem_errwarn_umonad_overflow : sem_errwarn_monad_overflow; } return MarkError((Expr *)mkint64const(flag, &rv), errorexpr, errormsg); } a = skip_invisible(a); if (h0_(a) == s_floatcon) { int32 flag = exf_(a)->floatlen; /* same as type info. */ DbleBin d,r; int status; fltrep_to_widest(&d, exf_(a)); switch (op) { case s_monplus: status = flt_move(&r,&d); break; case s_neg: status = flt_negate(&r,&d); break; default: syserr(syserr_trymonadicreduce1, (long)op); return c; } if (status > flt_ok) { if (errorexpr == NULL) { errormsg = sem_errwarn_fp_overflow; errorexpr = c; } return MarkError(mk_expr1(op, type_(c), a), errorexpr, errormsg); } { FloatCon *m = fltrep_from_widest(&r, flag, 0); return MarkError(mkinvisible(type_(c), c, (Expr *)m), errorexpr, errormsg); } } if ((flag & ts_longlong) == ts_longlong) { TypeExpr *t = princtype(typeofexpr(a)); /* hmm */ SET_BITMAP m = h0_(t)==s_typespec ? typespecmap_(t) : 0; if ((m & ts_longlong) == ts_longlong) { Expr *fname; switch (op) { case s_monplus: return a; case s_neg: fname = sim.llneg; break; case s_bitnot: fname = sim.llnot; break; default: syserr(syserr_trymonadicreduce, (long)op); fname = NULL; /* To keep compiler quiet */ } return MarkError(mk1fnap(fname, mkExprList1(a)), errorexpr, errormsg); } } { TypeExpr *t = princtype(typeofexpr(a)); /* hmm */ SET_BITMAP m = h0_(t)==s_typespec ? typespecmap_(t) : 0; Expr *fname = NULL; if (software_floats_enabled && is_float_(m)) switch (op) { case s_monplus: return a; case s_neg: fname = sim.fnegate; break; default: syserr(syserr_fp_op, (long)op); } else if (software_doubles_enabled && is_anydouble_(m)) switch (op) { case s_monplus: return a; case s_neg: fname = sim.dnegate; break; default: syserr(syserr_fp_op, (long)op); } if (fname != NULL) return MarkError(mk1fnap(fname, mkExprList1(a)), errorexpr, errormsg); } return errorexpr == NULL ? c : MarkError(mk_expr1(op, type_(c), a), errorexpr, errormsg); } static Expr *castfn(Expr *e) { TypeExpr *t1, *t2; Expr *a = arg1_(e), *fname = NULL; SET_BITMAP m1, m2; if (h0_(e) != s_cast) return e; t1 = princtype(type_(e)); /* hmm (SOFTWARE_FLOATING_POINT) */ t2 = princtype(typeofexpr(a)); /* hmm (SOFTWARE_FLOATING_POINT) */ if (h0_(t1) != s_typespec || h0_(t2) != s_typespec) return e; m1 = typespecmap_(t1); if (m1 & bitoftype_(s_void)) return e; /* cast to void: leave alone */ m2 = typespecmap_(t2); if (int_islonglong_(m1)) { if (m2 & bitoftype_(s_double)) { fname = (m1 & bitoftype_(s_unsigned)) ? ((m2 & bitoftype_(s_short)) ? sim.llufromf : sim.llufromd) : ((m2 & bitoftype_(s_short)) ? sim.llsfromf : sim.llsfromd); } else if (int_islonglong_(m2)) { if ((m1 ^ m2) & (bitoftype_(s_signed) | bitoftype_(s_unsigned))) /* Change of signedness : cast must stay */ return e; else return a; } else fname = (m2 & bitoftype_(s_unsigned)) ? sim.llfromu : sim.llfroml; } else if (int_islonglong_(m2)) { if (m1 & bitoftype_(s_double)) fname = (m2 & bitoftype_(s_unsigned)) ? ((m1 & bitoftype_(s_short)) ? sim.llutof : sim.llutod) : ((m1 & bitoftype_(s_short)) ? sim.llstof : sim.llstod); else return mkcast(s_cast, mk1fnap(sim.lltol, mkExprList1(a)), t1); } else if (is_float_(m1)) { if (is_float_(m2)) return a; else if (software_floating_point_enabled && is_anydouble_(m2)) fname = sim.fnarrow; else if (software_floats_enabled) fname = (m2 & bitoftype_(s_unsigned)) ? sim.ffloatu : sim.ffloat; #ifdef TARGET_LACKS_UNSIGNED_FIX else if (software_doubles_enabled && (m2 & bitoftype_(s_unsigned))) fname = sim.ffloatu; #endif } else if (is_anydouble_(m1)) { if (software_floating_point_enabled && is_float_(m2)) fname = sim.dwiden; else if (is_anydouble_(m2)) return a; else if (software_doubles_enabled) fname = (m2 & bitoftype_(s_unsigned)) ? sim.dfloatu : sim.dfloat; } if (fname != NULL) return mk1fnap(fname, mkExprList1(a)); if (software_floats_enabled && is_float_(m2)) fname = (m1 & bitoftype_(s_unsigned)) ? sim.ffixu : sim.ffix; else if (software_doubles_enabled && is_anydouble_(m2)) fname = (m1 & bitoftype_(s_unsigned)) ? sim.dfixu : sim.dfix; #ifdef TARGET_LACKS_UNSIGNED_FIX else if (software_doubles_enabled && is_float_(m2) && (m1 & bitoftype_(s_unsigned))) fname = sim.ffixu; #endif if (fname != NULL) return mkcast(s_cast, mk1fnap(fname, mkExprList1(a)), type_(e)); return e; } static Expr *trycastreduce(Expr *a, TypeExpr *tc, Expr *c, bool explicit) /* Args somewhat redundant -- c = (s_cast,tc,a) */ { TypeExpr *x = princtype(tc); /* type being cast to. */ /* (can ignore typedef qualifiers). */ if (h0_(a) == s_integer || h0_(a) == s_int64con) { bool truncated = NO; unsigned32 n, r; SET_BITMAP m, ta; if (h0_(a) == s_integer) { ta = typespecmap_(princtype(type_(a))); n = intval_(a); } else { ta = int64map_(a); truncated = I64_UToI(&n, &int64val_(a).u); } r = n; switch (h0_(x)) /* signed/unsigned shouldn't matter here */ { case s_typespec: m = typespecmap_(x); switch (m & -m) /* LSB - unsigned/long etc. are higher */ { case bitoftype_(s_char): r = (issignedchar_(m) && (n & 0x80)) ? (n | ~(int32)0xff) : (n & 0xff); break; case bitoftype_(s_enum): /* ansi C says treat like 'int'. */ case bitoftype_(s_int): if (int_islonglong_(m)) { if (h0_(a) == s_int64con) { return (Expr *)mkint64const(m, &int64val_(a).i); } else if (ta & bitoftype_(s_unsigned)) { uint64 u; I64_IToU(&u, n); return (Expr *)mkint64const(m, (int64 *)&u); } else { int64 i; I64_IToS(&i, n); return (Expr *)mkint64const(m, &i); } } if ((int_isshort_(m) ? sizeof_short : (m & bitoftype_(s_long)) ? sizeof_long : sizeof_int) == 2) r = (!(m & bitoftype_(s_unsigned)) && (n & 0x8000)) ? (n | ~(int32)0xffff) : (n & 0xffff); break; case bitoftype_(s_void): r = 0; goto omit_check; /* mkvoided did it for us. */ case bitoftype_(s_double): /* remember (double)(-1u) != (double)(-1) ... */ /* Use int_to_real() rather than flt_itod() or flt_utod() since it fills */ /* in a string with the number etc etc etc. */ if (ta & ARITHTYPEBITS) return mkinvisible(tc, c, (Expr *)int_to_real( n, ta & bitoftype_(s_unsigned), m)); /* drop through */ default: return c; /* always harmless to return cast */ } if (!explicit && (truncated || r != n)) cc_ansi_warn(sem_rerr_implicit_cast_overflow(x,n,r)); break; case t_content: r = n==0 ? TARGET_NULL_BITPATTERN : n; break; /* cast to pointer */ default: return c; /* should not happen (prev error) */ } omit_check: return mkintconst(tc,r,c); } a = skip_invisible(a); if (h0_(a) == s_floatcon) { /* We have a cast (possibly implicit) on a floating constant value. */ /* Produce a new FloatCon value with the new type. */ if (h0_(x) == s_typespec) { SET_BITMAP m = typespecmap_(x); int32 n; int status; DbleBin d; fltrep_to_widest(&d, exf_(a)); switch (m & -m) { case bitoftype_(s_char): status = (issignedchar_(m)) ? flt_dtoi(&n, &d) : flt_dtou((unsigned32 *)&n, &d); /* I do not complain about (char)258.0, but I will moan at (char)1.e11 */ /* where 1.e11 will not fit in an int. This is at least compatible with */ /* run-time behaviour on casts. */ n = (issignedchar_(m) && (n & 0x80)) ? (n | ~(int32)0xff) : (n & 0xff); break; case bitoftype_(s_int): status = (m & bitoftype_(s_unsigned)) ? flt_dtou((unsigned32 *)&n, &d) : flt_dtoi(&n, &d); if ((int_isshort_(m) ? sizeof_short : (m & bitoftype_(s_long)) ? sizeof_long : sizeof_int) == 2) n = (!(m & bitoftype_(s_unsigned)) && (n & 0x8000)) ? (n | ~(int32)0xffff) : (n & 0xffff); break; case bitoftype_(s_enum): status = flt_dtoi(&n, &d); /* This case seems pretty dodgy! */ break; case bitoftype_(s_double): { char *oldfloatstr = exf_(a)->floatstr; FloatCon *fc = fltrep_from_widest(&d, m, oldfloatstr); return mkinvisible(tc, c, (Expr *)fc); } default: /* this includes the (void)1.3 case for which warning has */ /* already been given. Could do ok=1, n=0 instead. */ return c; } if (status > flt_ok) { cc_warn(sem_warn_fix_fail); n = 0; } return mkintconst(tc,n,c); } return c; /* nothing doing */ } return c; } /* check_index_overflow checks if an address computation (possibly via */ /* a subscript operation) indexes an array whose size, n, is manifest. */ /* If so then it checks that a (constant) offset is in the range 0..n. */ /* IF a dereference later occurs, then we moan at the use of offset n */ /* too. At this time, though, the stride will have been multiplied */ /* into the offset, so we have to compensate. Argument 'stride' is */ /* a TypeExpr * for the stride type or NULL if not dereferenced (yet). */ /* Note also that modify_formal_type makes this hard to do (and less */ /* justifiable) in "int f(int a[4]) { return a[-1]; }". Hence don't. */ static void check_index_overflow(Expr *ptr, Expr *disp, int posneg, bool deref) { TypeExpr *t0; if (feature & FEATURE_PCC) return; t0 = typeofexpr(ptr); ptr = skip_invisible_or_cast(ptr); /* @@@ skip_invisible doesn't work? */ if (h0_(disp) == s_integer && h0_(ptr) == s_addrof) { TypeExpr *t = type_(ptr); if (h0_(t) == t_content) { TypeExpr *t2 = princtype(typearg_(t)); /* princtype since array type may be typedef'd. */ if (h0_(t2) == t_subscript) { Expr *bound = typesubsize_(t2); int32 k = sizeoftype(typearg_(princtype(t0))); int32 n = posneg * intval_(disp); if (bound && h0_(bound) == s_binder) bound = NULL; if (k == 0) k = 1; /* paranoia */ if (!deref) { /* always whinge for n<0 or n>limit... */ if (n < 0 || bound && n * k> evaluate(bound) * sizeoftype(typearg_(t2))) cc_warn(sem_warn_index_ovfl, n); } else { /* ... but also if n=limit AND dereferencing. */ if (bound && n == evaluate(bound) * k) cc_warn(sem_warn_index_ovfl, n/k); } } } } } static void check_index_dereference(Expr *e) { if (!(feature & FEATURE_PCC) && h0_(e) == s_content) { Expr *a = arg1_(e); if (h0_(a) == s_plus) #ifdef OLD_POINTER_CODE check_index_overflow(arg2_(a), arg1_(a), 1, YES), #endif check_index_overflow(arg1_(a), arg2_(a), 1, YES); if (h0_(a) == s_minus) check_index_overflow(arg1_(a), arg2_(a), -1, YES); } } static Expr *nonconst1(Expr *e) /* make this table driven */ { Expr *e1; for (;;) switch (h0_(e)) { default: return e; case s_integer: return 0; case s_invisible: e = orig_(e); break; case s_cast: case s_monplus: case s_neg: case s_bitnot: case s_boolnot: e = arg1_(e); break; case s_plus: case s_minus: case s_times: case s_div: case s_rem: case s_and: case s_or: case s_andand: case s_oror: case s_leftshift: case s_rightshift: case s_equalequal: case s_notequal: case s_less: case s_lessequal: case s_greater: case s_greaterequal: case s_comma: if ((e1 = nonconst1(arg1_(e))) != 0) return e1; e = arg2_(e); break; case s_cond: if ((e1 = nonconst1(arg1_(e))) != 0) return e1; if ((e1 = nonconst1(arg2_(e))) != 0) return e1; e = arg3_(e); break; } } void moan_nonconst(Expr *e, msg_t nonconst_msg, msg_t nonconst1_msg, msg_t nonconst2_msg) { if (debugging(DEBUG_TYPE)) { eprintf("moan_nonconst on "); pr_expr(e); } e = nonconst1(e); if (e == 0) cc_err(nonconst_msg); else if (h0_(e) == s_binder) cc_err(nonconst1_msg, (exb_(e))); else cc_err(nonconst2_msg, h0_(e)); } static bool check_narrow_subterm(Expr *e, TypeExpr *te, TypeExpr *tt) { tt = princtype(tt), te = princtype(te); /* ignore qualifiers */ if (h0_(tt) == s_typespec && h0_(te) == s_typespec && (/* moan at int/long ops in any float context */ typespecmap_(tt) & ~typespecmap_(te) & bitoftype_(s_double) || /* moan at plain ops in long context, both same floatiness. */ !((typespecmap_(tt) ^ typespecmap_(te)) & bitoftype_(s_double)) && typespecmap_(tt) & ~typespecmap_(te) & bitoftype_(s_long) || /* moan at (float) short double in other float context */ typespecmap_(tt) & bitoftype_(s_double) && typespecmap_(te) & ~typespecmap_(tt) & bitoftype_(s_short) )) { retry: switch h0_(e) { case s_invisible: e = orig_(e); goto retry; case s_comma: e = arg2_(e); goto retry; case s_monplus: e = arg1_(e); goto retry; case s_and: case s_or: case s_xor: case s_leftshift: case s_rightshift: case s_plus: case s_minus: case s_times: case s_div: /* but not s_ptrdiff -- since long a = ptr1-ptr2 is always ok */ case s_rem: case s_neg: case s_bitnot: #ifdef EXTENSION_VALOF case s_valof: #endif #ifndef FORTRAN /* re-instate something like this for f77 soon */ if (suppress & D_LOWERINWIDER) xwarncount++; else cc_warn(sem_warn_low_precision, h0_(e)); #endif return 1; case s_cond: /* "long x = p() ? 1 : 2;" cannot reasonably give a warning */ /* but think more about "long x = p() ? 33000 : 1". */ return check_narrow_subterm(arg2_(e), te, tt) ? 1 : check_narrow_subterm(arg3_(e), te, tt); #ifdef never case s_integer: if ((e = intorig_(e)) != 0) goto retry; /* drop through */ case s_andand: case s_oror: case s_equalequal: case s_notequal: /* + other relops */ #endif default: break; } } return 0; } static int32 bf_container_bits(TypeExpr *t) { SET_BITMAP m = typespecmap_(t); if (m & bitoftype_(s_char)) return 8; if (int_islonglong_(m)) return 8 * sizeof_longlong; #ifdef TARGET_LACKS_HALFWORD_STORE if (target_lacks_halfword_store) return MAXBITSIZE; #endif if (int_isshort_(m)) return sizeof_short*8; return MAXBITSIZE; } static Expr *bf_container(Expr *e, SET_BITMAP m) { if (!(h0_(e) == s_dot && m & BITFIELD)) syserr(syserr_bf_container); /* @@@ te_int is OK while sizeof_int == sizeof_long. */ /* in the longer term move to an 'unbitfield_type()' container? */ { int32 maxsize = bf_container_bits(type_(e)); if (maxsize >= MAXBITSIZE) return mk_exprwdot(s_dot, mkqualifiedtype(int_islonglong_(m) ? te_llint : te_int, m & QUALIFIER_MASK), arg1_(e), exprdotoff_(e)); else { int32 off = exprdotoff_(e); TypeExpr *te = primtype2_(m & ~BITFIELD, typespectagbind_(type_(e))); int32 byteoff = (exprmsboff_(e) / maxsize) * (maxsize / 8); if (target_lsbytefirst) byteoff = sizeof_int - (maxsize / 8) - byteoff; return mk_exprwdot(s_dot, te, arg1_(e), off+byteoff); } } } static Expr *coerce2(Expr *e, TypeExpr *t) /* does NOT check consistent - use mkcast for this */ /* really only for implicit arithmetic casts */ { Expr *r; TypeExpr *te = princtype(typeofexpr(e)); /* ignore cast qualifiers */ if (equivtype(t,te) == 2) return e; /* identical types, no cast */ if (isbitfield_type(te)) { SET_BITMAP m = typespecmap_(te); e = bitfieldvalue(e, m, bf_container(e, m)); } (void)check_narrow_subterm(e, te, t); r = mk_expr1(s_cast, t, e); r = trycastreduce(e,t,r,NO); return castfn(r); /* the invisible node in the following should never be seen and needs re-thinking re constant reduction. */ /* return mkinvisible(t, e, mk_expr1(s_cast, t, e)); */ } /* The complications below for coercion context are due to AM's */ /* implementation of the fact that in most contexts fns/arrays are */ /* coerced to pointers exactly when char/short/bitfield are widened to */ /* int. (I.e. neither for lvalue (inlcuding sizeof) context, both for */ /* rvalue context). The exception is comma context, where ANSI have */ /* (foolishly?) specified that, given char a[10], we have */ /* sizeof(0,a)==sizeof(char *), sizeof(0,a[0])==sizeof(char). Yuk. */ /* The implementation chosen is further encouraged by the observation */ /* that otherwise we would make comma-context the only non-lvalue */ /* phrase to have non-widened types, which seems like a bug invitation. */ /* For C++ errors, and also C *warnings*, for abuse of int/enum we */ /* now defer widening of enum to int. */ enum Coerce_Context { COERCE_NORMAL, COERCE_ARG, COERCE_COMMA, COERCE_ASSIGN, COERCE_VOIDED }; /* COERCE_VOIDED is the same as COERCE_NORMAL, except that non lvalue */ /* array objects are permitted and C++ refs are not deref'd */ /* coerceunary ought to be idempotent for its uses. */ /* Its caller has ensured that 'e' is not s_error (errornode). */ static Expr *coerceunary_2(Expr *e, enum Coerce_Context c) { TypeExpr *qt = typeofexpr(e), *t = princtype(qt); /* NB. in principle coerceunary() converts lvalues to rvalues and */ /* hence could remove top level qualifiers. However, this would */ /* turn over (a little?) more store and routines elsewhere happily */ /* manage to ignore such qualifiers. */ /* Surprisingly, 'qt' is needed for coercing lvalues such as x in */ /* "typedef int t[3][4]; const t x;". This must coerce x to */ /* type (const int (*)[4]). See t_subscript case. */ SET_BITMAP m; if (debugging(DEBUG_TYPE)) { eprintf("Coerceunary called: "); pr_expr_nl(e); } /* Here is just the place to check that "a[n]" is (in)valid given */ /* the declaration "int a[n]". */ check_index_dereference(e); if (LanguageIsCPlusPlus) { if (h0_(e) == s_binder && bindconst_(exb_(e))) e = mkinvisible(qt, e, bindconst_(exb_(e))); } if (LanguageIsCPlusPlus) { if ((h0_(e) == s_binder || h0_(e) == s_member) && attributes_(exb_(e)) & CB_ANON) e = mkfieldselector(s_dot, (Expr *)realbinder_(exb_(e)), (ClassMember *)bindsym_(exb_(e))); /* do 'enum' constant name -> integer const here too? */ } switch (h0_(t)) { case s_typespec: m = typespecmap_(t); switch (m & -m) /* LSB - unsigned/long etc. are higher */ { case bitoftype_(s_char): /* INTEGRALTYPEBITS */ case bitoftype_(s_bool): case bitoftype_(s_int): case bitoftype_(s_enum): /* For explanation of the next line see the comment for COERCE_COMMA. */ if (c == COERCE_COMMA) return e; /* As part of the previous line, we now have to unravel char/bitfields */ /* in NORMAL/ARG context, but they may be embedded inside s_comma:s. */ /* This is needed to avoid s_dot syserr() and to preserve the useful */ /* fact that only l-value and fn-return aetrees can have narrow values. */ if (h0_(e) == s_comma && m & (BITFIELD| bitoftype_(s_char)|bitoftype_(s_short)|bitoftype_(s_enum)) && !(m & bitoftype_(s_long))) { /* BEWARE: smashing of tree known to be unshared. */ arg2_(e) = coerceunary_2(arg2_(e), c); type_(e) = typeofexpr(arg2_(e)); return e; } /* bitfieldvalue can promote to signed or unsigned int. */ /* For C++ it can also promote to enum. @@@ review long bit fields. */ /* @@@ For systems in which sizeof_long>sizeof_int then maybe we should */ /* allow long bit values and promotion to (unsigned)long as an ANSI- */ /* conformant extension. See what the ANSI C++ committee think. */ if (m & BITFIELD) /* rvalue context here */ { Expr *ee = skip_invisible(e); return bitfieldvalue(ee, m, bf_container(ee, m)); } /* C++: it is arguable that COERCE_ARG (unchecked params) should */ /* not promote its arg here. Then we could warn on printf("%d", enum) */ /* In C, of course, this is perfectly OK. */ if (m & bitoftype_(s_enum) && c == COERCE_ASSIGN) return e; /* ANSI says coerce unsigned or signed char (or short) to (signed) int */ /* if shorter. PCC says unsigned char (or short) coerce to unsigned. */ /* This code now copes with sizeof_int==sizeof_short. */ /* It does not cope with sizeof_int==sizeof_char in ANSI mode. */ /* In C++ enums promote to int or unsigned int depending on their */ /* container type. @@@ Promoting enums to long or unsigned long is not */ /* yet handled. */ if (m & (bitoftype_(s_char)|bitoftype_(s_short) |bitoftype_(s_enum)) && /* next line copes with "long long" encoding. */ !(m & bitoftype_(s_long))) e = (feature & FEATURE_PCC) ? /* Someone might like to worry about the case */ /* where default char is unsigned in PCC mode */ /* does it then promote to signed int (as now) or */ /* unsigned int? K&R say (signed) int. */ coerce2(e, (m & bitoftype_(s_unsigned)) ? te_uint:te_int) : coerce2(e, ((sizeof_short==sizeof_int && int_isshort_(m) && m & bitoftype_(s_unsigned)) || (LanguageIsCPlusPlus && (m & bitoftype_(s_enum)) && ((tagbindbits_(typespectagbind_(t)) & TB_CONTAINER) == TB_CONTAINER_UINT))) ? te_uint:te_int); return e; case bitoftype_(s_double): /* The pcc mode code here may need improving (as char above) if PCC has */ /* sizeof(0,(float)0)==sizeof(float) -- this code gives sizeof(double). */ if ((c == COERCE_ARG || feature & FEATURE_PCC) && (m & bitoftype_(s_short))) return coerce2(e, te_double); return e; case bitoftype_(s_struct): case bitoftype_(s_class): case bitoftype_(s_union): case bitoftype_(s_void): return e; default: break; } break; case t_unknown: case t_content: return e; case t_subscript: if (!(feature & FEATURE_PCC) && c != COERCE_VOIDED) /* recovery better be good. */ (void)ensurelvalue(e, s_addrof); /* Complications here coercing a const array into a pointer to */ /* a const element. Use "t a[n]" -> "(t *)&a" */ { TypeExpr *t1 = ptrtotype_( mkqualifiedtype(typearg_(t), typedef_qualifiers(qt))); return mkinvisible(t1, e, mk_expr1(s_cast, t1, mkaddr(e))); } case t_ref: { if (c == COERCE_COMMA || c == COERCE_VOIDED) return e; else { TypeExpr *t2 = typearg_(t); /* recursion allows for ref to array/fn [ES,p128,l-1]!!? */ return coerceunary_2( mkinvisible(t2, e, mk_expr1(s_content,t2,e)), c); } } case t_coloncolon: /* if (!LanguageIsCPlusPlus) break; -- must be C++ */ return thisify(e); case t_ovld: /* if (!LanguageIsCPlusPlus) break; -- must be C++ */ /* It's never the right thing to do to change a generic into a specific just because there's only one. But we do it here (ovld_resolve_addr, actually) to make some cases work that we haven't implemented in general (n-way overloaded) yet. */ { BindList *bl = typeovldlist_(t); if (cdr_(bl) == NULL) /* hack to allow single static memfn */ { Expr *tmp = (Expr *)ovld_resolve_addr(e, typeovldlist_(t)); if (h0_(tmp) != s_binder || (bindparent_((Binder*)tmp) != NULL && !(bindstg_((Binder*)tmp) & b_memfns))) return e; /* same as t_fnap case */ e = tmp; t = typeofexpr(e); #if NEVER return coerceunary_2( (Expr *)ovld_resolve_addr(e, typeovldlist_(t)), c); #endif /* fall through to case t_fnap */ } else /* no coersion from 'T::f' to '&T::f' */ return e; } case t_fnap: if (LanguageIsCPlusPlus) { if (h0_(e) == s_dot) /* C++ member function */ /* @@@ give a type warning on the next line? */ return coerceunary_2(exprdotmemfn_(e),c); if (h0_(e) == s_dotstar) /* see [ES, p71] */ { cc_err(sem_err_noncallsite_function); return errornode; } /* Note re thisify(): &memfn2 is legal even in a static member fn. */ if (h0_(e) == s_binder && bindstg_(exb_(e)) & b_impl) { Binder *b = realbinder_(exb_(e)); if (bindstg_(b) & b_memfna) t = (TypeExpr *)syn_list3(t_coloncolon, t, bindparent_(exb_(e))); /* Take address of implementation but use type of member. */ /* Making a memfn behave like s_member in typeofexpr() would help here. */ e = (Expr *)b; } } { TypeExpr *t2 = ptrtotype_(t); return mkinvisible(t2, e, mk_expr1(s_addrof,t2,e)); } default:; } syserr(syserr_coerceunary1, (long)h0_(t), (long)typespecmap_(t)); return e; } Expr *coerceunary(Expr* e) { return coerceunary_2(e, COERCE_NORMAL); } /* Null pointer constants are defined in Dec 88 draft, section 3.2.2.3. */ /* This routine accepts (void *)(int *)0 as NPC, drafts leave undef'd. */ bool isnullptrconst(const Expr *e) { if (h0_(e) == s_integer) { TypeExpr *t = princtype(type_(e)); /* type_(e)==typeofexpr(e) */ if (h0_(t) == s_typespec && typespecmap_(t) & INTEGRALTYPEBITS && intval_(e) == 0 || /* Note: (void *)0 is a NPC, but (const void *)0 isn't. We assume */ /* (void *const)0 is a NPC, because qualifiers are ignored on non- */ /* lvalues, of which casts are an example. */ isptrtovoidtype(t) && intval_(e) == TARGET_NULL_BITPATTERN) return 1; } return 0; } static Expr *pointerofint(Expr *e, AEop op, TypeExpr *t) { if (!isnullptrconst(e) || (op != s_equalequal && op != s_notequal)) cc_pccwarn(sem_rerr_pointer_compare, op); return coerce2(e,t); } Expr *mkintegral(AEop op, Expr *a) /* op in {s_switch, s_subscript} */ { if (h0_(a = coerceunary(a)) == s_error) return a; { /* @@@ We should check warnings (C++ errs!) for switch(enum) etc here. */ TypeExpr *t = princtype(typeofexpr(a)); if (h0_(t) == s_typespec) { SET_BITMAP m = typespecmap_(t); switch (m & -m) { case bitoftype_(s_int): /* possibly long/unsigned */ if (!int_islonglong_(m)) return a; } } /* It is debatable whether 'int' is the right type on the next line, */ /* but observe that only erroneous cases (flts/pointers/etc) go here. */ return mkcast(op, a, te_int); } } /* mktest() is used for exprs in conditional (0/non-0) context. It does two things. 1) warns (optionally later) of '=' if '==' could be more sensible. 2) adds a !=0 node to any non-boolean values, so result is always 0/1 which also takes care of type-checking modulo error messages. */ Expr *mktest(AEop opreason, Expr *a) { Expr *x; AEop op; for (x=a;;) switch (op = h0_(x)) { case s_invisible: x = orig_(x); break; case s_comma: x = arg2_(x); break; case s_oror: case s_andand: case s_boolnot: return a; /* type must be OK. Args already done. */ case s_assign: case s_bitnot: if (suppress & D_ASSIGNTEST) xwarncount++; else cc_warn(sem_warn_odd_condition, op); /* drop through */ default: { IGNORE(opreason); /* re-think whether this is useful */ if (isrelational_(op)) return a; /* type OK */ if (LanguageIsCPlusPlus) { TypeExpr *t = princtype(typeofexpr(a)); if (isprimtype_(t, s_bool)) return mkbinary(s_notequal, a, lit_false); a = coerceunary(a); t = princtype(typeofexpr(a)); if (isclasstype_(t)) a = allowable_boolean_conversion(a); else if (!((h0_(t) == s_typespec) && (typespecmap_(t) & ARITHTYPEBITS)) && h0_(t) != t_content && !isptrtomember(t)) { if (h0_(t) != t_unknown) typeclash(s_notequal); a = errornode; } } /* Beware TARGET_NULL_BITPATTERN */ return LanguageIsCPlusPlus ? cpp_mkbinaryorop(s_notequal, a, lit_zero) : mkbinary(s_notequal, a, lit_zero); } } } static Expr *mkvoided(Expr *e) /* currently always returns its arg */ { Expr *x; AEop op; for (x = e;;) switch (op = h0_(x)) { case s_invisible: x = orig_(x); break; case s_cast: /* This could otherwise moan about the wrong */ /* operator since coerce2 can insert s_cast:s */ /* without an s_invisible node. */ x = arg1_(x); break; case s_fnap: /* Only non-void results come here: moan? */ return e; case s_let: case s_comma: x = arg2_(x); break; case s_cond: (void)mkvoided(arg2_(x)); x = arg3_(x); break; case s_integer: if (intorig_(x)) { x = intorig_(x); break; } /* (void)(1+2); */ /* treat 0 specially because (e ? f() : 0) is common (indeed necessary) */ /* in macro:s (e.g. assert) which must be an expression, not command. */ { TypeExpr* t = princtype(typeofexpr(x)); if (isprimtype_(t, s_int) && intval_(x) == 0) return e; else if (isprimtype_(t, s_char)) op = s_character; else if (isprimtype_(t, s_bool)) op = intval_(x) ? s_true : s_false; /* and drop through */ } /* else drop through */ default: /* Suppression of warnings for explicit casts is now done by caller. */ if ( #ifdef FOR_ACORN !cplusplus_flag && #endif !(isassignop_(op) || isincdec_(op) || (op == s_binder && isgensym(bindsym_(exb_(x)))))) cc_warn(sem_warn_void_context, op); /* drop through */ case s_assign: case s_init: return e; #ifdef EXTENSION_VALOF case s_valof: return e; #endif } } static Expr *mklet(Binder *v, TypeExpr *t, Expr *e) { if (h0_(e) == s_error) return errornode; return mk_exprlet(s_let, t, mkSynBindList(0, v), e); } static Expr *mkletmany(TypeExpr *t, Expr *e, ...) /* Binder *v, ..., 0 */ { va_list ap; SynBindList *l = 0; Binder *v; if (h0_(e) == s_error) return errornode; va_start(ap, e); while ((v = va_arg(ap, Binder *)) != 0) l = mkSynBindList(l, v); va_end(ap); return mk_exprlet(s_let, t, l, e); } static Expr *appendlet(Expr *let, Expr *e) { TypeExpr* te; if (let == 0) return e; if (h0_(let) == s_error || h0_(e) == s_error) return errornode; if (h0_(let) != s_let) syserr("appendlet %ld", h0_(let)); te = typeofexpr(e); if (arg2_(let) != 0) { /* like mkbinary(s_comma, arg2_(let), e); but don't coerceunary(e) */ Expr* a = arg2_(let); if (h0_(a = coerceunary(a)) == s_error) return errornode; a = mkcast(s_comma, a, te_void); if (h0_(a) == s_error) return errornode; e = mk_expr2(s_comma, te, a, e); } return mk_exprlet(s_let, te, exprletbind_(let), e); } Expr *mkunary(AEop op, Expr *a) { Expr *c; TypeExpr *t; if (monadneedslvalue_(op)) /* & ++ -- */ { c = ensurelvalue(a, op); c = (op == s_addrof) ? mkaddr(c) : mkincdec(op, c); /* add an invisible node if expression was transformed (for errors) */ return (h0_(c) == s_error) ? errornode : (h0_(c) == op) ? c : (t = typeofexpr(c), mkinvisible(t, mk_expr1(op,t,a), c)); } /* The next line treats monadic + as coercing enum->int. Check C++. */ if (h0_(a = coerceunary(a)) == s_error) return a; t = typeofexpr(a); /* the operators below all take rvalues in which qualifiers are ignored */ switch (op) /* + - ~ ! * */ { case s_content: if (indexable(t)) { t = indexee(t); /* kill all accesses via (qualified) void pointers. */ if (isvoidtype(t)) { cc_err(sem_rerr_void_indirection); return errornode; } break; } if (!istypevar(t)) typeclash(op); return errornode; case s_boolnot: a = mktest(op,a); if (h0_(a) == s_error) return errornode; t = typeofexpr(a); break; /* case s_monplus: */ /* ANSI have ruled that +ptr is illegal, but 0+ptr is OK! ... */ /* ... to make +ptr valid add: if (indexable(t)) break; */ /* case s_bitnot: */ /* case s_neg: */ default: /* (s_bitnot(~), s_neg(-), s_monplus(+) */ t = princtype(t); if (h0_(t) == s_typespec && (typespecmap_(t) & (op == s_bitnot ? INTEGRALTYPEBITS : ARITHTYPEBITS))) break; if (!istypevar(t)) typeclash(op); return errornode; } c = mk_expr1(op,t,a); /* AM: I wonder if we should do the transformations +e => 0+e; -e => 0-e; !e => 0==e; ~e = (-1)^e; here? This would only leave & and * as monads. It would certainly simplify type checking for (e.g. +x as it would say that int/float/pointer were ok only). Then cg.c could get to undo it (and catch similar cases too!). */ return trymonadreduce(op,a,c, h0_(t)==s_typespec ? typespecmap_(t) : addrsignmap_); } static Expr *mkshift(AEop op, Expr *a, int32 n) /* for bitfields only! */ { if (n == 0) return a; /* @@@ The next line is a hack to avoid spurious error messages when */ /* 1<<31 is used to mask off a bitfield, as in x.a=1. */ else if (h0_(a) == s_integer && type_(a) == te_int && op==s_leftshift) return mkintconst(te_int, (unsigned32)(intval_(a)) << n, 0); else return mkbinary(op, a, mkintconst(te_int, n, 0)); } static void I64_LSBMask(int64 *n, int32 size) { int64 one; I64_IToS(&one, 1); I64_Lsh(n, &one, size); I64_SSub(n, n, &one); } static Expr *OtherBitsMask(int32 size, int32 maxsize, int32 lspos) { if (maxsize <= MAXBITSIZE) return mkintconst(te_int, ~(lsbmask(size) << lspos), 0); else { int64 n; I64_LSBMask(&n, size); I64_Lsh(&n, &n, lspos); I64_Not(&n, &n); return (Expr *)mkint64const(ts_longlong, &n); } } static Expr *LSBMask(int32 size, int32 maxsize) { if (maxsize <= MAXBITSIZE) return mkintconst(te_int, lsbmask(size), 0); else { int64 n; I64_LSBMask(&n, size); return (Expr *)mkint64const(ts_longlong, &n); } } static Expr *bitfieldvalue(Expr *ebf, SET_BITMAP m, Expr *ewd) { /* * MEMO: exprbsize_ is size; exprmsboff_ is offset from msb; * (ebf must be s_dot of bits, ewd yields the word containing bitfield). * ANSI require 'int' bit fields treated as 'unsigned' or 'signed' just * when chars would be. E.g. that { unsigned a:7,b:32 } gives x.a type int, * and x.b unsigned, whereas PCC gives both unsigned (cf. unsigned char). * tr is type of result. * (We use an explicit cast to ensure the type of the value is right, * rather than relying on the invisible node to hold it, lest the * invisible node be optimised away while the type info is still needed). */ int32 size = exprbsize_(ebf); int32 maxsize = bf_container_bits(type_(ebf)); TypeExpr *tr = bf_promotedtype(type_(ebf), size); int32 maxbitsize = int_islonglong_(m) ? sizeof_longlong*8 : sizeof_int*8; /* AM @@@ There is work to be done (e.g. in the next line) so that we */ /* choose signed/unsigned enum bit fields depending on set of values? */ /* Currently enum bit fields act as plain int (i.e. may/maynot extend). */ Expr *e; if (issignedchar_(m)) { e = mkshift(s_rightshift, mkshift(s_leftshift, ewd, (exprmsboff_(ebf) % maxsize) + ((sizeof_int / (maxsize/8)) - 1) * maxsize), maxbitsize-size); } else if #ifdef TARGET_HAS_SCALED_OPS /* expand to a pair of shifts except when the field occupies */ /* the low-order bits of the container (so no shift needed */ /* for shift+mask extraction */ (maxsize-size-(exprmsboff_(ebf) % maxsize) != 0) #else /* expand to shift + mask, except when the field occupies */ /* the high-order bits of the container (so just a rightshift*/ /* needed for shift+shift extraction). */ (exprmsboff_(ebf) != 0 || maxsize != maxbitsize) #endif { if ((exprmsboff_(ebf) % maxsize) == 0) { e = mkshift(s_rightshift, mkcast(s_cast, ewd, int_islonglong_(m) ? te_ullint : te_uint), maxsize-size); } else { e = mkshift(s_rightshift, mkcast(s_cast, mkshift(s_leftshift, ewd, (exprmsboff_(ebf) % maxsize) + (maxbitsize / maxsize - 1) * maxsize), int_islonglong_(m) ? te_ullint : te_uint), maxbitsize-size); } } else if (size == maxsize) { e = ewd; } else { e = mkbinary(s_and, mkshift(s_rightshift, ewd, maxsize-size-(exprmsboff_(ebf) % maxsize)), LSBMask(size, maxsize)); } return mkinvisible(tr, ebf, mkcast(s_cast, e, tr)); } static Expr *bitfieldinsert(AEop op, Expr *ebf, Expr *ewd, Expr *val) { int32 size = exprbsize_(ebf); int32 maxsize = bf_container_bits(type_(ebf)); int32 lspos = maxsize-size-(exprmsboff_(ebf)%maxsize); return mkassign(op, /* not mkbinary (else x.bit = 1 gives 2 errs). */ ewd, size == maxsize ? val : mkbinary(s_or, mkbinary(s_and, ewd, OtherBitsMask(size, maxsize, lspos)), mkshift(s_leftshift, mkbinary(s_and, val, LSBMask(size, maxsize)), lspos))); } /* bitfieldstuff() has been so re-arranged to show its similarity to */ /* to mkopassign (q.v.). Rationalise the two one day. */ static Expr *bitfieldstuff(AEop op, Expr *a, SET_BITMAP m, Expr *ewd, Expr *b) /* special case: op==s_postinc has b = 1 or -1 according to ++ or -- */ { /* note that 'ewd' must not have side effects as it is duplicated */ Expr *bb = op == s_assign ? b : mkbinary(op == s_postinc ? s_plus : unassignop_(op), bitfieldvalue(a, m, ewd), b); return bitfieldinsert(op == s_postinc ? s_displace : s_assign, a, ewd, mkcast(op, bb, int_islonglong_(m) ? te_llint : te_int)); } static Expr *bitfieldassign(AEop op, Expr *a, TypeExpr *ta, Expr *b) /* special case: op==s_postinc has b = 1 or -1 according to ++ or -- */ /* NB: ta == typeofexpr(a), eliminate this arg? */ { Expr *bitword, *r; SET_BITMAP m; /* /* BEWARE: the next line can lose top-level qualifiers. This only */ /* really affects volatile (const done in ensurelvalue()), but more */ /* seriously the code to access bitfields needs review for volatile. */ ta = prunetype(ta); if (h0_(a) != s_dot || h0_(ta) != s_typespec) { syserr(syserr_bitfieldassign); return errornode; /* note the curious a/ta spread of info */ } m = typespecmap_(ta); bitword = bf_container(a, m); /* @@@ AM: the expression (x.b = 1) where x.b has bitfield type here */ /* has promoted type of x.b, maybe it shouldn't (e.g. sizeof). */ if (issimplelvalue(a)) r = bitfieldvalue(a, m, bitfieldstuff(op, a, m, bitword, b)); else { Binder *gen = gentempbinder(ptrtotype_(typeofexpr(bitword))); r = bitfieldvalue(a, m, mklet(gen, te_int, mkbinary(s_comma, mkbinary(s_assign, (Expr *)gen, mkunary(s_addrof,bitword)), bitfieldstuff(op, a, m, mkunary(s_content, (Expr *)gen), b)))); } if (h0_(r) == s_error) return errornode; /* for correct error messages and absence of warnings when assignment is voided. We rely on the form of r (and hence bitfieldvalue). */ return mkinvisible(type_(r), mk_expr2(op, ta, a, b), r); } /* mkincdec, mkaddr and mkassign deal with monadic and diadic operators which require an lvalue operand (this is assumed already checked). Many of these may turn into the pseudo-operator s_let to reduce CG complexity. Consider nasties like "int *f(); double *g(); *f() /= *g();" */ /* mkincdec and mkaddr never insert s_invisible nodes -- they leave the */ /* caller to do it -- is this right in retrospect? */ static Expr *mkincdec(AEop op, Expr *a) /* op can be ++ -- */ { TypeExpr *t = princtype(typeofexpr(a)); if (h0_(a) == s_error) return errornode; if (LanguageIsCPlusPlus && isprimtype_(t, s_bool)) { if (incdecisinc_(op)) { cc_warn(sem_warn_deprecated_bool, op); if (incdecispre_(op)) return mkbinary(s_comma, mkassign(s_assign, a, lit_true), a); else { Binder *gen = gentempbinder(te_boolean); Expr *b; b = mkbinary(s_comma, mkbinary(s_comma, mkassign(s_assign, (Expr *)gen, a), mkassign(s_assign, a, lit_true)), (Expr *)gen); return mklet(gen, te_boolean, b); } } else cc_rerr(sem_rerr_postdecr_bool, op); } { /* type check enough here for correct error msgs or extra param */ Expr *b = mkintconst(te_int, (incdecisinc_(op) ? 1 : -1), 0); /* The following test avoids warnings for "u--" where u is unsigned int */ /* and where -1 should be the bit pattern 0xffff. */ /* @@@ Reconsider the use of "--x" ==> "x=x+(-1) in the light of this. */ if (sizeof_int == 2 && !incdecisinc_(op)) { if (h0_(t) == s_typespec) { SET_BITMAP m = typespecmap_(t); if ((m & (bitoftype_(s_int)|bitoftype_(s_unsigned)| bitoftype_(s_long))) == (bitoftype_(s_int)|bitoftype_(s_unsigned)) || (m & (bitoftype_(s_char)|bitoftype_(s_unsigned))) == (bitoftype_(s_char)|bitoftype_(s_unsigned)) && feature & FEATURE_PCC) b = mkintconst(te_uint, 0xffff, 0); } } if (incdecispre_(op)) /* turn ++x to x+=1 */ return mkassign(s_plusequal, a, b); else return mkassign(s_postinc, a, b); /* let mkassign() do it - note that it 'knows' about s_postinc */ } } /* Add extra arg 'implicit' to mkaddr to unify code with coerceunary? */ static Expr *mkaddr(Expr *a) { TypeExpr *t, *tp; if (h0_(a) == s_error) return errornode; t = typeofexpr(a); tp = princtype(t); /* last_seen is a botch. Seen a type store reused! */ if (LanguageIsCPlusPlus) switch (h0_(tp)) { case t_coloncolon: { TagBinder *cl = typespectagbind_(tp); ClassMember *m = (ClassMember *)a; /* This (&A::a) is really just offsetof! */ /* Note, given class D:B {}, that the curious def of &D::b [ES, p55] */ /* being &B::b is necessary because of virtual bases. */ /* /* We accidentally get the type of &(B::b) wrong here. It should be */ /* as &(this->B::b) not as &B::b. */ a = mkaddr(mkfieldselector(s_arrow, nullptr(cl), m)); /* LDS - was: attributes_(m) & CB_ANON ? realbinder_(m) : m)) */ return h0_(a) == s_error ? errornode : mk_expr2_ptr(s_plus, ptrtotype_(t), a, lit_one); } case t_ovld: /* return mkaddr((Expr *)ovld_resolve_addr(a, typeovldlist_(tp))); */ if (h0_(a = (Expr *)ovld_resolve_addr(a, typeovldlist_(tp))) == s_error) return a; t = typeofexpr(a); if (h0_(princtype(t)) == t_ovld) break; /* else fall through */ case t_fnap: if (h0_(a) == s_dot) /* C++ member function */ return mkaddr(exprdotmemfn_(a)); if (h0_(a) == s_dotstar) /* see [ES, p71] */ { cc_err(sem_err_noncallsite_function); return errornode; } if (h0_(a) == s_binder && bindstg_(exb_(a)) & b_impl) { Binder *b = realbinder_(exb_(a)); if (!(suppress & D_CFRONTCALLER)) cc_warn(sem_warn_addr_of_memfn, b); if (bindstg_(b) & b_memfna) { if (bindstg_(b) & bitofstg_(s_virtual)) b = generate_wrapper(exb_(a)); t = (TypeExpr *)syn_list3(t_coloncolon, t, bindparent_(exb_(a))); } /* Take address of implementation but use type of member. */ /* Making a memfn behave like s_member in typeofexpr() would help here. */ a = (Expr *)b; } /* drop through */ } /* The following line handles the big kludge whereby pcc treats &a as */ /* &a[0]. Note that then we lie somewhat about the type as given, say, */ /* int a[5]; f(&a); we have a node &a with type (int *) but whose son */ /* is (int [5]). Still this does not worry optimise, the only code to */ /* look inside an & node. */ if (feature & FEATURE_PCC && h0_(tp) == t_subscript) t = typearg_(tp); /* The next line allows the offsetof() macro to reduce to a compile- */ /* time constant as ANSI require. @@@ Think a little more -- */ /* AM would like to keep all reductions together in trydiadreduce, */ /* but this means that re-arrangements have to be spotted early. */ /* This is the classical phase-order problem recurring. */ /* There are also ANSI-dubious things here about WHICH constant exprs. */ /* are allowed in various contexts. (e.g. array size, initialiser...) */ { int32 n = 0; Expr *q, *p = a; for (; p != NULL && (p = skip_invisible_or_cast(p)) != NULL; p = arg1_(p)) { if (h0_(p) == s_dot) { n += exprdotoff_(p); if (!(h0_(arg1_(p)) == s_content && h0_(arg1_(arg1_(p))) == s_integer)) continue; p = arg1_(arg1_(p)); } else if (h0_(p) == s_content && h0_(arg1_(p)) == s_plus && h0_(q = skip_invisible_or_cast(arg1_(arg1_(p)))) == s_integer && h0_(arg2_(arg1_(p))) == s_integer) { n += intval_(arg2_(arg1_(p))); p = q; } else break; return mk_expr2_ptr(s_plus, ptrtotype_(t), p, mkintconst(te_int, n, 0)); } } /* note that it has already been verified that a is an l-value if that is */ /* important. */ return mk_expr1(s_addrof, ptrtotype_(t), a); } static Expr *mkopassign(AEop op, Expr *asimple, Expr *b) { /* asimple must have passed issimplelvalue() or be otherwise reevalable */ /* @@@ review s_postinc the light of clumsy code for sizeof_int == 2. */ if (op == s_postinc) { b = mkbinary(s_plus, asimple, b); if ((mcrepofexpr(asimple) & MCR_SORT_MASK) == MCR_SORT_STRUCT) { TypeExpr *t = typeofexpr(asimple); Binder *gen = gentempbinder(t); b = mkbinary(s_comma, mkbinary(s_comma, mkassign(s_assign, (Expr *)gen, asimple), mkassign(s_assign, asimple, b)), (Expr *)gen); return mklet(gen, t, b); } return mkassign(s_displace, asimple, b); } else return mkassign(s_assign, asimple, mkbinary(unassignop_(op), asimple, b)); } static Expr *mkassign(AEop op, Expr *a, Expr *b) /* for = += *= ... also s_displace and s_postinc */ { TypeExpr *t1, *t1x; Expr *r; if (h0_(a) == s_error || h0_(b) == s_error) return errornode; check_index_dereference(a); t1 = typeofexpr(a); /* un-coerced type */ t1x = princtype(t1); if (!(suppress & D_STRUCTASSIGN) && (mcrepoftype(t1x) & MCR_SORT_MASK) == MCR_SORT_STRUCT) cc_warn(sem_warn_structassign); if (LanguageIsCPlusPlus && istypevar(t1x)) return mk_expr2(op, t1, a, b); if (LanguageIsCPlusPlus && isprimtype_(t1x, s_bool) && op != s_assign && op != s_displace && op != s_init) { cc_rerr(sem_rerr_opequal_bool, op); return errornode; } /* @@@ not clear this is in the right place -- ensurelvalue/mkassign */ if (LanguageIsCPlusPlus && h0_(t1) == t_coloncolon) { a = thisify(a); if (h0_(a) == s_error) return a; t1 = typeofexpr(a); } if (isbitfield_type(t1)) { TypeExpr *t2 = unbitfield_type(t1); /* @@@ Beware: the next cast to t2 may worsen code for char bitfields, */ /* but it is more correct than using te_int (e.g. warnings/enums). */ /* regalloc.c now optimises char casts followed by masks. */ /* However this doesn't happen yet (see the ONE_DAY_SOON test above). */ Expr *bb = mkcast(op, b, t2); a = skip_invisible(a); if (issimplevalue(b)) return bitfieldassign(op, a, t1, bb); else { TypeExpr *tt = bf_promotedtype(t1, exprbsize_(a)); Binder *gen = gentempbinder(tt); /* bf_promotedtype? */ /* The let statement here is so that any possible side-effects in the */ /* rhs can not cause confusion with the expansion of the bitfield */ /* assignment into shifts and masks. Without it x.a = x.b = nn can give */ /* trouble as the integer holding x can be loaded for the outer */ /* assignment before it is updated by the inner one. */ Expr *e = mkbinary(s_comma, mkbinary(s_init, (Expr *)gen, bb), bitfieldassign(op, a, t1, (Expr *)gen)); r = mklet(gen, typeofexpr(e), e); } } else if (h0_(a) == s_cond && op == s_assign) { /* This can only legitimately happen in C++, but the error action */ /* for C faced with i ? j : k = l is to generate the same tree as */ /* C++ does. */ if (h0_(b) == s_binder) r = mkcond(arg1_(a), mkbinary(s_assign, arg2_(a), b), mkbinary(s_assign, arg3_(a), b)); else if ((mcrepofexpr(b) & MCR_SORT_MASK) == MCR_SORT_STRUCT) r = mkbinary(s_assign, mkunary(s_content, mkcond(arg1_(a), mkaddr(arg2_(a)), mkaddr(arg3_(a)))), b); else /* We now expand to (let v = l in i ? j = l : k = l) */ /* in optimise1, since then there will be extra cases which */ /* don't at this stage have s_cond as top operator on the lhs */ r = mk_expr2(op, t1, a, b); } else if (op == s_assign || op == s_displace || op == s_init) { r = 0; /* not dead code */ if (LanguageIsCPlusPlus && op == s_init) { TypeExpr *pta = princtype(t1); if (isclasstype_(pta)) r = mkopap(op, typespectagbind_(pta), a, mkExprList1(b)); } if (r == 0) { b = mkcast(op, b, t1); r = (h0_(b) == s_error) ? errornode : mk_expr2(op, t1, a, b); } } else if (issimplelvalue_i(a, 0)) r = mkopassign(op, a, b); else if (issimplelvalue_i(a, allowpostinc)) { Expr *inc = NULL; Binder *gen = gentempbinder(t1); a = RemovePostincs(a, &inc); r = mklet(gen, t1, mkbinary(s_comma, mkbinary(s_comma, mkbinary(s_init, (Expr *)gen, mkopassign(op, a, b)), inc), (Expr *)gen)); } else { /* otherwise use a pointer in case side-effects - e.g. *f()+=1. */ Binder *gen = gentempbinder(ptrtotype_(t1)); r = mklet(gen, t1, mkbinary(s_comma, mkbinary(s_init, (Expr *)gen, mkaddr(a)), mkopassign(op, mkunary(s_content, (Expr *)gen), b))); } return h0_(r) == s_error ? errornode : h0_(r) == op ? r : mkinvisible(type_(r), mk_expr2(op, type_(r), a, b), r); } /* mkindex copes with indexing on a machine in which sizeof int and */ /* and sizeof long differ. Then we need a widen/narrow before index. */ /* The last two arguments provide for (constant) index checking. */ static Expr *mkindex(Expr *e, int32 stride, Expr *array, int posneg) { /* The code is marginally perverse here so that no tests are */ /* generated if sizeof_ptr/int/long are equal. */ if (sizeof_ptr == sizeof_int || sizeof_ptr == sizeof_long || sizeof_ptr == sizeof_longlong) { int32 n = sizeoftype(typeofexpr(e)); if (sizeof_ptr == sizeof_long && n != sizeof_long) e = coerce2(e, te_lint); if (sizeof_ptr == sizeof_int && n != sizeof_int) e = coerce2(e, te_int); } else syserr(syserr_mkindex); check_index_overflow(array, e, posneg, NO); return mkbinary(s_times, e, mkintconst((sizeof_ptr==sizeof_int ? te_int:te_lint),stride,0)); } Expr *mkbinary(AEop op, Expr *a, Expr *b) { TypeExpr *t1,*t2,*t3; if (op == s_init) /* merge with diadneedslvalue below? */ { Expr *c = mkassign(s_init, a, b); /* @@@ do we need an ensurelvalue() on a above for meminit of anonu's? */ if (/*LanguageIsCPlusPlus &&*/ /* We *need* to do this for "const int x = 8; int A[x];" etc. */ /* (But [ES] doesn't seem to say so.) */ /* Currently just save int/float values (possibly reduced from exprs) */ /* associated with 'const' binders. Should we do 'int *const x = &y;'? */ h0_(c) == s_init && arg1_(c) == a && h0_(a) == s_binder) /* and not b_member? */ { Expr *bb = skip_invisible(arg2_(c)); TypeExpr *t = bindtype_(exb_(a)); if ((h0_(bb) == s_integer || h0_(bb) == s_floatcon) && (qualifiersoftype(t) & bitoftype_(s_const) || istypevar(t))) { Expr *gb = globalize_expr(bb); /* @@@ over-sloppy! */ /* @@@ Binder's should have a bit to tell us local/global? */ bindconst_(exb_(a)) = gb; if (debugging(DEBUG_SYN)) cc_msg("const $b = $e\n", a, gb); } } return c; } if (diadneedslvalue_(op)) { Expr *c = mkassign(op, ensurelvalue(a,op), b); /* add an invisible node if expression was transformed (for errors) */ return (h0_(c) == s_error) ? errornode : (h0_(c) == op) ? c : (t1 = typeofexpr(c), mkinvisible(t1, mk_expr2(op,t1,a,b), c)); } if (h0_(a = coerceunary(a)) == s_error) return a; if (h0_(b = coerceunary_2(b, op==s_comma ? COERCE_COMMA : COERCE_NORMAL)) == s_error) return b; /* the next line checks and inserts !=0 in && ||. */ if (isboolean_(op)) { a = mktest(op,a); b = mktest(op,b); if (h0_(a) == s_error || h0_(b) == s_error) return errornode; } t1 = typeofexpr(a); t2 = typeofexpr(b); switch (op) /* special case type rules... generalise to table like lexclass? */ { case s_comma: a = mkcast(s_comma, a, te_void); if (h0_(a) == s_error) return errornode; /* note: ANSI forbids reduction of ',' operators */ return mk_expr2(op, t2, a, b); case s_subscript: if ((indexable(t1) && indexer(t2)) || (indexable(t2) && indexer(t1))) /* note that mkbinary() may permute (a,b) */ return mkunary(s_content, mkbinary(s_plus, a, b)); /* drop through */ typeclash(op); return errornode; case s_arrowstar: /* map x->*e to (*x).*e, i.e. fixup a,t1 and drop through. */ if (!indexable(t1)) goto clash; t1 = indexee(t1); a = mk_expr1(s_content, t1, a); /* drop through */ case s_dotstar: /* Here f().*e gives the same complications as in f().mem -- we want */ /* to select a field from a class which does not have an lvalue. */ /* Moreover, we don't wish to disturb the parse tree too much while */ /* we might still give errors. Hence leave s_dotstar for optimise() */ /* to remove since optimise() now ensures that such structs do get an */ /* l-value (beware 1-word ones!). Note that nowadays optimise should */ /* also transform s_dot to s_content too! Finally, we have to remember */ /* to check the use of s_dotstar on a 1-word structure in simplify.c. */ /* @@@ beware this code is (obviously) very similar to findfield UNIFY! */ { TypeExpr *t1c = princtype(t1), *t2e = princtype(t2); SET_BITMAP q = qualifiersoftype(t1); if (!(isclasstype_(t1c) && h0_(t2e) == t_content)) goto clash; t2e = typearg_(t2e); /* Do we need prunetype(t2e) here? Can one "typedef A::p, A::*q?;" */ if (h0_(t2e) != t_coloncolon) goto clash; if (typespectagbind_(t2e) != typespectagbind_(t1c)) { if (derived_from(typespectagbind_(t2e), typespectagbind_(t1c))) { t1c = tagbindtype_(typespectagbind_(t2e)); a = mkcast(s_cast, a, t1c); } else if (istypevar(tagbindtype_(typespectagbind_(t2e))) || istypevar(tagbindtype_(typespectagbind_(t1c)))) return errornode; } if (typespectagbind_(t2e) == typespectagbind_(t1c)) { TypeExpr *tr = mkqualifiedtype(typearg_(t2e), q); /* If second arg is a constant we should diadreduce to s_dot?? */ return mk_expr2(s_dotstar, tr, a, b); } } clash: typeclash(op); return errornode; case s_plus: if (indexable(t1) && indexer(t2)) return mk_expr2_ptr(op, t1, a, mkindex(b, strideofindexee(t1), a, 1)); if (indexable(t2) && indexer(t1)) #ifdef OLD_POINTER_PLUS return mk_expr2_ptr(op, t2, mkindex(a, strideofindexee(t2), b, 1), b); #else /* int+ptr is now treated as ptr+int, hence i[p], p[i] as *(p+i). */ return mk_expr2_ptr(op, t2, b, mkindex(a, strideofindexee(t2), b, 1)); #endif break; case s_minus: if (indexable(t1) && indexer(t2)) return mk_expr2_ptr(op, t1, a, mkindex(b, strideofindexee(t1), a, -1)); if (indexable(t1) && indexable(t2)) { /* Ignore top-level qualifiers as vals are rvalues. */ /* Also ignore (by unioning) qualifiers on pointed-to */ /* types. Use compositetype() to establish stride. */ /* @@@ ANSI is ambiguous on f(int (*a)[], int (*b)[3]) { return a-b; } */ TypeExpr *t3 = qualunion_compositetype(indexee(t1), indexee(t2)); if (t3) { /* The following line is the only use of s_ptrdiff */ /* which is only serves to stop check_narrow_subterm */ /* from issuing spurious warnings on */ /* long x = offsetof(..) */ Expr *actual = mk_expr2(s_ptrdiff, te_int, a, b); Expr *r = mk_expr2_ptr(op, te_int, a, b); int32 sizeof_t3 = sizeoftype(t3); /* the following helps the offsetof() macro used in */ /* static initialisers... */ if (sizeof_t3 != 1) r = mkbinary(s_div, r, mkintconst(te_int, sizeof_t3, 0)); if (sizeof_ptr != sizeof_int && sizeof_ptr != sizeof_longlong) /* Fix this more seriously one day? */ /* If so then review te_int in term for 'r'. */ syserr(syserr_ptrdiff); if (h0_(r) == s_error) return errornode; /* The invisible node is for correct error msgs */ return mkinvisible(te_int, actual, r); } } break; default: if (isrelational_(op)) { /* unify code with mkcond()... */ if (indexable(t1) && indexable(t2)) { /* ignore top-level qualifiers as vals are rvalues */ TypeExpr *t1a = indexee(t1), *t2a = indexee(t2); /* Now ignore qualifiers on pointed-to types, but see */ /* qualfree_equivtype() for a warning. */ if (!qualfree_equivtype(t1a,t2a)) { /* looks like a type error, but first check for */ /* C++ pointers to derived types */ TypeExpr* unused; if (!LanguageIsCPlusPlus || !common_pointer_type(op, t1, a, &a, t2, b, &b, &unused)) /* then if equality op and one arg is (void *) */ /* Note that (void *) types are tricky -- the null pointer constant */ /* (void *)0 is comparable with a fn, but no other (void *)values are. */ { if (!((op == s_equalequal || op == s_notequal) && (isvoidtype(t1a) && (!isfntype(t2a) || isnullptrconst(a))) || (isvoidtype(t2a) && (!isfntype(t1a) || isnullptrconst(b))))) cc_pccwarn(sem_rerr_different_pointers, op); } } return mk_expr2_ptr(op, te_boolean, a, b); } /* The following lines handle the case NULL == 0 (of integral type). */ if (indexable(t1) && indexer(t2)) return mk_expr2_ptr(op, te_boolean, a, pointerofint(b,op,t1)); if (indexable(t2) && indexer(t1)) return mk_expr2_ptr(op, te_boolean, pointerofint(a,op,t2), b); if (!isinequality_(op) && isptrtomember(t1) && indexer(t2)) return mk_expr2_ptr(op, t1, a, pointerofint(b,op,t1)); if (!isinequality_(op) && isptrtomember(t2) && indexer(t1)) return mk_expr2_ptr(op, t2, pointerofint(a,op,t1), b); } break; } /* all that SHOULD be left are the arithmetic types */ t3 = lubtype(op,t1,t2); /* BEWARE - see trydiadreduce below */ if (t3 == 0) return errornode; if (op == s_leftshift || op == s_rightshift) { /* done by lubtype() */ t2 = princtype(t2); if (int_islonglong_(typespecmap_(t2))) b = mkcast(s_leftshift, b, te_uint); } else a = coerce2(a, t3), b = coerce2(b, t3); { Expr *c = mk_expr2(op, ((isrelational_(op) || isboolean_(op)) ? te_boolean : t3), a, b); /* the next line relies on the form of result of lubtype() (q.v.) */ return trydiadreduce(c, typespecmap_(t3)); } } static int is_unrooted(Expr *e) { if (e == 0) return 1; else { Binder *b = exb_(e); if (h0_(b) == s_binder && bindsym_(b) == 0) /* nullbinder(cl)... */ return 1; if (h0_(e) != s_dot) return 0; } return is_unrooted(arg1_(e)); } Expr *mkfnap(Expr *e, ExprList *l) { TypeExpr *t; FormTypeList *d; bool curried = NO; Binder *fnb = NULL; Expr *let = NULL; Expr *firstarg = NULL; TypeExpr *tt; ScopeSaver tactuals = NULL; bool hasimplicitthis = NO; if (h0_(e) == s_error) return errornode; if (LanguageIsCPlusPlus) { TagBinder *cl = current_member_scope(); Expr *ee; ExprList *const origl = l; e = mkfnap_cpp(e, &l, &curried, &let, &firstarg); hasimplicitthis = origl != l; ee = skip_invisible(e); if (cl != NULL && tagactuals_(cl) != NULL && (h0_(ee) == s_binder && !is_local_binder(exb_(ee))) && !call_dependency_type(princtype(typeofexpr(ee)), tagactuals_(cl))) tactuals = tagactuals_(cl); } if (h0_(e) == s_binder) fnb = exb_(e); if (h0_(e = coerceunary(e)) == s_error) return e; t = typeofexpr(e); if (LanguageIsCPlusPlus && curried && h0_(t = princtype(t)) == t_content && h0_(tt = princtype(typearg_(t))) == t_coloncolon && h0_(t = princtype(typearg_(tt))) == t_fnap) d = mkFormTypeList(typefnargs_(t), 0, /* /* qualifiers? */ ptrtotype_(tagbindtype_(typespectagbind_(tt))), 0); else if (!curried && indexable(t) && (t = princtype(indexee(t)), h0_(t) == t_fnap)) d = typefnargs_(t); else { TagBinder *cl = current_member_scope(); if (!istypevar(t) && (!cl || !(tagbindbits_(cl) & TB_TEMPLATE))) cc_err(sem_err_nonfunction); return errornode; } /* Here we know: e is a (possibly instance of generic) function */ /* 'l' is the arg list (possibly adorned with 'this'), 'd' is the */ /* formal list (similarly adorned). 'curried' is a hack for C++ '->*' */ /* and 't' is the t_fnap type of 'e' (used for TypeFnAux). */ { /* Beware: this routine side-effects the structure of 'l'. */ /* @@@ This routine should also add default args. */ ExprList *ll, *lq = NULL; int argindex = hasimplicitthis ? 0 : 1; push_fnap_context(fnb); for (ll = l; ll != NULL; argindex++, lq = ll, ll = cdr_(ll)) { Expr *elt = exprcar_(ll); TypeExpr *formtype = NULL; /* avoid other error messages due to wrong no of args. */ if (h0_(elt) == s_error) { pop_fnap_context(); return errornode; /* e.g. syntax error */ } set_fnap_arg(argindex); /* For functions with narrow parameters (float, short, char), we normally * widen the corresponging actual arguments before passing, and narrow in * the called function (callee-narrowing). This is to some extent a space * against time tradeoff, but it also has the effect of * - allowing a function with narrow parameters to be called in the scope * of a declaration without prototype, or no declaration. (of course, * only if the corresponding arguments promote to the right type). * - making f(x) float x; {} function correctly when called in the scope * of a prototypr f(float x), even though the types aren't compatible. * (for which reason we merely warn of this incompatibility except in * strict ANSI conformance mode). * This behaviour is altered if CONFIG_UNWIDENED_NARROW_ARGS is set, in * which case arguments corresponding to narrow parameters are expected * to have been narrowed by the caller (and the warning above becomes an * error always). */ if (d != NULL) /* type of arg visible: prototype or previous K&R defn. */ { if (!typefnaux_(t).oldstyle) { /* prototype parameter */ Expr *x = elt, *originalx = elt; TypeExpr *fttype = d->fttype, *t2 = princtype(fttype); #ifdef PASCAL if ( h0_(fttype) != s_content || !is_conformant(typearg_(fttype))) { if (h0_(fttype->pun.type) == s_var) x = mkunary(s_addrof, x); if (h0_(fttype->pun.type) == s_addrof) { Binder *b; block_binders = syn_list2(block_binders, b = inst_decl(gensymval(1), typearg_(fttype), bitofstg_(s_auto), 0)); x = mkbinary(s_comma, mk_pas_assign(s_assign, (Expr *)b, x), mkunary(s_addrof, (Expr *)b)); } } #endif if (!(config & CONFIG_UNWIDENED_NARROW_ARGS) && h0_(t2) == s_typespec && is_float_(typespecmap_(t2))) { /* This code is to avoid a spurious warning when */ /* (float)+(float) is passed to a function with a */ /* prototype 'float' parameter with callee-narrowing */ TypeExpr *t1 = princtype(typeofexpr(x)); if (h0_(t1) == s_typespec && is_float_(typespecmap_(t1))) x = mkcast(s_cast, x, te_float); } x = mkcast(s_fnap, x, widen_formaltype(fttype)); if (tactuals != NULL && !call_dependency_type(typeofexpr(x), tactuals) && !call_dependency_val(originalx, tactuals)) { cc_err(sem_err_call_dependency, e, current_member_scope()); pop_fnap_context(); return errornode; } /* x = mkcast(s_fnap, coerceunary_2(x, COERCE_ASSIGN), */ /* widen_formaltype(fttype)); */ if (h0_(x) != s_error) { TypeExpr *t1 = princtype(typeofexpr(x)); if (isclasstype_(t1)) { TagBinder *cla = typespectagbind_(t1); /* class types which require construction are passed by reference and */ /* copy-constructed in the callee (see syn.c::rd_fndef()). */ if (TB_NOTPODU_(cla, TB_NEEDSCCTOR)) x = mkaddr(x); } exprcar_(ll) = x; } d = cdr_(d); continue; } else /* K&R style defn in scope: check if requested below. */ formtype = d->fttype, d = cdr_(d); } else if (h0_(tt = princtype(typeofexpr(elt))) == t_content && h0_(tt = typearg_(tt)) == t_ovld) /* The following line does a couple of things: it forces a diagnostic (no fn type can be te_void), and does a recoverery by forcing a choice of an overloaded instance. */ elt = mkaddr((Expr *)ovld_resolve_addr_2(s_fnap, te_void, typeovldlist_(tt), exb_(elt))); /* unchecked parameter or K&R (olde) style fn defn in scope. */ if (isvoidtype(typeofexpr(elt))) /* includes "const void" etc. */ { cc_err(sem_err_void_argument); pop_fnap_context(); return errornode; } /* unchecked or olde-style paramaters get a special coercion, */ /* which includes converting float to double. */ if (h0_(elt = coerceunary_2(elt, COERCE_ARG)) == s_error) { pop_fnap_context(); return elt; } exprcar_(ll) = elt; if (formtype != NULL && (feature & (FEATURE_PCC|FEATURE_FUSSY)) != FEATURE_PCC && !qualfree_equivtype(promoted_formaltype(formtype), typeofexpr(elt))) cc_warn(sem_warn_olde_mismatch, e); /* if TARGET_NULL_BITPATTERN != 0 and actual is (int)0 then warn if ... */ /* ... FEATURE_PREDECLARE or some such. */ } if (LanguageIsCPlusPlus) { if (lq != NULL) cdr_(lq) = exprlist_of_default_args(d, argindex); else l = exprlist_of_default_args(d, argindex); } { int32 len = length(l) - curried; /* we have to discount the addition to 'l' if curried (only). */ /* perhaps all non-static memfns should be seen as curried? */ if (debugging(DEBUG_TYPE)) cc_msg("fn $e(%ld..%ld) gets %ld args\n", e, (long)minargs_(t), (long)maxargs_(t), (long)len); if (!(minargs_(t) <= len && len <= maxargs_(t))) { if (typefnaux_(t).oldstyle) { if ((feature & (FEATURE_PCC|FEATURE_FUSSY)) != FEATURE_PCC) cc_warn(sem_rerr_wrong_no_args, e); } else cc_rerr(sem_rerr_wrong_no_args, e); } } if (!curried && fntypeisvariadic(t) && typefnaux_(t).variad > 0) /* ho-hum, lets see if there's an illegal printf/scanf! */ e = formatcheck(e, l, typefnargs_(t), typefnaux_(t).variad); e = mk_expr2(s_fnap, typearg_(t), e, (Expr *)l); pop_fnap_context(); } e = appendlet(let, e); /* The rationale for the following line (relevance to C++ only) In e.f(), e has to be evaluated. If f is a static member, e will not be in the args list and has to be explicitly captured in a s_comma node such that e.f() ==> (e,f()). It used to be e.f() => (e,f)() but that prevents static inlining from happening. */ return (firstarg) ? mkbinary(s_comma, /* cast to void to avoid no side-effect warning */ mkcast(s_cast|s_qualified, firstarg, te_void), e) : e; } static Expr *pointercast(AEop op, Expr *e, TypeExpr *te, TypeExpr *tr) { int err; /* Here we have a cast from pointer-to-te to a pointer-to-tr. */ /* Moan while doing so for unsuitable implicit casts. */ /* The Oct 88 draft clarifies that void pointers ARE required */ /* to respect const/volatile qualification too. */ if (op == s_cast) err = 0; else { SET_BITMAP q = qualifiers_lost(te, tr); int errq = (q == 0) ? 0 : 1; if (qualfree_equivtype(te, tr) || isvoidtype(tr)) { if (q == bitoftype_(s_unaligned) && isprimtype_(tr, s_char)) err = 0; else err = errq; } else if (!(feature & FEATURE_CPP) && isvoidtype(te)) { /* illegal in C++, so (later optionally) warn in ANSI C. */ #ifndef FOR_ACORN if (!errq) cc_ansi_warn(sem_warn_narrow_voidstar); #endif err = errq; } else if (istypevar(te) || istypevar(tr)) err = 0; else err = errq | 2; if (err && !(suppress & D_IMPLICITCAST)) { if (err & 2) cc_pccwarn(sem_rerr_implicit_cast1, op); else if (LanguageIsCPlusPlus && q == bitoftype_(s_const) && h0_(e) == s_invisible && isstring_(h0_(orig_(e)))) cc_warn(sem_warn_depr_string, op); else cc_pccwarn(sem_rerr_implicit_cast5, op, q); } } return e; } static void check_narrowing_cast(AEop op, SET_BITMAP from, SET_BITMAP to) { if (op == s_cast); /* all OK */ else if (to & bitoftype_(s_enum)) { /* A cast from a type to itself cannot come here, so this is */ /* implicit cast from arith type to a different enum type. */ cc_rerr_cwarn(sem_rerr_casttoenum, op, from); } else if (/* moan at long int -> int/char */ ((to & (bitoftype_(s_long)|bitoftype_(s_int))) == bitoftype_(s_int) || (to & bitoftype_(s_char)) != 0) && (from & (bitoftype_(s_long)|bitoftype_(s_int))) == (bitoftype_(s_long)|bitoftype_(s_int)) || /* any floating type to any shorter floating type */ (to & bitoftype_(s_double)) && (from & bitoftype_(s_double)) && (to & ~from & bitoftype_(s_short) || from & ~to & bitoftype_(s_long)) || /* any floating type to any integral type */ (to & INTEGRALTYPEBITS && (from & bitoftype_(s_double))) /* any other ideas at what to moan at? */ ) { if (suppress & D_IMPLICITNARROWING) xwarncount++; else cc_warn(sem_warn_narrowing, op); } } /* tidy up relationship with coerce2() */ Expr *mkcast(AEop op, Expr *e, TypeExpr *tr) { TypeExpr *te, *x, *y, *xp, *yp; Expr *r; SET_BITMAP m; bool no_redundant = (op != s_cast); /* note s_cast|s_qualified */ if (h0_(e) == s_error) return errornode; op &= ~s_qualified; if (LanguageIsCPlusPlus && (r = cpp_mkcast(op, &e, tr)) != NULL) return r; e = isvoidtype(tr) ? coerceunary_2(e, COERCE_VOIDED) : (op == s_cast) ? coerceunary(e) : /* coerce most things but not enum->int. */ coerceunary_2(e, COERCE_ASSIGN); if (h0_(e) == s_error) return e; te = typeofexpr(e); /* check te,tr match enough ... */ switch (qualfree_equivtype(te,tr)) { case 2: if (no_redundant) /* if no_redundant and te and tr are IDENTICAL types we needn't store the cast. */ return e; if (feature & FEATURE_TELL_PTRINT) cc_warn(sem_warn_cast_sametype); /* drop through */ case 1: /* permissible cast */ break; case 0: /* not obviously permissible, check more */ x = princtype(tr), y = princtype(te); /* lose quals as rvalues */ /* If one of them is an unknown type, just turn it into an error but without reporting as such. */ if (h0_(x) == t_unknown || h0_(y) == t_unknown) return errornode; #ifdef TARGET_IS_ARM_OR_THUMB /* /* LDS: for now, until policy is agreed */ if (op != s_cast || feature & FEATURE_ANOMALY) #endif (void)check_narrow_subterm(e, y, x); switch (h0_(x)) { case t_content: /* cast to pointer. */ if (isnullptrconst(e)); /* always ok */ else if (xp = princtype(x = typearg_(x)), h0_(y) == t_content || h0_(xp) == t_fnap) { /* cast from ptr type or any cast to fn ptr... */ /* AM finds the dataflow hard to follow here... */ if (h0_(y) == t_content) yp = princtype(y = typearg_(y)); else yp = y; if ((h0_(xp) == t_fnap) != (h0_(yp) == t_fnap)) { if (op != s_cast) { if (suppress & D_CAST) cc_warn(sem_warn_fn_cast, op); else cc_pccwarn(sem_warn_fn_cast, op); } else if ((!(feature & (FEATURE_PCC|FEATURE_LIMITED_PCC) || suppress & D_IMPLICITCAST))) cc_warn(sem_warn_fn_cast, op); /* AM: the following reflects a bug (fix) in the interface aetree->cg. */ /* There is danger here if a local static array, or address of a local var */ /* is being cast to a fn ptr type - the Expr tree will contain a structure */ /* like (addrof (binder name)) or (binder name) with type t_subscript ... */ /* which cg.c will interpret as a literal name of a function, fatally... */ /* (Indeed such a thing MUST NOT become external for fear of name clashes) */ /* To fool cg.c into generating a J_CALLR with an appropriate expression, */ /* we turn such structures into (plus (addrof (binder name)) 0). The + 0 */ /* gets optimised out, so this costs nothing in the generated code. */ /* N.B. Doing this so calls to extern arrays still get done via J_CALLK */ /* is tricky... it's not clear that it's worth it... */ /*/* would this be better inside an invisible node? */ /* the s_plus is visible when you do */ /*'typedef void (*FP)(); int a[]; void f() { (FP)a; }' */ if (h0_(xp) == t_fnap && (h0_(e) == s_cast || h0_(princtype(te)) == t_content)) { /* possible cast of dangerous expr to fn type... */ /* ...unless straight cast to extern array... */ if (h0_(e) != s_invisible || h0_(r = arg1_(e)) != s_binder || !(bindstg_(exb_(r)) & bitoftype_(s_extern))) e = mk_expr2(s_plus, te, e, globalize_int(0)); } } else { /* e has type pointer-to-y and tr is pointer-to-x. */ if (LanguageIsCPlusPlus) e = cpp_ptrcast(op,e,y,x,t_content); else e = pointercast(op,e,y,x); } } #ifdef TARGET_IS_ALPHA /* These TARGET_IS_ALPHA parts are temporary; (a) while porting */ /* to 64-bit hosting and (b) until we decide what we really want. */ else if (isprimtypein_(y,bitoftype_(s_int))) /* bool and char (should have) been widened here. */ /* check this is so >>> s_bool <<< */ { SET_BITMAP m = typespecmap_(y); /* The next line is probably a noop if sizeof_int==sizeof_ptr, but */ /* is overkeen on the alpha (e.g. faults (int *)1;) */ if (sizeof_ptr > int_decodelength_(m)) cc_rerr("cast to pointer from too-small $m", m); /* PTRINT */ else if (op != s_cast) { if (!(suppress & D_IMPLICITCAST)) cc_pccwarn(sem_rerr_implicit_cast2, op); } } #else /* TARGET_IS_ALPHA */ else if (isprimtypein_(y,bitoftype_(s_int)|bitoftype_(s_bool))) { if (op != s_cast) { if (!(suppress & D_IMPLICITCAST)) cc_pccwarn(sem_rerr_implicit_cast2, op); } } #endif /* TARGET_IS_ALPHA */ else { if (!(suppress & D_CAST)) { cc_err(sem_err_bad_cast, op, y); return errornode; } cc_warn(sem_err_bad_cast, op, y); } break; case s_typespec: m = typespecmap_(x); switch (m & -m) /* LSB - unsigned/long etc. are higher */ { case bitoftype_(s_bool): if (!isprimtype_(y, s_bool)) { if ((h0_(e) != s_integer || (intval_(e) != 0 && intval_(e) != 1))) cc_warn(sem_warn_unusual_bool, op); e = mktest(op, e); } break; case bitoftype_(s_int): #ifdef TARGET_IS_ALPHA if (h0_(y) == t_content) { /* cast ptr->int: check enough bits. */ if (sizeof_ptr > int_decodelength_(m)) cc_rerr("cast from pointer to too-small $m", m); else if (op == s_cast) #else /* TARGET_IS_ALPHA */ if (h0_(y) == t_content && !int_isshort_(m)) { /* the only valid coercion from pointer */ if (op == s_cast) #endif /* TARGET_IS_ALPHA */ { if (feature & FEATURE_TELL_PTRINT) /* police pointer purity */ cc_warn(sem_warn_pointer_int); } else { if (!(suppress & D_IMPLICITCAST)) cc_pccwarn(sem_rerr_implicit_cast3, op); } break; } /* For some odd reason 'case 3.4:' is a constraint violation in ANSI C */ /* but seems valid in C++ (but it will give a warning for implicit */ /* cast to the (INTEGRAL) type of the controlling switch. */ if ((op == s_switch || op == s_subscript || (op == s_case && !LanguageIsCPlusPlus)) && isprimtype_(y,s_double)) { cc_pccwarn(sem_rerr_implicit_cast4,op,y); break; } /* drop through */ case bitoftype_(s_char): case bitoftype_(s_enum): case bitoftype_(s_double): if (h0_(y) != s_typespec || !(typespecmap_(y) & ARITHTYPEBITS)) { /* This recovery is by and large OK for all Codemist back-ends. */ /* /* @@@ AM However, it currently kills (syserr()) cg.c if just one of */ /* x and y is an integer-like struct. Fix. */ /* Also consider making a fn out of the following to remove */ /* near duplication of code in the next case, but only if the text of */ /* the ...cast1 and ...cast2 messages can be unified. */ /* @@@ relaxation guarded by FEATURE_PCC until cg.c can stop syserr()ing. */ if (feature & FEATURE_PCC && sizeoftype(x) == sizeoftype(y) && alignoftype(x) <= alignoftype(y)) { /* same size, dest no more aligned than src */ cc_pccwarn(sem_err_bad_cast1, op, x); break; } else { if (!(suppress & D_CAST)) { cc_err(sem_err_bad_cast1, op, x); return errornode; } cc_warn(sem_err_bad_cast1, op, x); } } check_narrowing_cast(op, typespecmap_(y), typespecmap_(x)); break; case bitoftype_(s_struct): case bitoftype_(s_class): case bitoftype_(s_union): /* @@@ relaxation guarded by FEATURE_PCC until cg.c can stop syserr()ing. */ if (feature & FEATURE_PCC && sizeoftype(x) == sizeoftype(y) && alignoftype(x) <= alignoftype(y)) /* same size, dest no more aligned than src */ cc_pccwarn(sem_err_bad_cast2, op, x); else { cc_err(sem_err_bad_cast2, op, x); return errornode; } break; case bitoftype_(s_void): /* Warn for casts unless explicit or already voided */ /* Macro:s like getc() or pop() in void context */ /* need explicit casts to suppress warnings. */ if (op != s_cast && !isprimtype_(y,s_void)) e = mkvoided(e); break; default: syserr(syserr_mkcast, (long)h0_(x), (long)typespecmap_(x)); return errornode; } break; default: syserr(syserr_mkcast1, (long)h0_(x)); return errornode; case t_fnap: case t_subscript: cc_err(sem_err_bad_cast1, op, x); return errornode; /* improve */ } } r = mk_expr1(s_cast, tr, e); r = trycastreduce(e, tr, r, op==s_cast); return castfn(r); } static Expr *findfield(AEop op, TypeExpr *te, ClassMember *member) { Expr *path; TagBinder *b; TypeExpr *t = princtype(te); if (!isclasstype_(t)) { if (!istypevar(t)) cc_err(sem_err_illegal_loperand, op); return errornode; } b = typespectagbind_(t); if (!(tagbindbits_(b) & TB_DEFD)) { cc_err(sem_err_undef_struct, b); return errornode; } #if 0 /* get rid of path_t0_member handling memfn call */ if (h0_(member) == s_binder && isfntype(bindtype_(member))) { if (bindstg_(member) & b_memfna) path = mk_exprwdot(s_dot, bindtype_(member), (Expr *)mk_binder(0, u_referenced, t), (IPtr)member); else path = (Expr *)member; } else #endif path = path_to_member(member, b, INDERIVATION); if (path == NULL) { /* failed to find a real data member... */ cc_err(sem_err_unknown_field, b, h0_(member) == s_identifier ? (Symstr *)member:memsv_(member)); path = errornode; } return path; } static Expr *mkdotable(AEop op, Expr *e) { TypeExpr *te; /* The next line effectively a no-op for C but C++ can coerce values */ /* of type (struct x &) implicitly to type (struct x). */ /* It needs to be done for case s_arrow anyway (e.g. array->foo). */ if (h0_(e = coerceunary(e)) == s_error) return e; te = princtype(typeofexpr(e)); if (op == s_arrow) { /* treat x->a as (*x).a. */ if (indexable(te)) return mk_expr1(s_content, indexee(te), e); } else if ((op == s_dot || op == s_qualdot) && isclasstype_(te)) return e; if (!istypevar(te)) typeclash(op); return errornode; } Expr *rooted_path(Expr *path, SET_BITMAP qualifiers, Expr *root) { Expr *e = path; TypeExpr *rt = typeofexpr(root); for (e = path; (h0_(e) == s_dot || h0_(e) == s_qualdot || h0_(e) == s_content); e = arg1_(e)) { Binder *b = exb_(arg1_(e)); if (b == NULL || qualfree_equivtype(typeofexpr(arg1_(e)), rt) || h0_(b) == s_binder && bindsym_(b) == 0) { /* unrooted or rooted in a class nullbinder()... */ /* the case for qualfree_equivtype, considers struct B {T m;}; struct D : B {}; T B::*x = &D::m; also the following adjustment is required, considers struct Z : D {}; Z z; z.*x; */ if (b != NULL && isclasstype_(bindtype_(b)) && isclasstype_(rt) && (b = (ClassMember *) derived_from(typespectagbind_(bindtype_(b)), typespectagbind_(rt))) != 0) root = mkfieldselector(s_dot, root, b); /* @@@ rely upon interchangeable layout of core of C and C here */ arg1_(e) = root; if (h0_(type_(path)) == t_coloncolon) type_(path) = typearg_(type_(path)); if (qualifiers != 0) type_(e) = mkqualifiedtype(type_(e), qualifiers); break; } } return path; } Expr *mkfieldselector(AEop op, Expr *e, ClassMember *mem) { TypeExpr *te; Expr *path; e = mkdotable(op, e); if (h0_(e) == s_error) return errornode; te = typeofexpr(e); if (h0_(mem) == s_identifier || h0_(mem) == s_binder || h0_(mem) == s_member) path = findfield(op, te, mem); else path = (Expr *)mem; { SET_BITMAP q = qualifiersoftype(te); if (isunaligned_type(te)) q |= bitoftype_(s_unaligned); return rooted_path(path, q, e); } } Expr *mkcond(Expr *a, Expr *b, Expr *c) { Expr *r; TypeExpr *t, *t1, *t2; a = mktest(s_cond, a); /* checks type of a */ if (h0_(a) == s_error) return a; /* Slightly odd code for C++ cond: if b and c are same enum, then one */ /* presumes result is enum, otherwise int. [ES] silent, check std. @@@ */ /* ANSI C doesn't care since implicit int->enum is OK. */ if (sameenum(t1 = typeofexpr(b), t2 = typeofexpr(c))) { if (isbitfield_type(t1)) { t1 = princtype(t1); t = primtype2_(typespecmap_(t1) & ~BITFIELD, typespectagbind_(t1)); } else t = t1; } else if (h0_(b = coerceunary(b)) == s_error) return b; else if (h0_(c = coerceunary(c)) == s_error) return c; else if (t1 = typeofexpr(b), t2 = typeofexpr(c), /* C++: the next line is a lie [ES book]. (Because Lvalue conds?) */ /* since we are in r-value context, we can ignore qualifiers: */ t1 = princtype(t1), t2 = princtype(t2), (isclasstype_(t1) && isclasstype_(t2)) && ((t = qualunion_compositetype(t1,t2)) != 0 || common_reference_type(s_cond, t1, b, &b, t2, c, &c, &t))) /* nothing */; /* for C++ lvalue cond the next lines need changing too. */ /* Since cond's give rvalues the qualifiers on the result are */ /* irrelevant. However, if you wish to support (for PCC mode) */ /* "struct s { int m[10]; }; const struct s x;" */ /* "volatile struct s y; int *q = (p()?x:y).m" */ /* then you had better review the princtype() above and decide */ /* which qualifiers q needs to have. */ /* @@@ unify code with isrelational_() call above? */ else if (indexable(t1) && indexable(t2)) { /* Note this includes x?(void *)0:(void *)0 which the dec 88 */ /* ansi draft leaves (seemingly to AM) undefined. */ /* Note also that (x?(void *)0:(int *)z) has type (int *) but */ /* (x?(void *)y:(int *)z has type (void *). */ /* The rationale is that nullpointer constants (0 or (void*)0) */ /* must behave the same, but that void * values may be wider */ /* that int * values (e.g. a word-addressed machine). */ TypeExpr *t1x = indexee(t1), *t2x = indexee(t2); if (isnullptrconst(b)) t = t2; else if (isnullptrconst(c)) t = t1; else if (isvoidtype(t1x) && !isfntype(t2x)) t = ptrtotype_(mkqualifiedtype(t1x, qualifiersoftype(t2x))); else if (isvoidtype(t2x) && !isfntype(t1x)) t = ptrtotype_(mkqualifiedtype(t2x, qualifiersoftype(t1x))); else if ((t = qualunion_compositetype(t1x,t2x)) != 0) t = ptrtotype_(t); else if (!LanguageIsCPlusPlus || !common_pointer_type(s_cond, t1, b, &b, t2, c, &c, &t)) /* fix up to *some* type. */ t = t1, cc_rerr(sem_rerr_cant_balance, s_cond); } else if (indexable(t1)) /* Similarly note x?0:(void *)0 is unclear. */ c = mkcast(s_cond, c, t1), t = (h0_(c) == s_error ? 0 : t1); else if (indexable(t2)) b = mkcast(s_cond, b, t2), t = (h0_(b) == s_error ? 0 : t2); else if (isvoidtype(t1) && isvoidtype(t2)) /* note t1/t2 may be qualified void, but irrelevant on rvalues. */ t = te_void; else if (LanguageIsCPlusPlus && (isptrtomember(t1) || isptrtomember(t2))) { if (isnullptrconst(b)) t = t2; else if (isnullptrconst(c)) t = t1; else if (equivtype(t1, t2)) t = t1;/* @@@ need to allow 'int D::* p = &B::i;', etc. */ else /* fix up to *some* type. */ t = t1, cc_rerr(sem_rerr_cant_balance, s_cond); } else t = lubtype(s_cond,t1,t2); if (t == 0) return errornode; b = coerce2(b,t); c = coerce2(c,t); r = mk_expr3(s_cond,t,a,b,c); if (h0_(a) != s_integer) return r; /* else simplify. However, we must not allow (1 ? x : 2) look like an lvalue. Moreover, given we have already reduced b and c these may have divided by zero. Think more. Leave an s_invisible node or an s_integer node (the later if further reductions may be possible) */ /* @@@ (See also trydiadreduce()). It would seem that the following */ /* code can contravene the ANSI draft in that it also reduces */ /* int x[(1 ? 2:(0,1))] to int x[2], which silently misses a constraint */ /* violation that the comma operator shall not appear in const exprs. */ /* Similarly x[1 ? 2 : f()]. AM thinks the ANSI draft is a mess here. */ return mkinvisible(t, r, intval_(a) ? b : c); } void sem_init(void) { static Expr errorexpr = { s_error }; errornode = &errorexpr; } /* End of sem.c */
stardot/ncc
arm/uasm.c
/* * arm/uasm.c, version 1b * Copyright (C) Acorn Computers Ltd., 1988. * Copyright (C) Codemist Ltd., 1988. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ * Checkin $Date$ * Revising $Author$ */ #ifndef NO_VERSION_STRINGS extern char uasm_version[]; char uasm_version[] = "\narm/uasm.c $Revision$ 1a\n"; #endif /* *(hacked from c.armasm by <NAME> to output unix arm assembler) *@@@ AM: the files are sufficiently similar that I would have thought *@@@ conditional assembly sufficed. Moreover this eases maintenance *@@@ Moreover, the maybe_import/export junk acquired from the arthur *@@@ assembler bug could be much simplified here. */ /* Assembler output is routed to asmstream, annotated if FEATURE_ANNOTATE. */ /* /* ACN: Alignment of the diaplyed output is inconsistent in this case. */ /* See c.armobj for more details of data structures. */ /* exports: asmstream, display_assembly_code, asm_header, asm_trailer also decode_instruction(w, 0, 0) for use outside compiler */ #ifdef __STDC__ #include <string.h> /* for strncmp */ #else #include <strings.h> /* for strncmp */ #endif #include <ctype.h> #include "globals.h" #include "mcdep.h" #include "store.h" #include "codebuf.h" #include "builtin.h" #include "xrefs.h" #include "ops.h" #include "version.h" #include "mcdpriv.h" #include "errors.h" #include "disass.h" FILE *asmstream; #ifndef NO_ASSEMBLER_OUTPUT static char *regnames[16] = {"r0","r1","r2","r3","r4","r5","r6","r7", "r8","r9",0,0,0,0,"lr","pc"}; /* others filled in when pcs is set */ static char * const fregnames[8] = {"f0","f1","f2","f3","f4","f5","f6","f7"}; static void newline() { fputc('\n', asmstream); } void asm_setregname(int regno, char *name) { regnames[regno] = name; } #define annotations (feature & FEATURE_ANNOTATE) #define INSTRUC 1 #define NUMB 0 static void pr_chars(int32 w, int n) /* works on both sex machines */ { int i, c; fputc('\"', asmstream); for (i = 0; i < n; i++) { switch (c = ((unsigned char *)&w)[i]) { case '\\': case '\'': case '\"': break; case BELL: c = 'a'; break; case '\b': c = 'b'; break; case CHAR_FF: c = 'f'; break; case '\n': c = 'n'; break; case CHAR_CR: c = 'r'; break; case '\t': c = 't'; break; case CHAR_VT: c = 'v'; break; default: if (c < ' ' || c >= 127) fprintf(asmstream, "\\%o", c); else putc(c, asmstream); continue; } putc('\\', asmstream); putc(c, asmstream); } fputc('\"', asmstream); } static void spr_asmname(char *buf, Symstr const *sym) { char const *s = symname_(sym); if (sym == bindsym_(datasegment)) sprintf(buf, "L__dataseg"); else if (strncmp( s, "x$", 2) != 0) sprintf(buf, "_%s", s); else sprintf(buf, "%s", s+2); } static void pr_asmname(Symstr const *sym) { char buf[256]; spr_asmname(buf, sym); fputs(buf, asmstream); } static Symstr *find_extsym(int32 p) { CodeXref *x; for (x = codexrefs; x != NULL; x = x->codexrcdr) { if (p == (x->codexroff & 0x00ffffffL)) return(x->codexrsym); } syserr(syserr_find_extsym); return(NULL); } static List *litlabels; static int32 asm_codesize; /*@@@ AM: never really used. */ static char *asm_needslabel; /* a bitmap */ static List *asm_imported; #define needslabel(widx) (asm_needslabel[(widx) >> 3] & (1 << ((widx)&7))) #define setlabbit(widx) (asm_needslabel[(widx) >> 3] |= (1 << ((widx)&7))) static int32 LiteralBefore(int32 target) { List *p; for (p = litlabels; p != NULL; p = cdr_(p)) if (car_(p) <= target) return car_(p); return 0; } static void NoteLiteralLabel(int32 q) { if (needslabel(q / 4)) litlabels = (List *)global_cons2(SU_Other, litlabels, q+codebase); } static void printlabelname(char *buf, char const *before, char const *after, int32 offset, Symstr const *sym) { /* For data references, ignore the function name: it will be wrong for backward * references to the literal pool of another function. (Labels which are the * subject of data references have already been removed from asm_lablist). * For code references, generate a label of the form L<address>.J<label>.<proc>. */ LabList *p; char const *s; if (sym == NULL) s = "__OutsideFunction__"; else s = symname_(sym); for ( p = asm_lablist ; p != NULL ; p = p->labcdr) { LabelNumber *lab = p->labcar; if ((lab->u.defn & 0x00ffffff) == offset) sprintf(buf, "%sL%06lx.J%ld.%s%s", before, offset+codebase, lab_name_(lab) & 0x7fffffff, s, after); } sprintf(buf, "%sL%06lx%s", before, offset+codebase, after); } static Symstr *procname; typedef struct RelAddrRec { Symstr *sym; int32 count; int32 offset; char *buf; char *dis_limit; } RelAddrRec; static char *disass_adrl(RelAddrRec *r, char *buf, int32 offset) { int pos = (r->buf[3] == 'S' || r->buf[3] == ' ') ? 3 : 5; int c = r->buf[pos]; do buf--; while (buf[-1] != ','); memcpy(r->buf, "ADR", 3); while (--r->count >= 0) r->buf[pos++] = 'L'; r->buf[pos] = c; sprintf(buf, "%ld+", offset); buf += strlen(buf); spr_asmname(buf, r->sym); return buf; } static char *disass_cb(dis_cb_type type, int32 offset, unsigned32 address, int w, void *cb_arg, char *buf) { RelAddrRec *r = (RelAddrRec *)cb_arg; IGNORE(w); *buf = 0; if (type == D_BORBL) { r->dis_limit = buf; if (r->sym == NULL) printlabelname(buf, "", "", address, procname); else spr_asmname(buf, r->sym); } else if (type == D_ADDPCREL) { r->dis_limit = buf; if (r->sym != NULL) buf = disass_adrl(r, buf, offset + r->offset + address); else printlabelname(buf, "#", "-.-8", address+offset, procname); } else if (type == D_SUBPCREL) { r->dis_limit = buf; if (r->sym != NULL) buf = disass_adrl(r, buf, address - offset - r->offset); else { /* Backward reference to a string may be to an address part way through a literal in a different function, for which therefore no label was generated. (Hence the list litlabels). */ int32 target = address - offset + codebase; int32 litaddr = LiteralBefore(target); if (litaddr == target) printlabelname(buf, "#.+8-", "", address - offset, procname); else { char b[8]; sprintf(b, "+%ld)", target - litaddr); printlabelname(buf, "#.+8-(", b, litaddr - codebase, procname); } } } else if (type == D_LOADPCREL || type == D_STOREPCREL) { /* Backward references here can't currently be to an address for which no label was generated (loading as an integer the second word of a double constant or some non-initial word of a string are the possibilities, which literal pool management currently precludes). Still, we allow the possibility for safety. */ int32 target = address + codebase; int32 litaddr = offset >= 0 ? target : LiteralBefore(target); r->dis_limit = buf; if (litaddr == target) printlabelname(buf, "[pc, #", "-.-8]", address, procname); else { char b[8]; sprintf(b, "+%ld)-.-8", target - litaddr); printlabelname(buf, "[pc, #(", b, litaddr - codebase, procname); } } else if (type == D_LOAD || type == D_STORE) { if (r->sym != NULL) { r->dis_limit = buf; sprintf(buf, "%ld+", offset); buf += strlen(buf); spr_asmname(buf, r->sym); } } return buf+strlen(buf); } static void maybe_export(Symstr *sym) { char *p = symname_(sym); char c; ExtRef *x; /* Unless external there is nothing to do here. */ if ((x = symext_(sym)) != 0 && (x->extflags & xr_defext) == 0) return; /*@@@ AM does not see how the following can ever now happen as x$dataseg etc. */ /*@@@ are very local statics. Is this if error recovery inserted gensyms? */ while ((c = *p++) != 0) { /* look for odd characters in x$dataseg etc */ if (!(isalnum(c) || (c == '_'))) return; } { FILE *as = asmstream; fprintf(as, " .global "); pr_asmname(sym); fputs("\n", as); } } static void killasmlabel(int32 wordoffset) { /* Ensure that jopcode labels are present only for instructions, not data items */ LabList *p, *prev = NULL; int32 offset = wordoffset * 4L; for ( p = asm_lablist ; p != NULL ; prev = p, p = p->labcdr) if ((p->labcar->u.defn & 0x00ffffff) == offset) { p = (LabList *) discard2((List *) p); if (prev == NULL) asm_lablist = p; else prev->labcdr = p; return; } } static void asm_scancode(void) { int32 p; int bitmapsize; char *x; bitmapsize = (int)((codep + 127) >> 5); /* > 1 bit per word of code */ asm_needslabel = x = (char *)BindAlloc(bitmapsize); memclr((VoidStar)x, bitmapsize); for (p = 0; p < codep; p += 4) { int32 w = code_inst_(p); int32 f = code_flag_(p); switch (f) { case LIT_RELADDR: break; case LIT_OPCODE: switch (w & 0x0f000000) { case OP_B: case OP_BL: if (w & 0x00800000L) w |= 0xff000000L; else w &= 0x00ffffffL; w = (p / 4L) + 2L + w; /* word index */ setlabbit(w); break; case OP_PREN: if (((w >> 16L) & 0xfL) == R_PC) { int32 d = w & 0xfffL; if ((w & F_UP)==0) d = -d; w = (p + 8L + d) / 4L; setlabbit(w); killasmlabel(w); } break; case 0x02000000L: { int32 op = w & (0xfL << 21L); if ( (op == F_ADD || op == F_SUB) && (((w >> 16L) & 0xfL) == R_PC)) { int32 shift = (w & 0xf00)>>7, val = w & 0xff; val = (val>>shift) | (val<<(32-shift)); if (op == F_SUB) val = -val; w = (p + 8L + val) / 4L; setlabbit(w); killasmlabel(w); } } break; case OP_CPPRE: if (((w >> 16L) & 0xfL) == R_PC) { int32 d = w & 0xffL; if ((w & F_UP)==0) d = -d; w = (p + 8L) / 4L + d; setlabbit(w); killasmlabel(w); } break; default: break; } default: break; } } } static void pr_common_defs(void) { ExtRef *x; FILE *as = asmstream; int n_comm = 0; obj_symlist = (ExtRef *)dreverse((List *)obj_symlist); /* oldest = smallest numbered first */ for (x = obj_symlist; x != 0; x = x->extcdr) { int flags = x->extflags; int32 sz = x->extoffset; if ((x->extindex > 1) && (sz > 0) && ((flags & (xr_defloc | xr_defext)) == 0)) { if (n_comm == 0) {++n_comm; fputs("\n", as);} fprintf(as, " .comm "); pr_asmname(x->extsym); fprintf(as, ", %lu\n", sz); } } } /* exported functions ...*/ static void disassemble(int32 w, int32 q, Symstr *sym, RelAddrRec *r) { r->sym = sym; r->offset = 0; r->count = 0; r->dis_limit = NULL; disass(w, q, r->buf, (void *)r, disass_cb); { char *cp, *end = (r->dis_limit == 0) ? r->buf + strlen(r->buf) : r->dis_limit; for (cp = r->buf; cp != end; cp++) { char ch = *(unsigned char *)cp; if (isupper(ch)) *cp = tolower(ch); } } fprintf(asmstream, " %s", r->buf); } void display_assembly_code(Symstr *name) { int32 q, lastline = -1; FILE *as = asmstream; Symstr *sym; RelAddrRec r; char buf[256]; r.buf = buf; newline(); asm_scancode(); if (name != 0 && name != bindsym_(codesegment)) /* name may be 0 for string literals from static inits */ { newline(); maybe_export(name); if (annotations) fprintf(as, " "); pr_asmname(name); fprintf(as, ":\n\n"); } for (q = 0; q < codep; q += 4) /* q is now a BYTE offset */ { int32 w = code_inst_(q), f = code_flag_(q); VoidStar aux = code_aux_(q); if (needslabel(q / 4)) { printlabelname(buf, "", ":\n", q, name); fputs(buf, as); } if (annotations) fprintf(as, "%.6lx %.8lx ", (long)(q + codebase), (long)w); switch(f) { case LIT_RELADDR: if (lastline == NUMB) newline(); disassemble(w, q, (Symstr *)aux, &r); lastline = INSTRUC; break; case LIT_OPCODE: if (lastline == NUMB) newline(); disassemble(w, q, NULL, &r); lastline = INSTRUC; break; case LIT_STRING: if (lastline == INSTRUC) newline(); fprintf(as, " .ascii "); NoteLiteralLabel(q); if (host_lsbytefirst != target_lsbytefirst) /* already sex_reversed, so reverse back */ w = totargetsex(w, LIT_BBBB); pr_chars(w, 4); lastline = NUMB; break; case LIT_NUMBER: if (lastline == INSTRUC) newline(); NoteLiteralLabel(q); fprintf(as, " .word %#.8lx", (long)w); lastline = NUMB; break; case LIT_ADCON: if (lastline == INSTRUC) newline(); NoteLiteralLabel(q); sym = find_extsym(codebase+q); fprintf(as, " .word "); pr_asmname(sym); if (w != 0) fprintf(as, "+%#lx", (long)w); lastline = NUMB; break; case LIT_FPNUM: if (lastline == INSTRUC) newline(); NoteLiteralLabel(q); { char *s = (char *)aux; if (*s != '<') { fprintf(as, " .float %s", s); } else { fprintf(as, " .word %#.8lx", w); } } lastline = NUMB; break; case LIT_FPNUM1: if (lastline == INSTRUC) newline(); NoteLiteralLabel(q); { char *s = (char *)aux; if (*s != '<') { fprintf(as, " .double %s", s); } else { fprintf(as, " .word %#.8lx, %#.8lx", w, code_inst_(q+4) ); } } lastline = NUMB; break; case LIT_FPNUM2: /* all printed by the FPNUM1 */ if (annotations) break; else continue; default: fprintf(as, "\n ????\n"); } newline(); } asm_codesize += codep; } void asm_header(void) { asm_codesize = 0; asm_imported = NULL; litlabels = NULL; disass_sethexprefix("0x"); disass_setregnames(regnames, (char **)fregnames); if (annotations) return; /* do not bore interactive user */ fprintf(asmstream, "@ generated by %s\n\n", CC_BANNER); fprintf(asmstream, " .text"); } typedef struct ExtRefList { struct ExtRefList *cdr; ExtRef *car; } ExtRefList; static void pr_onehalf(FILE *as, unsigned short w) { union { int32 l; unsigned short w[2]; } val; fprintf(as, " .half %#.4x @ ", w); val.w[0] = w; pr_chars(val.l, 2); } static void pr_onebyte(FILE *as, unsigned char b) { union { int32 l; unsigned char b[4]; } val; fprintf(as, " .byte %#.2x @ ", b); val.b[0] = b; pr_chars(val.l, 1); } static void pr_twobytes(FILE *as, unsigned char b, unsigned char c) { union { int32 l; unsigned char b[4]; } val; fprintf(as, " .byte %#.2x, %#.2x @ ", b, c); val.b[0] = b; val.b[1] = c; pr_chars(val.l, 2); } static void asm_checklenandrpt(int32 len, int lenwanted, int32 rpt, int32 val) { bool norpt = NO; if (lenwanted < 0) norpt = YES, lenwanted = -lenwanted; if (len != lenwanted) syserr(syserr_asm_data, (long)len); if (rpt != 1 && (val != 0 || norpt)) syserr(syserr_asm_trailer1, (long)rpt, (long)val); } static void asm_data(DataInit *p) { FILE *as = asmstream; int32 adr; for (; p != 0; p = p->datacdr) { int32 rpt = p->rpt, sort = p->sort, len = p->len; union { unsigned32 l; unsigned16 w[2]; unsigned8 b[4]; FloatCon *f; } val; val.l = p->val; switch (sort) { case LIT_LABEL: newline(); /* All LIT_LABEL's get more properly registered with the preceding */ /* obj_symref() -- e.g. in vargen.c. */ { ExtRef *x = symext_((Symstr *)rpt); if (x == 0) syserr(syserr_duff_lab); adr = x->extoffset; } maybe_export((Symstr *)rpt); if (adr & 3) { fprintf(as, "L%.3lx:\n", adr & ~3L); pr_asmname((Symstr *)rpt); fprintf(as, " .equ L%.3lx + %ld\n", adr & ~3L, adr & 3L); } else { pr_asmname((Symstr *)rpt); fprintf(as, ":\n"); } break; default: syserr(syserr_asm_trailer, (long)sort); case LIT_BBBB: asm_checklenandrpt(len, -4, rpt, val.l); fprintf(as, " .byte %#.2x, %#.2x, %#.2x, %#.2x @ ", val.b[0], val.b[1], val.b[2], val.b[3]); pr_chars(val.l, 4); break; case LIT_BBBX: asm_checklenandrpt(len, -3, rpt, val.l); fprintf(as, " .byte %#.2x, %#.2x, %#.2x @ ", val.b[0], val.b[1], val.b[2]); pr_chars(val.l, 3); break; case LIT_BBX: asm_checklenandrpt(len, -2, rpt, val.l); pr_twobytes(as, val.b[0], val.b[1]); break; case LIT_BXXX: asm_checklenandrpt(len, -1, rpt, val.l); pr_onebyte(as, val.b[0]); break; case LIT_HH: asm_checklenandrpt(len, -4, rpt, val.l); fprintf(as, " .half %#.4x, %#.4x @ ", val.w[0], val.w[1]); pr_chars(val.l, 4); break; case LIT_HX: asm_checklenandrpt(len, -2, rpt, val.l); pr_onehalf(as, val.w[0]); break; case LIT_BBH: asm_checklenandrpt(len, -4, rpt, val.l); pr_twobytes(as, val.b[0], val.b[1]); newline(); pr_onehalf(as, val.w[1]); break; case LIT_HBX: asm_checklenandrpt(len, -3, rpt, val.l); pr_onehalf(as, val.w[0]); newline(); pr_onebyte(as, val.b[2]); break; case LIT_HBB: asm_checklenandrpt(len, -4, rpt, val.l); pr_onehalf(as, val.w[0]); newline(); pr_twobytes(as, val.b[2], val.b[3]); break; case LIT_NUMBER: asm_checklenandrpt(len, 4, rpt, val.l); if (len != 4) syserr(syserr_asm_data, (long)len); if (rpt == 1) { fprintf(as, " .word %#.8lx @ ", (long)val.l); pr_chars(val.l, 4); } else /* val.l already checked to be zero */ fprintf(as, " .space %ld", (long)(rpt*len)); break; case LIT_FPNUM: { char *s = val.f->floatstr; if (*s != '<') { fprintf(as, " .%s %s", (len == 8) ? "double" : "float ", s); } else if (len == 4) { fprintf(as, " .word %#.8lx", val.f->floatbin.fb.val); } else { fprintf(as, " .word %#.8lx, %#.8lx", val.f->floatbin.db.msd, val.f->floatbin.db.lsd); } break; } case LIT_ADCON: /* (possibly external) name + offset */ while (rpt--) { fprintf(as, " .word "); pr_asmname((Symstr *)len); fprintf(as, "+%ld", (long)val.l); } break; } newline(); } } void asm_trailer(void) { #ifndef TARGET_IS_HELIOS FILE *as = asmstream; #ifdef CONST_DATA_IN_CODE asm_data(constdata_head()); #endif fprintf(as, "\n .data\n"); pr_common_defs(); asm_data(data_head()); if (bss_size != 0) { int32 n = 0; ExtRef *x = obj_symlist; ExtRefList *zisyms = NULL; fprintf(as, "\n .bss\n"); for (; x != NULL; x = x->extcdr) if (x->extflags & xr_bss) { ExtRefList **prev = &zisyms; ExtRefList *p; for (; (p = *prev) != 0; prev = &cdr_(p)) if (x->extoffset < car_(p)->extoffset) break; *prev = (ExtRefList *)syn_cons2(*prev, x); } for (; zisyms != NULL; zisyms = cdr_(zisyms)) { x = car_(zisyms); if (x->extoffset != n) fprintf(as, " .space %ld\n", x->extoffset-n); n = x->extoffset; maybe_export(x->extsym); pr_asmname(x->extsym); fprintf(as, ":\n"); } if (n != bss_size) fprintf(as, " .space %ld\n", bss_size-n); } newline(); #endif /* TARGET_IS_HELIOS */ } #endif /* NO_ASSEMBLER_OUTPUT */ /* To avoid messy conditional compilation in arm/gen.c */ DataDesc adconpool; Symstr *adconpool_lab; int adconpool_find(int32 w, int32 flavour, Symstr *sym) { IGNORE(w); IGNORE(flavour); IGNORE(sym); syserr("adconpool_find"); return 0; } void adconpool_flush(void) {} void adconpool_init(void) {} /* end of arm/uasm.c */