repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
---|---|---|
stardot/ncc | cppthumb/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 CPLUSPLUS 1
#define THUMB_CPLUSPLUS 1
#define TARGET_VTAB_ELTSIZE 4
#define NON_RELEASE_VSN TOOLVER_TCPP
#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. */
# 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 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
#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
#ifdef HOST_CANNOT_INVOKE_LINKER
#define DRIVER_ENV { \
0, 0, 0, \
"", "", "", ":", "", "", "lst", \
"tasm", \
"armlink", NULL, "", \
"", "", "", \
"armlib.o", "hostlib.o", "armlib.o", "", "", "" \
}
#else
#define DRIVER_ENV { \
0, (KEY_LINK), 0, \
"", "", "", ":", "", "", "lst", \
"tasm", \
"armlink", NULL, "", \
"", "", "", \
"armlib.o", "hostlib.o", "armlib.o", "", "", "" \
}
#endif
#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 */
#ifndef TARGET_IS_NEWTON
# define PROFILE_COUNTS_INLINE 1
/* to avoid conflict with host compilers */
# define C_INC_VAR "ARMINC"
# define C_LIB_VAR "ARMLIB"
#else
# define PROFILE_DISABLES_TAILCALL 1
# define C_INC_VAR "ARMCIncludes"
# define C_LIB_VAR NULL
#endif
#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
#ifdef CPLUSPLUS
# ifndef CFRONT_MODE_WARN_LACKS_STORAGE_TYPE
# define CFRONT_MODE_WARN_LACKS_STORAGE_TYPE 1
# endif
#endif
#define MSG_TOOL_NAME "armcpp" /* 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 | cpparm/options.h | /*
* 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 TARGET_HAS_DWARF 1
#define TARGET_VTAB_ELTSIZE 4
/* for indirect VTABLEs optimised for single inheritance */
/* 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_HAS_INLINE_ASSEMBLER 1
#define ARM_INLINE_ASSEMBLER 1
#define PROFILE_COUNTS_INLINE 1
#ifndef __acorn
# ifdef TARGET_IS_NEWTON
# define TARGET_MACHINE "Newton"
# define TARGET_SYSTEM "Newton OS"
# define TARGET_IS_NEWTONOS 1
# define TARGET_DEFAULT_BIGENDIAN 1
# define STRUCT_PTR_ALIGN_DEFAULT 0 /* do not assume struct ptrs are 4-byte aligned */
# define NO_INSTORE_FILES 1 /* no in-store headers for Newton. */
# define PCS_DEFAULTS (PCS_CALLCHANGESPSR | PCS_FPE3 | PCS_NOSTACKCHECK)
/* Exploiting registers preserved by callee saves only 200 bytes in the */
/* Newton ROM and makes patching more difficult */
# define DRIVER_OPTIONS {"-zpu1", NULL} /* pc-rel vtables */
# define DO_NOT_EXPLOIT_REGISTERS_PRESERVED_BY_CALLEE 1
# define CFRONT_COMPATIBLE_DESTRUCTORS 1
# 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 char[] */
# 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 13 /* as MPW C '\n' */
# define CHAR_CR 10 /* as MPW C '\r' */
# define CFRONT_MODE_WARN_LACKS_STORAGE_TYPE 0
# define D_SUPPRESSED (D_SHORTWARN | D_STRUCTPADDING | D_PPNOSYSINCLUDECHECK | \
D_IMPLICITCTOR | D_LOWERINWIDER | D_CFRONTCALLER | \
D_MULTICHAR | D_STRUCTASSIGN)
# define HOST_DOESNT_WANT_FP_OFFSET_TABLES 1
# ifndef COMPILING_ON_MACINTOSH /* ifdef HOST_FILENAMES_ARE_CASE_SENSISTIVE */
# define RETRY_INCLUDE_LOWERCASE
# endif
# ifdef MAKE_WCHAR_T_UNSIGNED_SHORT
/* make wchar_t be unsigned short */
/* maybe this should be cfe somewhere */
# define sizeof_wchar sizeof_short
# define wchar_typespec (bitoftype_(unsigned)|bitoftype_(short)) /* for sem.c */
# define NUM_WCHAR (NUM_INT|NUM_SHORT|NUM_UNSIGN) /* for lex.c */
# endif
# else /* NOT TARGET_IS_NEWTON */
/* usual cross-development case... */
# define TARGET_SYSTEM ""
# define TARGET_IS_RISC_OS 1
# define TARGET_DEFAULT_BIGENDIAN 0
# define PCS_DEFAULTS (PCS_CALLCHANGESPSR | PCS_FPE3 | PCS_SOFTFP)
/* | PCS_NOSTACKCHECK */
/* | PCS_REENTRANT */
/* | PCS_FPREGARGS */
# endif
# define HOST_WANTS_NO_BANNER 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. */
# ifndef DRIVER_OPTIONS
/* -D__arm done by TARGET_PREDEFINES */
# define DRIVER_OPTIONS {NULL}
# endif
#else /* __acorn is defined */
# ifdef __unix
# define TARGET_SYSTEM "RISCiX"
# define TARGET_IS_UNIX 1
# define NO_INSTORE_FILES 1 /* no in-store headers under Unix. */
# define HOST_WANTS_NO_BANNER 1
/* #define TARGET_HAS_DIVREM_FUNCTION 1 -- divide fn also returns remainder.*/
/* #define TARGET_HAS_DIV_10_FUNCTION 1 -- fast divide by 10 */
/* but not under ARM Unix... */
# ifndef DRIVER_OPTIONS
/* -D__arm done by TARGET_PREDEFINES */
# define DRIVER_OPTIONS {"-zps1", "-D__unix", "-D__acorn", NULL}
# endif
#endif
# ifdef __riscos
# define TARGET_SYSTEM "RISC OS"
# 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. */
# ifndef DRIVER_OPTIONS
/* -D__arm done by TARGET_PREDEFINES */
# define DRIVER_OPTIONS {"-D__riscos", "-D__acorn", NULL}
# endif
# endif
#endif /* defined(__acorn) */
#include "toolver.h"
#define NON_RELEASE_VSN TOOLVER_ARMCPP
#ifndef TARGET_IS_NEWTON
# define PROFILE_COUNTS_INLINE 1
/* to avoid conflict with host compilers */
# define C_INC_VAR "ARMINC"
# define C_LIB_VAR "ARMLIB"
#else
# define PROFILE_DISABLES_TAILCALL 1
# define C_INC_VAR "ARMCIncludes"
# define C_LIB_VAR NULL
#endif
/* #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 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
# ifdef applec
/* work-around for MPW C */
# define NO_STATIC_BANNER 1
# endif
pascal void SpinCursor(short increment); /* copied from CursorCtl.h */
# define ExecuteOnSourceBufferFill() SpinCursor(1)
# ifdef __MWERKS__
# define REBUFFERSTDOUT 1
# endif
#else /* NOT macintosh */
# ifdef UNIX_TIME_LIMIT
# define TIME_LIMIT UNIX_TIME_LIMIT
# endif
#endif
#ifdef TARGET_IS_NEWTON
#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 "armcpp" /* used to load correct NLS message file */
#define TARGET_HAS_ASD
#endif
/* end of cpparm/options.h */
|
stardot/ncc | tests/bitfield.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"
typedef unsigned long uint32;
typedef unsigned short uint16;
typedef unsigned char uint8;
typedef struct {
uint32 queue1;
uint16 queue2;
uint8 grp_evt;
uint8 type : 7;
uint8 ou_et : 1;
} S_2275;
const S_2275 s_2275[2] = {
{0,4321,0,0x7f,1},
{0,0,0,1,1}
};
static void t_2275(void) {
uint16 val160 = 1234;
uint16 val161 = s_2275[0].queue2;
uint8 val80 = s_2275[0].type;
uint8 val81 = s_2275[0].ou_et;
EQI(val80, 0x7f);
EQI(val81, 1);
}
typedef struct {
uint32 a;
uint16 b;
uint8 c;
uint32 d:32;
uint32 e:32;
uint32 f:31;
uint32 g:1;
uint8 h:8;
uint8 i:8;
uint8 j:8;
uint8 k:8;
uint8 l:8;
} S_2290;
S_2290 s_2290 = {
0x11223344, 0x5566, 0x77, 0x8899aabb, 0xccddeeff,
0x7f112233, 1, 2, 3, 4, 5, 6
};
void t_2290(void) {
EQI(s_2290.a, 0x11223344);
EQI(s_2290.b, 0x5566);
EQI(s_2290.c, 0x77);
EQI(s_2290.d, 0x8899aabb);
EQI(s_2290.e, 0xccddeeff);
EQI(s_2290.f, 0x7f112233);
EQI(s_2290.g, 1);
EQI(s_2290.h, 2);
EQI(s_2290.i, 3);
EQI(s_2290.j, 4);
EQI(s_2290.k, 5);
EQI(s_2290.l, 6);
s_2290.d = 0xbbaa9988;
s_2290.l = 3;
EQI(s_2290.a, 0x11223344);
EQI(s_2290.b, 0x5566);
EQI(s_2290.c, 0x77);
EQI(s_2290.d, 0xbbaa9988);
EQI(s_2290.e, 0xccddeeff);
EQI(s_2290.f, 0x7f112233);
EQI(s_2290.g, 1);
EQI(s_2290.h, 2);
EQI(s_2290.i, 3);
EQI(s_2290.j, 4);
EQI(s_2290.k, 5);
EQI(s_2290.l, 3);
}
int main(void) {
BeginTest();
t_2275();
t_2290();
EndTest();
return 0;
}
/* End of $RCSfile$ */
|
stardot/ncc | tests/1923.c | /* ARM C library test */
/* Copyright (C) Advanced RISC Machines, 1997. All Rights Reserved */
/* SPDX-Licence-Identifier: Apache-2.0 */
/* THIS TEST HAS BEEN SUPERCEDED BY 2581.c */
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
#include <stdlib.h>
#include <limits.h>
#include "testutil.h"
double dd(double x)
{
/* return a number bigger than the argument */
return x*2;
}
float df(float x)
{
/* return a number bigger than the argument */
return x*2;
}
int main(void)
{
double d, f;
long l;
unsigned long u;
/* disable the IVO exception */
__fp_status(__fpsr_IOE, 0);
BeginTest();
/* double -> long [overflow] */
d = (double)INT_MAX;
l = (long)d; /* does not overflow */
EQI(l, INT_MAX); /* should return INT_MAX */
d = dd(d);
l = (long)d; /* overflows */
EQI(l, INT_MAX); /* should return INT_MAX */
d = dd(d);
l = (long)d; /* overflows */
EQI(l, INT_MAX); /* should return INT_MAX */
/* double -> unsigned long [-ve] */
d = (double)-1;
u = (unsigned long)d; /* should fail - invalid */
EQI(u, 0);
/* double -> unsigned long [overflow] */
d = (double)UINT_MAX;
u = (unsigned long)d; /* should not overflow */
EQI(u, UINT_MAX);
d = dd(d);
u = (unsigned long)d; /* overflows */
EQI(u, UINT_MAX);
d = dd(d);
u = (unsigned long)d; /* overflows */
EQI(u, UINT_MAX);
/* float -> long [overflow] */
f = (float)INT_MAX;
l = (long)f; /* overflows */
EQI(l, INT_MAX); /* should return INT_MAX */
f = df(f);
l = (long)f; /* overflows */
EQI(l, INT_MAX); /* should return INT_MAX */
f = df(f);
l = (long)f; /* overflows */
EQI(l, INT_MAX); /* should return INT_MAX */
/* float -> unsigned long [-ve] */
f = (float)-1;
u = (unsigned long)f; /* should fail - invalid */
EQI(u, 0);
/* float -> unsigned long [overflow] */
f = (float)UINT_MAX;
u = (unsigned long)f; /* should not overflow */
EQI(u, UINT_MAX); /* /* Value is unlikely to be UINT_MAX: floats */
/* don't have sufficient precision */
f = df(f);
u = (unsigned long)f; /* overflows */
EQI(u, UINT_MAX);
f = df(f);
u = (unsigned long)f; /* overflows */
EQI(u, UINT_MAX);
EndTest();
return 0;
}
|
stardot/ncc | tests/2382.c | <filename>tests/2382.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"
#ifdef __cplusplus
typedef unsigned int size_t;
class SingleObject {};
typedef unsigned char Boolean;
typedef char Char;
typedef signed char SChar;
typedef unsigned char UChar;
typedef signed char Byte;
typedef signed char SByte;
typedef unsigned char UByte;
typedef short Short;
typedef signed short SShort;
typedef unsigned short UShort;
typedef long Long;
typedef signed long SLong;
typedef unsigned long ULong;
typedef signed long FastInt;
typedef long Ref;
class RefVar {
public:
RefHandle* h;
inline RefVar();
inline ~RefVar();
inline RefVar(const Ref r);
inline RefVar(const RefVar& o);
operator long() const { return h->ref; }
inline long Length() const;
};
struct ObjectTable {
ObjHeader header;
RefHandle handles[1];
};
class TObjectHeap {
protected:
Ptr fMemory;
Ptr fStart;
Ptr fLimit;
ObjectTable* fObjectTable;
long fFreeOTEntry;
void Uriah(void);
};
class POutTranslator
{
public:
int Print(const char *fmt, ...);
};
extern POutTranslator* gREPout;
void TObjectHeap::Uriah()
{
long totalSize = 0;
long freeSize = 0;
long lockedSize = 0;
long largestFree = 0;
ULong internalFrag = 0;
long totalMapSize = 0;
long virtualMapSize = 0;
long totalSymbolSize = 0;
long nCodeBlocks = 0;
long totalCodeSize = 0;
long totalLitSize = 0;
long virtualLitSize = 0;
long totalScriptSize = 0;
long totalBinarySize = 0;
long totalBinarys = 0;
long totalArraySize = 0;
long totalArrays = 0;
long totalFrameSize = 0;
long totalFrames = 0;
long totalContextSize = 0;
Ptr start = fStart;
Ptr limit = fLimit;
for (Ptr obj = start; obj < limit; obj += ObjPhysicalSize(obj)) {
long physSize = ObjPhysicalSize(obj);
totalSize += physSize;
if ( ( kObjFree) ) {
freeSize += physSize;
if (physSize > largestFree) largestFree = physSize;
}
else {
internalFrag += physSize - ((long) ((*(unsigned long *) obj ) >> 8)) ;
lockedSize += physSize;
Ref oref = ((Ref) (((long) obj ) + kTagPointer)) ;
Ref c = NILREF;
totalSymbolSize += physSize;
{
Ref instrs = GetFrameSlot(oref, (RSSYMinstructions) );
Ref lits = GetFrameSlot(oref, (RSSYMliterals) );
nCodeBlocks++;
totalCodeSize += ObjPhysicalSize(ObjectPtr(instrs));
virtualLitSize += 4 * Length(lits);
totalScriptSize += physSize;
}
totalLitSize += physSize;
}
}
gREPout->Print ("total %d, free %d, largest %d, locked %d, int frag %d,
ext frag %d\n",
totalSize, freeSize, largestFree, lockedSize,
(internalFrag * 1000) / totalSize,
((freeSize - largestFree) * 1000) / totalSize);
gREPout->Print ("%d scripts: %d bytecode, p:%d/v:%d literals, grand
total %d\n",
nCodeBlocks, totalScriptSize, totalLitSize, virtualLitSize,
totalCodeSize+totalScriptSize+totalLitSize);
gREPout->Print ("frames %d(%d)maps p:%d/v:%d\n", totalFrameSize,
totalFrames, totalMapSize, virtualMapSize);
gREPout->Print ("symbols %d, binaries %d(%d)\n", totalSymbolSize,
totalBinarySize, totalBinarys);
gREPout->Print ("*** total size should be %X\n", fLimit - fStart);
long nextFreeIndex = fFreeOTEntry;
while (nextFreeIndex != -1)
{
nextFreeIndex = RINT(fObjectTable->handles[nextFreeIndex].ref);
}
}
#endif
/* no runnable test */
int main(void)
{
BeginTest();
EQI(0, 0);
EndTest();
return 0;
}
|
stardot/ncc | mip/dump.h | /*
* dump.h: compiler state save and restore
* Copyright (C) 1996 Advanced RISC Machines Limited. All rights reserved.
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$ Codemist 0
* Checkin $Date$
* Revising $Author$
*/
#define DS_Version 1
#define DS_Dump 1
#define DS_Load 2
extern unsigned dump_state;
typedef struct {
uint32 ngensym, nsym,
nglobbind,
nglobtag,
nbindlist;
} Dump_LoadState;
extern Dump_LoadState dump_loadstate;
typedef enum {
Dump_Dump,
Dump_Load
} Dump_Sort;
#ifndef NO_DUMP_STATE
uint32 Dump_BinderRef(Binder *);
uint32 Dump_TagRef(TagBinder *);
uint32 Dump_TagOrBinderRef(Binder *);
uint32 Dump_SymRef(Symstr *);
uint32 Dump_NoteSharedBindList(BindList *);
Binder *Dump_LoadedBinder(uint32);
TagBinder *Dump_LoadedTag(uint32);
Binder *Dump_LoadedTagOrBinder(uint32);
Symstr *Dump_LoadedSym(uint32);
BindList *Dump_LoadedSharedBindList(uint32);
void Dump_Sym(Symstr *, FILE *);
Symstr *Dump_LoadSym(size_t, FILE *);
void Dump_BindList(BindList *, FILE *);
BindList *Dump_LoadBindList(FILE *);
/* (For unshared bindlists) */
void Dump_Friends(Friend *, FILE *);
Friend *Dump_LoadFriends(FILE *);
void Dump_StrSeg(StringSegList *, FILE *);
StringSegList *Dump_LoadStrSeg(FILE *);
void Dump_Expr(Expr *e, FILE *f);
Expr *Dump_LoadExpr(FILE *f);
void Dump_Type(TypeExpr *, FILE *);
TypeExpr *Dump_LoadType(FILE *);
void Dump_LoadString(char *, size_t, FILE *);
void Dump_SharedBindLists(FILE *);
void Dump_Init(Dump_Sort, FILE *);
void Inline_LoadState(FILE *);
void Inline_DumpState(FILE *);
void Bind_LoadState(FILE *);
void Bind_DumpState(FILE *);
void PP_LoadState(FILE *);
void PP_DumpState(FILE *);
void Builtin_LoadState(FILE *f);
void Builtin_DumpState(FILE *f);
void Vargen_LoadState(FILE *f);
void Vargen_DumpState(FILE *f);
#else
#define Dump_BinderRef(a) ((uint32)0)
#define Dump_TagReg(a) ((uint32)0)
#define Dump_SymRef(a) ((uint32)0)
#define Dump_SharedBindListRef(a) ((uint32)0)
#define Dump_LoadedBinder(a) ((Binder *)0)
#define Dump_LoadedTag(a) ((TagBinder *)0)
#define Dump_LoadedSym(a) ((Symstr *)0)
#define Dump_LoadedSharedBindList(a) ((BindList *)0)
#define Dump_Sym(a,b) ((void)0)
#define Dump_LoadSym(a,b) ((Symstr *)0)
#define Dump_BindList(a,b) ((void)0)
#define Dump_LoadBindList(a) ((BindList *)0)
#define Dump_StrSeg(a,b) ((void)0)
#define Dump_LoadStrSeg(a) ((StringSegList *)0)
#define Dump_Expr(e,f) ((void)0)
#define Dump_LoadExpr(f) ((Expr *)0)
#define Dump_Type(a,b) ((void)0)
#define Dump_LoadType(a) ((TypeExpr *)0)
#define Dump_LoadString(a,b,c) ((void)0)
#define Dump_SharedBindLists(a) ((void)0)
#define Dump_NoteSharedBindList(a) ((void)0)
#define Dump_Init(a,b) ((void)0)
#define Inline_LoadState(a) ((void)0)
#define Inline_DumpState(a) ((void)0)
#define Bind_LoadState(a) ((void)0)
#define Bind_DumpState(a) ((void)0)
#define PP_LoadState(a) ((void)0)
#define PP_DumpState(a) ((void)0)
#define Builtin_LoadState(f) ((void)0)
#define Builtin_DumpState(f) ((void)0)
#endif /* NO_DUMP_STATE */
|
stardot/ncc | thumb/target.h | <filename>thumb/target.h
/*
* C compiler file thumb/target.h, version 1
* Copyright (C) Codemist Ltd., 1988-94.
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
#ifndef _target_LOADED
#define _target_LOADED 1
#define TARGET_IS_THUMB 1
#include "toolenv.h"
#ifndef TARGET_MACHINE
# define TARGET_MACHINE "Thumb"
#endif
#define TARGET_PREDEFINES { "__arm", \
"__thumb", \
"__CLK_TCK=100", \
"__JMP_BUF_SIZE=22" }
#define EXTENSION_SYSV 1
#define localcg_newliteralpool_exists 1
#define SOFTWARE_FLOATING_POINT 1
#define software_floating_point_enabled 1
#define software_floats_enabled 1
#define software_doubles_enabled 1
#define SOFTWARE_FLOATING_POINT_RETURNS_DOUBLES_IN_REGISTERS 1
#define TARGET_SOFTFP_SUPPORT_INCLUDES_REVERSE_OPS 1
#define TARGET_FP_ARGS_IN_FP_REGS 1
#define TARGET_HAS_IEEE 1
#define TARGET_ENDIANNESS_CONFIGURABLE 1
#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 1
#define NON_ALIGNED_DATA
#define TARGET_HAS_NATURALLY_ALIGNED_STATICS 1
#define TARGET_HAS_FP_OFFSET_TABLES 1
#define TARGET_HAS_DEBUGGER 1
#define TARGET_DEBUGGER_WANTS_MACROS 1
#define TARGET_HAS_NEGATIVE_INDEXING 1
/* #define TARGET_HAS_SCALED_ADDRESSING */
extern int target_scalable(int32 m, int32 n);
/* #define TARGET_HAS_SWITCH_BRANCHTABLE 1 */
#define TARGET_HAS_TAILCALL 1
/*#define TARGET_HAS_TAILCALLR 1*/
#define TARGET_HAS_RECURSIVE_TAILCALL_ONLY 1
#define TARGET_HAS_MULTIPLY 1
#define TARGET_HAS_ROTATE 1
#define TARGET_HAS_BLOCKMOVE 1
#define THUMB_MOVC 1
/* #define TARGET_ALLOWS_COMPARE_CSES 1 */
#define TARGET_HAS_2ADDRESS_CODE 1
#define two_address_code(op) (((op) & J_TABLE_BITS) == J_SHLR || \
((op) & J_TABLE_BITS) == J_SHRR || \
((op) & J_TABLE_BITS) == J_RORR)
#define TARGET_HAS_HALFWORD_INSTRUCTIONS 1
#define TARGET_HAS_SPECIAL_VARARGS 1
#define TARGET_GEN_NEEDS_VOLATILE_INFO 1
#define DO_NOT_EXPLOIT_REGISTERS_PRESERVED_BY_CALLEE 1
/* #define TARGET_INLINES_MONADS 1 */
#define TARGET_LACKS_RR_UNALIGNED_ACCESSES 1
#define TARGET_LACKS_UNSIGNED_FIX 1
#define TARGET_ADDRESSES_UNSIGNED 1
#define TARGET_LDRK_MIN 0
#define TARGET_LDRK_MAX 127L
#define TARGET_LDRWK_MIN 0
#define TARGET_LDRWK_MAX 63L
#define TARGET_LDRBK_MIN 0
#define TARGET_LDRBK_MAX 31L
#define TARGET_SP_LDRK_MIN 0
#define TARGET_SP_LDRK_MAX 1023L
/* Thumb lacks LDRB/LDRH [sp,...] instructions, but MAX values still = 1023
* as we will use ADD ip, sp, #N to address the object.
*/
#define TARGET_SP_LDRWK_MIN 0
#define TARGET_SP_LDRWK_MAX 1023L
#define TARGET_SP_LDRBK_MIN 0
#define TARGET_SP_LDRBK_MAX 1023L
#define TARGET_MAX_FRAMESIZE (5*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 4L
#define MAXGLOBINTREG 8L
#define TARGET_HAS_BSS 1
#define CONST_DATA_IN_CODE 1
#define NINTREGS 16L /* same as smallest fp reg, usually R_F0 */
/* ECN - Lie about no. of FLT regs to prevent pointless register spillage when
* cg thinks its has no FP register available. See cg_expr1
*/
#define NFLTARGREGS 8L
#define NFLTVARREGS 8L
#define R_FV1 (R_F0+NFLTARGREGS)
#define MAXGLOBFLTREG 0L
#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.
*/
/*
* IP is uses as scratch workspace in many places, and is not made available
* to the general register allocator. It must neverthless be preserved
* across procedure calls for ARM inter-working to be possible. Ugh.
*/
#define ARM_R_IP 12L
#define R_IP 0x3L
/*
* FR is used in the creation of stack frames. It may be the same as
* IP but it may not be one of the arg registers, hence the separation.
*/
#define R_FR 0x7L
#define ALLOCATION_ORDER {0,1,2,3,7,4,5,6,255}
#define R_SP 13L /* stack pointer */
#define R_LR 14L /* link addr in fn calls or work reg */
#define R_PSR 15L
#define TARGET_SPECIAL_ARG_REG R_V1
/* 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 *, char const *);
# define target_lib_name_(x,e) target_lib_name(x,e)
#endif
#define 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
#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
#define TARGET_PREFIX(fname) "__16" ## fname
#ifdef TARGET_HAS_DEBUGGER
# ifndef TARGET_HAS_DWARF
# define TARGET_HAS_ASD
# 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 "tcpp"
#else
# define TOOLFILENAME "tcc"
#endif
#endif
/* end of thumb/target.h */
|
stardot/ncc | tests/inlnthumb.c | /*
* Thumb 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"
#ifdef __thumb
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
SUB r0, r2, r1 /* no RSB in Thumb */
ADD r1, r0, r2
ADD r2, r0, r1 /* ADC / SBC UNSAFE */
SUB r0, r1, r2
SUB r1, r2, r0 /* no RSC in Thumb */
TST r0, r1
/* no TEQ in Thumb */
CMP r0, r1
CMN r0, r1
ORR r2, r0, r1
MOV r0, r1
BIC r1, r0, r2
MVN r0, r2
/* until here */
ROR r1, r2
ADD a, r0, r1
}
return a;
}
int t2(int a, int b, int c)
{ int d;
/* Data processing */
__asm
{ /* each binary op comes in 4 forms */
ADD a, #1
ADD a, b
ADD b, a, #1
ADD c, a, c
SUB a, #1
SUB a, b
SUB b, a, #1
SUB c, a, c
ADC a, b
ADC a, #1
ADC b, a, #1
ADC c, a, c
SBC a, b
SBC a, #1
SBC b, a, #1
SBC c, a, c
AND a, #1
AND a, b
AND b, a, #1
AND c, a, c
BIC a, #1
BIC a, b
BIC b, a, #1
BIC c, a, c
ORR a, #1
ORR a, b
ORR b, a, #1
ORR c, a, c
EOR a, #1
EOR a, b
EOR b, a, #1
EOR c, a, c
ASR a, #1
ASR a, b
ASR b, a, #1
ASR c, a, c
LSR a, #1
LSR a, b
LSR b, a, #1
LSR c, a, c
LSL a, #1
LSL a, b
LSL b, a, #1
LSL c, a, c
ASL a, #3 /* ASL is synonym for LSL */
ROR a, #1
ROR a, b
ROR b, a, #1
ROR c, a, c
MUL a, #5
MUL a, b
MUL b, a, #5
MUL c, a, c
/* each unary op comes in 2 forms */
MOV a, b
MOV d, #1
ADC c, d
MVN a, a
MVN d, #1
ADC c, d
NEG a, a
NEG d, #1
ADC c, d
/* compares come in 2 forms */
CMP a, b
ADC a, b
CMP a, #1
TST a, b
TST a, #1
CMN a, b
CMN a, #1
NOP /* translates to MOV r8, r8 - doesn't set condition codes */
}
return a + b + c + d;
}
void t3(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]
LDRB a, [b, #8]
ADD a, a, #1
STRB a, [b, #9]
LDSB a, [b]
STRH a, [b, #12]
LDSH a, [b]
STR a, [b, #16]
LDRH a, [b]
STR a, [b, #20]
LDMIA b!, {r0 - r2} /* r0-r5 BROKEN-regalloc */
ADD b, #4*3
STMIA b!, {r0 - r2}
}
}
void t4(char *a, char *b, int n)
{ /* labels & branches */
int ch;
char *end;
__asm
{
ADD end, a, n
loop:
LDRB ch, [a]
ADD a, #1
STRB ch, [b]
CMP a, end
BEQ ret
ADD b, #1
CMP ch, #0
BNE loop
ret:
}
}
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), 0xAC004453);
EQI(t1(0xFFEEDDCC, 0xBBAA9988, 0x77665544), 0x8841EEBB);
t3(0, arr, arr);
#ifndef __BIG_ENDIAN
EQI(arr[0], 0x81818182);
EQI(arr[1], 0x22334456);
EQI(arr[2], 0xffff00ff);
EQI(arr[3], 0x0000ff82);
EQI(arr[4], 0xffff8182);
EQI(arr[5], 0x00008182);
EQI(arr[6], arr[0]);
EQI(arr[7], arr[1]);
EQI(arr[8], arr[2]);
#endif
t4(str1, str2, 16);
EQI(0, strcmp(str2, "Inline assembler "));
}
/******************* 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
LSR t, n, #24
LDRB res, [tab, t]
LSL n, #8
LSR t, n, #24
LDRB t, [tab, t]
LSL t, #8
ORR res, t
LSL n, #8
LSR t, n, #24
LDRB t, [tab, t]
LSL t, #16
ORR res, t
LSL n, #8
LSR t, n, #24
LDRB t, [tab, t]
LSL t, #24
ORR res, t
}
return res;
}
uint bitrev_2(uint n)
{
uint c0, c1, c2, t, sh;
__asm
{
MOV c2, #0x0F0F0F0F
LSL sh, c2, #2
EOR c1, c2, sh // 0x33333333
LSL sh, c1, #1
EOR c0, c1, sh // 0x55555555
AND t, c0, n
LSR sh, n, #1
AND n, c0, sh
LSL sh, t, #1
ORR n, n, sh
AND t, c1, n
LSR sh, n, #2
AND n, c1, sh
LSL sh, t, #2
ORR n, n, sh
AND t, c2, n
LSR sh, n, #4
AND n, c2, sh
LSL sh, t, #4
ORR n, n, sh
LSR sh, n, #8
MOV t, sh // DCBA
BIC t, t, #255 << 8 // 0D0B
ROR sh, n, #8
EOR n, t, sh // A0C0
ROR sh, t, #16
ORR n, n, sh // 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);
}
}
/******************* fail *************************/
/**************************************************/
int main ()
{
BeginTest();
test();
bitreverse_test();
EndTest();
return 0;
}
#else
int main ()
{
BeginTest();
EndTest();
return 0;
}
#endif
|
stardot/ncc | interp/target.h | <filename>interp/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
#define TARGET_IS_ARM 1
#define TARGET_IS_INTERPRETER 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" }
#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
#ifndef NO_OBJECT_OUTPUT
#define TARGET_HAS_DATA_VTABLES 1
#define target_has_data_vtables mcdep_data_vtables()
#endif
#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_scalable(n,m) 1
/* 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 !(target_has_halfword_support)
#define target_lacks_rr_halfword_store !(target_has_halfword_support)
#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
/* help please on the 0-1 controversy */
#define R_A1 0L
#define R_F0 16L
#define R_V1 4L
#define NARGREGS 4L
#ifdef TARGET_IS_HELIOS
# define NVARREGS 5L
# define MAXGLOBINTREG 5L
# define R_DP 9L /* Helios needs a static base register */
#else
# define NVARREGS 8L /* Includes R_SL & R_FP (only sometimes varregs) */
# define MAXGLOBINTREG 6L
#ifndef NO_OBJECT_OUTPUT
# define TARGET_HAS_BSS 1
#endif
# ifndef TARGET_HAS_AOUT
# define CONST_DATA_IN_CODE 1
# endif
#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 R_IP 0xcL /* temp + used in call (nb not necessarily a real register number) */
#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_LR 0xeL /* link addr in fn calls or work reg */
#define TARGET_SPECIAL_ARG_REG R_IP
/* emphasise non-obvious defaults in mip/defaults.h */
#ifndef alignof_double
# define alignof_double 4
#endif
#ifndef alignof_struct
# define alignof_struct 4
#endif
#ifndef COMPILING_ON_ARM
extern const char *target_lib_name(const char *, int32);
# define target_lib_name_(x,e) target_lib_name(x,e)
#endif
extern char *target_asm_options(int32);
#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 TARGET_IS_NULL
#define SOFTWARE_FLOATING_POINT 1
#define SOFTWARE_FLOATING_POINT_RETURNS_DOUBLES_IN_REGISTERS 1
#define software_floating_point_enabled (config & CONFIG_SOFTWARE_FP)
#define TARGET_SOFTFP_SUPPORT_INCLUDES_REVERSE_OPS 1
#endif
#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
#endif
#endif
/* end of arm/target.h */
|
stardot/ncc | clbcomp/clbcomp.h | /*
* C compiler file ccomp/ccomp.h
* Copyright (C) Advanced Risc Machines Ltd., 1996
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
#ifndef _ccomp_LOADED
#define _ccomp_LOADED 1
extern char *expr_string;
extern void clb_init(void);
extern Expr *clb_parse_expr(char *s);
#endif
|
stardot/ncc | mip/csescan.c | /*
* mip/csescan.c: CSE available expression analysis
* 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 125
* 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 "aeops.h"
#include "jopcode.h"
#include "store.h"
#include "cgdefs.h"
#include "builtin.h" /* for sim */
#include "mcdep.h" /* immed_cmp */
#include "flowgraf.h" /* is_exit_label */
#include "regalloc.h" /* vregister */
#include "errors.h"
#include "cg.h"
#include "codebuf.h"
#include "cseguts.h"
#include "ieeeflt2.h"
#define HASHSIZE 1024
#define hash(op,a,b) \
( ((op) + ((((IPtr)(a))/4) * 7)) & (HASHSIZE-1) )
#define LOCHASHSIZE 512
#define lochash(type,base,k,id) \
( ((type) + ((type) == LOC_VAR ? (IPtr)(id) : (k))) & (LOCHASHSIZE-1) )
Exprn **exprnindex[EXPRNINDEXSIZE];
#define LOCSEGSIZE 512
#define LOCINDEXSIZE 64
#define LOCSEGBITS 9
static Location **locindex[LOCINDEXSIZE];
#define loc_(id) (locindex[(id)>>LOCSEGBITS])[(id)&(LOCSEGSIZE-1)]
#define addtoreglist(r, l) l = (RegList *) syn_cons2(l, r)
static Location **locations; /* list of Locations used */
static Exprn **cse_tab; /* hash table of Exprns */
static Exprn *heapptr;
#define CSEIDSEGSIZE 128 /* This must be a multiple of the VRegSet chunk
size (or its intended space-saving fails)
*/
int32 cse_debugcount;
static int32 cseidsegment;
static int32 csealiasid, csealiaslimit;
static int32 csenonaliasid, csenonaliaslimit;
static VRegSetP availableexprns,
liveexprns,
wantedexprns,
killedlocations;
static VRegSetP loadrs;
#define CALLLOC (-1) /* a fake locid to say 'has calls' */
#define isrealloc(p) ((p) > CALLLOC)
#ifdef TARGET_ALLOWS_COMPARE_CSES
# define CCLOC (-2) /* fake locid meaning 'alters condition codes */
static VRegSetP compares;
#endif
#ifndef CSE_COMPARE_MASK
# define CSE_COMPARE_MASK Q_MASK /* just one op for all compares */
#endif
#define MOVCLOC (-2)
#define J_NEK J_INIT /* really, we should have a different jopcode for this */
#define J_HEAPPTR J_NOOP /* and for this */
#define IsLive(x) (vregset_member(exid_(x), liveexprns))
#define LocKills(x, p) (vregset_member(x, (p)->aliasusers))
static int32 locationid;
typedef struct FloatConList FloatConList;
struct FloatConList {
FloatConList *cdr;
FloatCon *f;
};
#define mkFloatConList(a,b) (FloatConList *)syn_cons2(a,b)
static FloatConList *floatconlist;
typedef struct Int64ConList Int64ConList;
struct Int64ConList {
Int64ConList *cdr;
Int64Con *i;
};
#define mkInt64ConList(a,b) (Int64ConList *)syn_cons2(a,b)
static Int64ConList *int64conlist;
struct LocList {
LocList *cdr;
Location *loc;
};
#define ll_loc_(p) ((p)->loc)
static LocList *LocList_New(LocList *next, Location *loc) {
return (LocList *)CSEList2(next, loc);
}
static LocList *LocList_DiscardOne(LocList *locs) {
return (LocList *)discard2((VoidStar)locs);
}
typedef struct RegValue {
struct RegValue *cdr;
/* VRegnum */ IPtr reg;
ExSet *value;
} RegValue;
#define rv_reg_(r) ((r)->reg)
#define rv_val_(r) ((r)->value)
static RegValue *knownregs;
static RegValue *RegValue_DiscardOne(RegValue *rv) {
return (RegValue *)discard3((VoidStar)rv);
}
static RegValue *RegValue_New(RegValue *next, VRegnum reg, ExSet *val) {
return (RegValue *)CSEList3(next, reg, val);
}
static RegValue const *RegValue_RegMember(VRegnum r, RegValue const *list) {
for (; list != NULL; list = cdr_(list))
if (r == list->reg)
return list;
return NULL;
}
typedef struct LocSet LocSet;
struct LocSet {
LocSet *cdr;
Location *loc;
ExSet *oldval;
};
#define ls_loc_(p) ((p)->loc)
#define ls_oldval_(p) ((p)->oldval)
#define LocSet_Member(x, s) generic_member((IPtr)x, (List const *)s)
static LocSet *LocSet_New(LocSet *next, Location *loc) {
return (LocSet *)CSEList3(next, loc, NULL);
}
static LocSet *LocSet_DiscardOne(LocSet *locs) {
return (LocSet *)discard3((VoidStar)locs);
}
static LocSet *LocSet_Copy(LocSet const *locs) {
LocSet *res = NULL, **resp = &res;
for (; locs != NULL; locs = cdr_(locs)) {
LocSet *p = LocSet_New(NULL, ls_loc_(locs));
*resp = p; resp = &cdr_(p);
}
return res;
}
static void LocSet_Discard(LocSet *locs) {
for (; locs != NULL; locs = LocSet_DiscardOne(locs))
continue;
}
static bool LocSet_Subset(LocSet const *sub, LocSet const *super) {
for (; sub != NULL; sub = cdr_(sub))
if (!LocSet_Member(ls_loc_(sub), super))
return NO;
return YES;
}
typedef struct StoreAccessList {
struct StoreAccessList *cdr;
LocSet *locs;
bool needed;
Icode *ic;
} StoreAccessList;
#define sa_locs_(p) ((p)->locs)
#define sa_needed_(p) ((p)->needed)
#define sa_ic_(p) ((p)->ic)
static StoreAccessList *storeaccesses;
static StoreAccessList *StoreAccessList_New(
StoreAccessList *next, LocSet *locs, bool needed, Icode *ic) {
return (StoreAccessList *)CSEList4(next, locs, needed, ic);
}
static StoreAccessList *StoreAccessList_DiscardOne(StoreAccessList const *sa) {
return cdr_(sa);
}
static StoreAccessList *StoreAccessList_Copy(StoreAccessList const *sa) {
StoreAccessList *res = NULL, **resp = &res;
for (; sa != NULL; sa = cdr_(sa)) {
StoreAccessList *p = StoreAccessList_New(NULL, LocSet_Copy(sa_locs_(sa)), sa_needed_(sa), sa_ic_(sa));
*resp = p; resp = &cdr_(p);
}
return res;
}
static void StoreAccessList_Discard(StoreAccessList *sa) {
for (; sa != NULL; sa = StoreAccessList_DiscardOne(sa))
LocSet_Discard(sa_locs_(sa));
}
#ifdef ENABLE_CSE
/*
* Debugging stuff.
*/
void cse_print_loc(Location const *x)
{
switch (loctype_(x)) {
default:
cc_msg("<odd-loc %ld>", (long)loctype_(x)); break;
case LOC_VAR:
cc_msg("'%s'", symname_(bindsym_(locbind_(x))));
break;
case LOC_PVAR:
cc_msg("'%s'P", symname_(bindsym_(locbind_(x))));
break;
case LOC_(MEM_B):
case LOC_(MEM_W):
case LOC_(MEM_I):
case LOC_(MEM_LL):
case LOC_(MEM_F):
case LOC_(MEM_D):
cc_msg("[(%ld), #%ld]", (long)exid_(locbase_(x)), (long)locoff_(x));
break;
}
}
void cse_print_node(Exprn const *p)
{
J_OPCODE op;
if (p == NULL) { cc_msg("null\n"); return; }
op = exop_(p);
cc_msg("node %ld: ", (long)exid_(p));
if (op == J_NEK) {
/* Re-using J_INIT for this turns out not to be such a great idea ... */
cc_msg("NEK%13s%ld\n", "", (long)e1k_(p));
return;
} else if (op == J_HEAPPTR) {
cc_msg("HEAPPTR\n");
return;
}
jopprint_opname(op);
switch (extype_(p)) {
case E_UNARYK:
{ VRegInt r2, r3;
r2.r = GAP; r3.b = e1b_(p);
jopprint_op3(op, r2, r3);
}
break;
case E_UNARY:
cc_msg("(%ld)", (long)exid_(e1_(p)));
break;
case E_BINARYK:
cc_msg("(%ld), #%ld", (long)exid_(e1_(p)), (long)e2k_(p));
break;
case E_BINARY:
cc_msg("(%ld), (%ld)", (long)exid_(e1_(p)), (long)exid_(e2_(p)));
break;
case E_TERNARY:
cc_msg("(%ld) %s ? (%ld) : (%ld)",
(long)exid_(e1_(p)), condition_name(exmask_(p)),
(long)exid_(e2_(p)), (long)exid_(e3_(p)));
break;
case E_LOAD:
cse_print_loc(exloc_(p));
break;
case E_LOADR:
cc_msg(" r%ld", (long)e1_(p));
break;
case E_MISC:
cc_msg("**");
break;
case E_CALL:
{ int32 i;
cc_msg("%s(", symname_(bindsym_(exfn_(p))));
for (i = 0 ; i < exnargs_(p) ; i++) {
if (i != 0) cc_msg(", ");
cc_msg("(%ld)", (long)exid_(exarg_(p, i)));
}
cc_msg(")");
if (exnres_(p) > 1) cc_msg("=>%ld", exnres_(p));
}
break;
}
cc_msg("\n");
}
void cse_printexits(int32 flags, LabelNumber *exit, LabelNumber *exit1)
{
Icode ic;
if (flags & BLKSWITCH)
return;
INIT_IC(ic, J_NOOP);
if (flags & BLK2EXIT) {
ic.op = J_B + (flags & Q_MASK);
ic.r3.l = exit1;
print_jopcode(&ic);
}
if (!(flags & BLK0EXIT)) {
ic.op = J_B;
ic.r3.l = exit;
print_jopcode(&ic);
}
}
static void ExSet_Print(ExSet const *set, char const *s) {
char c = '{';
for (; set != NULL; set = cdr_(set)) {
cc_msg("%c%ld", c, (long)exid_(exs_ex_(set)));
c = ' ';
}
if (c != '{') cc_msg("}%s", s);
}
static void StoreAccessList_Print(StoreAccessList const *p, char const *s) {
char *s1 = "store accesses: ";
for (; p != NULL; p = cdr_(p)) {
LocSet *locs = sa_locs_(p);
char *s2 = " <";
cc_msg("%s%s", s1, loads_r1(sa_ic_(p)->op) ? "LD": "ST");
for (; locs != NULL; locs = cdr_(locs)) {
cc_msg(s2); cse_print_loc(ls_loc_(locs));
cc_msg(" {%ld}", exid_(ls_loc_(locs)->load));
s2 = ", ";
}
cc_msg(">");
s1 = ", ";
}
cc_msg("%s", s);
}
static void RegValue_Print(RegValue const *p, char const *s) {
for (; p != NULL; p = cdr_(p)) {
cc_msg("r%ld = ", rv_reg_(p));
ExSet_Print(p->value, cdr_(p) == NULL ? s : " ");
}
}
#else
void cse_print_loc(Location const *x)
{
IGNORE(x);
}
void cse_print_node(Exprn const *p)
{
IGNORE(p);
}
void cse_printexits(int32 flags, LabelNumber *exit, LabelNumber *exit1)
{
IGNORE(flags); IGNORE(exit); IGNORE(exit1);
}
static void ExSet_Print(ExSet const *set, char const *s) {
IGNORE(set);
}
static void StoreAccessList_Print(StoreAccessList const *p, char const *s) {
IGNORE(p); IGNORE(s);
}
static void RegValue_Print(RegValue const *p, char const *s) {
IGNORE(p); IGNORE(s);
}
#endif /* ENABLE_CSE */
#define J_SIGNbits (J_SIGNED|J_UNSIGNED)
#define CantBeSubExprn(x) ((x) == NULL || (x) == heapptr || exop_(x) == J_NEK)
#define ExprnToSet(e) ExSet_Insert(e, NULL)
#define ExSet_Copy(e) ExSet_Append(e, NULL)
#define ExSet_DiscardOne(e) ((ExSet *)discard2(e))
bool ExSet_Member(Exprn const *e, ExSet const *set) {
ExSet const *p = set;
for (; p != NULL; p = cdr_(p))
if (exs_ex_(p) == e) return YES;
return NO;
}
static ExSet *ExSet_Insert(Exprn *e, ExSet *set) {
return (ExSet_Member(e, set)) ? set : (ExSet *) CSEList2(set, e);
}
static ExSet *ExSet_NDelete(Exprn *e, ExSet *set) {
ExSet *p, **prev = &set;
for (; (p = *prev) != NULL; prev = &cdr_(p))
if (exs_ex_(p) == e) {
*prev = ExSet_DiscardOne(p);
break;
}
return set;
}
static ExSet *ExSet_Union(ExSet *e1, ExSet const *e2) {
for (; e2 != NULL; e2 = cdr_(e2))
e1 = ExSet_Insert(exs_ex_(e2), e1);
return e1;
}
static void ExSet_Discard(ExSet *set) {
for (; set != NULL; )
set = ExSet_DiscardOne(set);
}
static ExSet *LiveExSet(ExSet *set) {
/* Destructively modify <set>, removing from it those Exprns which */
/* aren't live. */
ExSet *p, **prev = &set;
while ((p = *prev) != NULL)
if (!IsLive(exs_ex_(p)))
*prev = ExSet_DiscardOne(p);
else
prev = &cdr_(p);
return set;
}
static ExSet *ExSet_Intersection(ExSet *s, ExSet const *s1) {
ExSet *p, **prev = &s;
while ((p = *prev) != NULL)
if (ExSet_Member(exs_ex_(p), s1))
prev = &cdr_(p);
else
*prev = ExSet_DiscardOne(p);
return s;
}
static bool AlreadyNarrowed(Exprn const *e, J_OPCODE op);
static ExSet *NarrowedSet(ExSet *set, J_OPCODE op) {
ExSet *p, *res = NULL;
for (p = set; p != NULL; p = cdr_(p))
if (AlreadyNarrowed(exs_ex_(p), op))
res = ExSet_Insert(exs_ex_(p), res);
return res;
}
typedef bool ExSetMapFn(Exprn *, void *);
static bool ExSet_Map(ExSet const *p, ExSetMapFn *f, void *a) {
for (; p != NULL; p = cdr_(p))
if (!f(exs_ex_(p), a)) return NO;
return YES;
}
static Exprn *ExSet_Some(ExSet const *p, ExSetMapFn *f, void *a) {
for (; p != NULL; p = cdr_(p))
if (f(exs_ex_(p), a)) return exs_ex_(p);
return NULL;
}
static ExSet *ExSet_Append(ExSet const *a, ExSet *b) {
ExSet *res = b;
for (; a != NULL; a = cdr_(a))
res = ExSet_Insert(exs_ex_(a), res);
return res;
}
bool ExSetsOverlap(ExSet const *a, ExSet const *b) {
ExSet const *p;
for (p = a; p != NULL; p = cdr_(p))
if (!CantBeSubExprn(exs_ex_(p)) && ExSet_Member(exs_ex_(p), b))
return YES;
return NO;
}
ExSet *ExSet_OpMember(ExSet *set, J_OPCODE op, int32 ignorebits) {
for (; set != 0; set = cdr_(set))
if ((exop_(exs_ex_(set)) & ~ignorebits) == op)
return set;
return NULL;
}
typedef bool OpInSet_Aux(Exprn const *);
static ExSet *OpInSetFn(ExSet *set, OpInSet_Aux *p) {
for (; set != 0; set = cdr_(set))
if (p(exs_ex_(set)))
return set;
return NULL;
}
#ifdef TARGET_HAS_ROTATE
static ExSet *OpInSetWithE1(ExSet *set, J_OPCODE op, int32 ignorebits, Exprn *e1) {
for (; set != 0; set = cdr_(set))
if ((exop_(exs_ex_(set)) & ~ignorebits) == op &&
e1_(exs_ex_(set)) == e1)
return set;
return NULL;
}
#endif
static ExSet *ExprnInSet(ExSet *set, Exprn *e) {
for (; set != 0; set = cdr_(set))
if (exs_ex_(set) == e) return set;
return NULL;
}
void ExSet_TransferExprnsInSet(VRegSetP *s1, VRegSetP *s2, ExSet const *set) {
bool ins1;
for (; set != 0; set = cdr_(set)) {
int32 exid = exid_(exs_ex_(set));
cseset_delete(exid, *s1, &ins1);
if (ins1) cseset_insert(exid, *s2, &ins1);
}
}
static int32 cse_optype(int32 op)
{
/* The order of these tests is significant, as remarked below .. */
if (op == CSE_LOADR) return E_LOADR;
if ((op & ~Q_MASK) == CSE_COND) return E_TERNARY;
if (isproccall_(op)) return E_CALL;
if (j_is_adcon(op)) return E_UNARYK;
if (j_is_ldr_or_str(op)) return E_LOAD;
if (j_is_diadr(op)) return E_BINARY;
if (j_is_diadk(op)) return E_BINARYK;
if (reads_r3(op)) return E_UNARY; /* must be after j_is_diadr(op) */
if (loads_r1(op)) return E_UNARYK; /* must be at end */
/* WD: TODO - broken for loads_r2, etc */
/* But only if such things are made CSEs, which they currently aren't */
return E_MISC;
}
static int32 locsize(LocType type)
{
switch (type) {
case LOC_(MEM_B): return 1;
case LOC_(MEM_W): return 2;
case LOC_(MEM_I): return 4;
case LOC_(MEM_LL): return 8;
/* we should really get these values from sizeof_short &c? */
case LOC_(MEM_F): return 4;
case LOC_(MEM_D): return 8;
/* /* the next line is dubious -- what about LOC_VAR/LOC_PVAR? */
/* <NAME> and AM just (13/4/92) agreed to put MEM_xxx parts in */
/* LOC_VAR and LOC_PVAR fields. Soon to be done! */
default: return 4;
}
}
static LocType loctype(J_OPCODE op)
{ int32 mem = j_memsize(op);
switch (mem) {
case MEM_D:
case MEM_F:
case MEM_I:
case MEM_B:
case MEM_W:
case MEM_LL: return LOC_(mem);
default: syserr(syserr_loctype); return LOC_(MEM_I);
}
}
static bool overlap(LocType typea, int32 a,
LocType typeb, int32 b)
{
return ((a >= b && a < (b+locsize(typeb))) ||
(b >= a && b < (a+locsize(typea))));
}
Exprn *cse_AdconBase(Exprn *ex, bool allowvaroffsets)
{ if (ex == NULL) syserr(syserr_adconbase);
if (ex == heapptr) return ex;
switch (exop_(ex) & J_TABLE_BITS)
{
case J_ADCON: case J_ADCONV: case J_ADCONF: case J_ADCOND: case J_ADCONLL:
return ex;
case J_LDRK: /* J_LDRLK on TARGET_IS_ALPHA? */
{ Location *loc = exloc_(ex);
return (loctype_(loc) == LOC_VAR &&
(bindstg_(locbind_(loc)) & b_noalias)) ? ex : NULL;
}
case J_ADDR:
if (!allowvaroffsets) break;
{
Exprn *r = cse_AdconBase(e1_(ex), YES);
if (r != NULL) return r;
if (!OpIsShifted(exop_(ex)))
return cse_AdconBase(e2_(ex), YES);
}
break;
case J_SUBR:
if (!allowvaroffsets) break;
/* drop through */
case J_SUBK:
case J_ADDK:
return cse_AdconBase(e1_(ex), allowvaroffsets);
}
return NULL;
}
static Exprn *AdconBaseK(Exprn *ex, int32 *p)
{ if (ex == NULL) syserr(syserr_adconbase);
if (ex == heapptr) return ex;
switch (exop_(ex) & J_TABLE_BITS)
{
case J_ADCON: case J_ADCONV: case J_ADCONF: case J_ADCOND: case J_ADCONLL:
return ex;
case J_SUBK:
*p -= e2k_(ex);
return AdconBaseK(e1_(ex), p);
case J_ADDK:
*p += e2k_(ex);
return AdconBaseK(e1_(ex), p);
}
return NULL;
}
typedef enum {
NotAlias, /* Definitely unrelated */
MaybeAlias, /* Possible aliases (address-taken var vs pointer dereference)
or definitely overlapping but not identical.
*/
IsSynonym /* The same location accessed identically (LDRV x vs LDRVK 0,x)
*/
} AliasType;
static AliasType possiblealias(Location const *loc, Location const *loc1)
{
/* Determine whether loc may be an alias of loc1. Both loc and */
/* loc1 may have any type. */
/* NB required to return NO if loc is the same as loc1 */
/* Simple variables are an oddity here: x may be aliased by */
/* something like ((ADCONV x) . n), but by nothing else (or else */
/* it would be marked as address-taken, and be a LOC_PVAR instead)*/
LocType t = loctype_(loc);
LocType t1 = loctype_(loc1);
if ((t & LOC_REG) || (t1 & LOC_REG))
{ if ((t|t1) & LOC_REALBASE) syserr("possiblealias(REG+REALBASE)");
return NotAlias;
}
if ((t & LOC_anyVAR) && (t1 & LOC_anyVAR)) {
if (locbind_(loc) != locbind_(loc1)) return NotAlias;
if (locvartype_(loc) != locvartype_(loc1)) return MaybeAlias;
/* Same variable, different access */
return NotAlias;
}
if (t1 & LOC_anyVAR) {
LocType x = t; Location const *xl = loc;
t = t1, loc = loc1;
t1 = x, loc1 = xl;
}
if (t & LOC_anyVAR) {
/* hence by above t1 = LOC_(MEM_xx)+maybe(REALBASE) */
int32 k = locoff_(loc1);
Exprn *base1 = locbase_(loc1);
Exprn *b1 = AdconBaseK(base1, &k);
Binder *v = locbind_(loc);
if (b1 != NULL) {
t = locvartype_(loc);
if (exop_(b1) == J_ADCONV && e1b_(b1) == v)
return k == 0 && t == t1 ? IsSynonym :
k < locsize(t) ? MaybeAlias :
NotAlias;
return NotAlias;
}
b1 = cse_AdconBase(base1, YES);
return b1 == NULL ? ((t == LOC_PVAR) ? MaybeAlias : NotAlias) :
(exop_(b1) == J_ADCONV && e1b_(b1) == v) ? MaybeAlias :
NotAlias;
}
/* By above both t and t1 are LOC_(MEM_xx)+maybe(REALBASE) */
{ Exprn *b = locbase_(loc), *b1 = locbase_(loc1);
int32 off = locoff_(loc), off1 = locoff_(loc1);
if (b != b1) {
Exprn *ba = cse_AdconBase(b, YES),
*b1a = cse_AdconBase(b1, YES);
if (ba == NULL || b1a == NULL)
return MaybeAlias;
else if (ba == b1a)
return MaybeAlias;
else if (exop_(ba) == J_ADCON && exop_(b1a) == J_ADCON &&
(bindstg_(e1b_(b1a)) & bitofstg_(s_static)) &&
(bindstg_(e1b_(ba)) & bitofstg_(s_static))) {
if (AdconBaseK(b, &off) == ba && AdconBaseK(b1, &off1) == b1a) {
return overlap(t1, off1 + bindaddr_(e1b_(b1a)), t, off + bindaddr_(e1b_(ba))) ?
MaybeAlias : NotAlias;
}
}
return NotAlias;
}
return (t == t1 && off == off1) ? NotAlias :
overlap(t1, off1, t, off) ? MaybeAlias :
NotAlias;
}
}
static void updateusers_cb(int32 n, void *arg) {
int32 id = *(int32 *)arg;
Location *loc = loc_(n);
int32 i;
for (i = 0 ; i < LOCINDEXSIZE ; i++) {
Location **index = locindex[i];
int32 j;
if (index == 0) break;
for (j = 0 ; j < LOCSEGSIZE ; j++) {
Location *q = index[j];
if (q == 0) break;
if (possiblealias(q, loc))
cseset_insert(id, q->aliasusers, NULL);
}
}
cseset_insert(id, loc->users, NULL);
cseset_insert(id, loc->aliasusers, NULL);
}
static void updateusers(int32 id, Exprn *p)
{ /*
* Update the 'users' field for all locations which are leaves of the
* expression p to include the expression node id.
* On the assumption that expressions are small, no attempt is made to be
* clever about getting at the leaves.
*/
if (p != NULL) cseset_map(exleaves_(p), updateusers_cb, &id);
}
static void maybealias_cb(int32 n, void *arg) {
if (ispublic(loc_(n))) *(bool *)arg = YES;
}
static bool maybealias(Exprn *p)
{ /*
* Returns true if p or some part of it may have aliases.
* (Used to give things which do and don't distinct sets of ids,
* to reduce the space usage of killed sets).
*/
bool res = NO;
if (p != NULL) cseset_map(exleaves_(p), maybealias_cb, &res);
return res;
}
FloatCon *CSE_CanonicalFPConst(FloatCon *old)
{
FloatConList *p;
for ( p = floatconlist ; p != NULL ; p = cdr_(p) )
if (p->f->floatlen == old->floatlen &&
p->f->floatbin.irep[0] == old->floatbin.irep[0] &&
((p->f->floatlen & bitoftype_(s_short)) ||
p->f->floatbin.irep[1] == old->floatbin.irep[1]))
return p->f;
floatconlist = mkFloatConList(floatconlist, old);
return old;
}
Int64Con *CSE_CanonicalLLConst(Int64Con *old)
{
Int64ConList *p;
for ( p = int64conlist ; p != NULL ; p = cdr_(p) )
if (p->i->bin.i.hi == old->bin.i.hi
&& p->i->bin.i.lo == old->bin.i.lo)
return p->i;
int64conlist = mkInt64ConList(int64conlist, old);
return old;
}
typedef struct {
int32 expid;
bool killed;
} ULWRec;
static void ulw_cb(int32 id, void *arg)
{
ULWRec *ulw = (ULWRec *) arg;
if (isrealloc(id) && !ulw->killed) {
ulw->killed = LocKills(ulw->expid, loc_(id));
}
}
bool cse_KilledInBlock(int32 expid)
{
/* (For use only from within cse_scanblock).
Determine whether the Exprn with id expid could reach the current
icode position from the block head (whether it has been killed yet
in the block).
*/
ULWRec ulw; ulw.expid = expid; ulw.killed = NO;
cseset_map(killedlocations, ulw_cb, (VoidStar) &ulw);
return ulw.killed;
}
#define OldLive 1
#define OldAvail 2
static int updateliveandwanted(Exprn *exp, int flags)
{
/* Update the set of live expressions to include expid (the return value
* indicates whether it was already in the set).
* If the expression has not been killed, add it also to the set of wanted
* expressions
*/
int oldlive;
bool old;
int32 expid = exid_(exp);
cseset_insert(expid, liveexprns, &old);
oldlive = old ? OldLive : 0;
if (!(flags & U_NOTDEF2)) {
cseset_insert(expid, availableexprns, &old);
if (old) oldlive |= OldAvail;
if (!(flags & U_NOTREF)) {
if (cseset_member(CALLLOC, killedlocations)) {
int32 i;
for (i = 0 ; i < LOCINDEXSIZE ; i++) {
Location **index = locindex[i];
int32 j;
if (index == 0) break;
for (j = 0 ; j < LOCSEGSIZE ; j++) {
Location *loc = index[j];
if (loc == 0) break;
if (ispublic(loc) && LocKills(expid, loc))
return oldlive;
}
}
}
#ifdef TARGET_ALLOWS_COMPARE_CSES
if (cseset_member(CCLOC, killedlocations) &&
is_compare(exop_(exp)))
return oldlive;
#endif
if (!cse_KilledInBlock(expid))
cseset_insert(expid, wantedexprns, NULL);
}
}
return oldlive;
}
BlockHead *cse_currentblock;
static Icode *currenticode;
ExprnUse *ExprnUse_New(ExprnUse *old, int flags, int valno)
{
return (ExprnUse *)CSEList3(old, cse_currentblock,
vfi_(valno, flags, currenticode - blkcode_(cse_currentblock)));
}
static bool HasSameArgList(
int is_commutative, int32 n, Exprn * const a[], Exprn * const b[])
{
int32 i;
if (is_commutative
&& ( (n == 2
&& a[0] != NULL && a[0] == b[1]
&& a[1] != NULL && a[1] == b[0])
|| (n == 4
&& a[0] != NULL && a[0] == b[2]
&& a[1] != NULL && a[1] == b[3]
&& a[2] != NULL && a[2] == b[0]
&& a[3] != NULL && a[3] == b[1])))
return YES;
for (i = 0 ; i < n ; i++)
if (a[i] == NULL || a[i] != b[i]) return NO;
return YES;
}
static bool SubExprn(Exprn const *sub, Exprn const *p)
{ if (p == NULL) return NO;
if (p == sub) return YES;
switch (extype_(p)) {
case E_BINARY:
if (SubExprn(sub, e2_(p))) return YES;
case E_BINARYK:
case E_UNARY:
return SubExprn(sub, e1_(p));
case E_LOAD:
{ Location *loc = exloc_(p);
if (loctype_(loc) & LOC_anyVAR) return NO;
return SubExprn(sub, locbase_(loc));
}
case E_CALL:
{ int32 i;
for (i = 0 ; i < exnargs_(p) ; i++)
if (SubExprn(sub, exarg_(p, i))) return YES;
}
}
return NO;
}
static void useoldexprn(Exprn *p, int flags) {
/* if the expression is already live in this block, then local cse
* will kill this occurrence, so I don't want to remember its position.
*/
if (!(flags & U_NOTDEF)) {
int oldlive = updateliveandwanted(p, flags);
if (!(oldlive & OldLive) || (flags & U_STORE)) {
/* If it has become alive, having previously been alive, there may
* still be some locations whose value I think it is. (Up to now,
* I would have known they weren't because it wasn't alive). Their
* values must be killed here.
*/
LocList *q = exlocs_(p);
for (; q != NULL; q = LocList_DiscardOne(q)) {
Location *loc = ll_loc_(q);
locvalue_(loc) = ExSet_NDelete(p, locvalue_(loc));
}
exlocs_(p) = NULL;
{ RegValue *r, **prevp = &knownregs;
for (; (r = *prevp) != NULL ; ) {
rv_val_(r) = ExSet_NDelete(p, rv_val_(r));
if (rv_val_(r) == NULL)
*prevp = RegValue_DiscardOne(r);
else
prevp = &cdr_(r);
}
}
if (!(oldlive & OldLive)) {
StoreAccessList **sap = &storeaccesses;
StoreAccessList *sa;
while ((sa = *sap) != NULL) {
LocSet **locsp = &sa->locs;
LocSet *locs;
while ((locs = *locsp) != NULL)
if (SubExprn(p, locs->loc->load))
*locsp = LocSet_DiscardOne(locs);
else
locsp = &cdr_(locs);
if (sa->locs == NULL)
*sap = StoreAccessList_DiscardOne(sa);
else
sap = &cdr_(sa);
}
}
}
if (!(oldlive & OldAvail) || (flags & U_STORE)) {
if (!(flags & U_NOTDEF2))
exuses_(p) = ExprnUse_New(exuses_(p), flags & ~U_STORE, 0);
exwaslive_(p) = NO;
}
}
}
#define find_varloc(id, load, flags) find_loc(LOC_VAR, NULL, 0, id, load, flags)
#define find_regloc(reg, load, flags) find_loc(LOC_REG, NULL, reg, NULL, load, flags)
#define find_memloc(type, base, offset, load, flags) find_loc(type, base, offset, NULL, load, flags)
static Location *find_loc(LocType type, Exprn *base, int32 k, Binder *id, J_OPCODE load,
int32 loctypeflags);
static Exprn *find_exprn(J_OPCODE op, Exprn *a, Exprn *b, Exprn *arg[], int flags)
{
Exprn *p, *prev;
Exprn **list;
int32 type;
VRegSetP leaves = NULL;
if (op == J_ADDK || op == J_SUBK) {
if (a == heapptr)
return heapptr;
else if (exop_(a) == J_NEK) {
int32 k = (int32)(IPtr)b;
if (op == J_SUBK) k = -k;
op = J_NEK;
a = (Exprn *)(IPtr)(e1k_(a) + k);
b = NULL;
flags = U_NOTDEF2+U_NOTREF;
}
} else if (op == J_ADDR && a == heapptr)
return heapptr;
list = &cse_tab[hash(op, a, b)];
type = cse_optype(op);
switch (type) {
case E_TERNARY:
if (CantBeSubExprn(arg[0]) || CantBeSubExprn(b) || CantBeSubExprn(a))
return NULL;
for (prev = NULL, p = *list; p != NULL; prev = p, p = cdr_(p)) {
if (exop_(p) == (op & ~Q_MASK)
&& a == e1_(p) && b == e2_(p) && arg[0] == e3_(p)
&& (op & Q_MASK) == exmask_(p)) {
if (prev != NULL) {
cdr_(prev) = cdr_(p); cdr_(p) = *list; *list = p;
}
if (!(flags & U_PEEK)) useoldexprn(p, flags);
return p;
}
}
if (flags & U_PEEK) return NULL; /* just checking */
p = (Exprn *) CSEAlloc(
(int) (offsetof(Exprn, u.ternary.mask) + sizeof(int32)));
e2_(p) = b;
e3_(p) = arg[0];
exmask_(p) = op & Q_MASK;
op &= ~Q_MASK;
leaves = cseset_copy(exleaves_(a));
cseset_union(leaves, exleaves_(b));
cseset_union(leaves, exleaves_(arg[0]));
break;
case E_BINARY:
if (CantBeSubExprn(b) || CantBeSubExprn(a)) return NULL;
for (prev = NULL, p = *list; p != NULL; prev = p, p = cdr_(p)) {
if (exop_(p) == op && a == e1_(p) && b == e2_(p)) { /* eureka! */
if (prev != NULL) {
cdr_(prev) = cdr_(p); cdr_(p) = *list; *list = p;
}
if (!(flags & U_PEEK)) useoldexprn(p, flags);
return p;
}
}
if (j_is_commutative(op)) {
Exprn **list2 = &cse_tab[hash(op, b, a)];
for (prev = NULL, p = *list2; p != NULL; prev = p, p = cdr_(p)) {
if (exop_(p) == op && b == e1_(p) && a == e2_(p)) { /* eureka! */
if (prev != NULL) {
cdr_(prev) = cdr_(p); cdr_(p) = *list2; *list2 = p;
}
if (!(flags & U_PEEK)) useoldexprn(p, flags);
return p;
}
}
}
if (flags & U_PEEK) return NULL; /* just checking */
p = (Exprn *) CSEAlloc(
(int) (offsetof(Exprn, u.binary.e2) + sizeof(Exprn *)));
e2_(p) = b;
leaves = cseset_copy(exleaves_(a));
cseset_union(leaves, exleaves_(b));
break;
case E_BINARYK:
if (CantBeSubExprn(a)) return NULL;
for (prev = NULL, p = *list; p != NULL; prev = p, p = cdr_(p)) {
if (exop_(p) == op && a == e1_(p) && b == e2_(p)) { /* eureka! */
if (prev != NULL) {
cdr_(prev) = cdr_(p); cdr_(p) = *list; *list = p;
}
if (!(flags & U_PEEK)) useoldexprn(p, flags);
return p;
}
}
if (flags & U_PEEK) return NULL; /* just checking */
p = (Exprn *) CSEAlloc(
(int) (offsetof(Exprn, u.binary.e2) + sizeof(Exprn *)));
e2_(p) = b;
leaves = cseset_copy(exleaves_(a));
break;
case E_UNARY:
if (CantBeSubExprn(a)) return NULL;
case E_LOAD:
case E_UNARYK:
case E_LOADR:
for (prev = NULL, p = *list; p != NULL; prev = p, p = cdr_(p)) {
if (exop_(p) == op && a == e1_(p)) {
if (prev != NULL) {
cdr_(prev) = cdr_(p); cdr_(p) = *list; *list = p;
}
if (!(flags & U_PEEK)) useoldexprn(p, flags);
return p;
}
}
if (flags & U_PEEK) return NULL; /* just checking */
switch (type) {
case E_UNARY:
leaves = cseset_copy(exleaves_(a));
break;
case E_LOAD:
{ Location *loc = (Location *)a;
if (!(loctype_(loc) & LOC_anyVAR))
cseset_union(leaves, exleaves_(locbase_(loc)));
cseset_insert(locid_(loc), leaves, NULL);
}
break;
case E_LOADR:
{ VRegnum r = (VRegnum)(IPtr)a;
Location *loc = isany_realreg_(r) ? find_regloc(r, CSE_LOADR, 0): NULL;
if (loc != NULL) {
cseset_insert(locid_(loc), leaves, NULL);
}
p = (Exprn *) CSEAlloc(
(int)(offsetof(Exprn, u.unary.e1) + sizeof(Exprn *) + sizeof(Location *)));
exloadrloc_(p) = loc;
break;
}
}
if (p == NULL)
p = (Exprn *) CSEAlloc(
(int)(offsetof(Exprn, u.unary.e1) + sizeof(Exprn *)));
break;
case E_CALL:
{ int32 i, n = k_argregs_((IPtr)b);
int iscommutative = flags & U_COMMUTATIVEFN;
flags &= ~U_COMMUTATIVEFN;
for (i = 0 ; i < n ; i++)
if (CantBeSubExprn(arg[i])) return NULL;
for (prev = NULL, p = *list; p != NULL; prev = p, p = cdr_(p)) {
if (exop_(p) == op && a == e1_(p) && b == e2_(p) &&
HasSameArgList(iscommutative, n, &exarg_(p, 0), arg)) {
if (prev != NULL) {
cdr_(prev) = cdr_(p); cdr_(p) = *list; *list = p;
}
if (!(flags & U_PEEK)) useoldexprn(p, flags);
return p;
}
}
if (flags & U_PEEK) return NULL; /* just checking */
p = (Exprn *) CSEAlloc(
(int) (offsetof(Exprn, u.call.arg[0]) + n * sizeof(Exprn *)));
for (i = 0 ; i < n ; i++) {
exarg_(p, i) = arg[i];
cseset_union(leaves, exleaves_(arg[i]));
}
e2_(p) = b; /* @@@ this updates call.nargs hence exfntype_()! */
}
break;
default:
p = NULL; /* to keep dataflow happy */
syserr(syserr_find_exprn, (long)type);
}
cdr_(p) = *list;
exop_(p) = op;
p->nodeid = type; /* id 0 (type is needed for maybealias) */
exwaslive_(p) = NO;
exleaves_(p) = leaves;
{ int32 id; int32 alias;
exuses_(p) = (flags & (U_NOTDEF+U_NOTDEF2)) ? NULL : ExprnUse_New(NULL, flags, 0);
e1_(p) = a;
*list = p;
exlocs_(p) = NULL;
if (maybealias(p)) {
if (++csealiasid >= csealiaslimit) {
csealiasid = cseidsegment;
csealiaslimit = (cseidsegment += CSEIDSEGSIZE);
}
id = csealiasid;
alias = EX_ALIAS;
} else {
if (++csenonaliasid >= csenonaliaslimit) {
csenonaliasid = cseidsegment;
csenonaliaslimit = (cseidsegment += CSEIDSEGSIZE);
}
id = csenonaliasid;
alias = 0;
}
p->nodeid = mknodeid_(id, alias|type); /* rewrite with correct id */
updateusers(id, p);
if (!(flags & U_NOTDEF)) updateliveandwanted(p, flags);
if (id >= EXPRNSEGSIZE * EXPRNINDEXSIZE)
syserr("CSE exprn table overflow");
{ Exprn **index = exprnindex[id>>EXPRNSEGBITS];
if (index == NULL) {
index = CSENewN(Exprn *, EXPRNSEGSIZE);
*(cseallocrec.statsbytes) += EXPRNSEGSIZE * sizeof(Exprn **);
exprnindex[id>>EXPRNSEGBITS] = index;
memclr(index, EXPRNSEGSIZE * sizeof(Exprn **));
}
index[id & (EXPRNSEGSIZE-1)] = p;
}
}
if (debugging(DEBUG_CSE)) cse_print_node(p);
return p;
}
static Exprn *find_binaryk(J_OPCODE op, Exprn *e, int32 n, int flags) {
return find_exprn(op, e, (Exprn *)(IPtr)n, NULL, flags);
}
#define find_movk(n, flags) find_unaryk(J_MOVK, n, flags)
static Exprn *find_unaryk(J_OPCODE op, int32 n, int flags) {
return find_exprn(op, (Exprn *)(IPtr)n, NULL, NULL, flags);
}
static Exprn *find_loadr(VRegnum r, int flags) {
return find_exprn(CSE_LOADR, (Exprn *)(IPtr)r, NULL, NULL, flags);
}
static Exprn *find_unaryb(int32 op, Binder *b, int flags) {
return find_exprn(op, (Exprn *)b, NULL, NULL, flags);
}
static Exprn *find_loadexprn(int32 op, Location *loc, int flags) {
return find_exprn(op, (Exprn *)loc, NULL, NULL, flags);
}
/*
* Stuff about reading/writing/corrupting Locations.
*/
static Location *find_loc(LocType type, Exprn *base, int32 k, Binder *id,
J_OPCODE load, int32 loctypeflags)
{
Location *p, *prev;
Location **list = &locations[lochash(type, base, k, id)];
if (base != NULL && exop_(base) == J_NEK)
return NULL;
for (prev = NULL, p = *list; p != NULL; prev = p, p = cdr_(p)) {
LocType ltype = loctype_(p);
if (ltype == LOC_REG) {
if (type != LOC_REG || locreg_(p) != k)
continue;
} else if ((ltype & LOC_anyVAR) && type == LOC_VAR) {
/* ltype is either LOC_VAR or LOC_PVAR (LOC_REG filtered out above) */
/* type can't be LOC_PVAR: that gets invented below */
if (locbind_(p) != id ||
locvartype_(p) != LOC_(j_memsize(load)))
/* The same variable accessed differently is a different (aliased)
location. Maybe can't happen as generated by cg, but I have
intentions to turn LDRVK 0,x into LDRV x.
*/
continue;
} else {
if (ltype != type || locbase_(p) != base || locoff_(p) != k)
continue;
}
if (prev != NULL) {
cdr_(prev) = cdr_(p); cdr_(p) = *list; *list = p;
}
return p;
}
if (loctypeflags & LOC_PEEK)
return NULL;
{ Location **index = locindex[locationid>>LOCSEGBITS];
p = CSENew(Location);
if (locationid >= LOCSEGSIZE * LOCINDEXSIZE)
syserr("CSE location table overflow");
if (index == NULL) {
index = CSENewN(Location *, LOCSEGSIZE);
*(cseallocrec.statsbytes) += LOCSEGSIZE * sizeof(Location **);
locindex[locationid>>LOCSEGBITS] = index;
memclr(index, LOCSEGSIZE * sizeof(Location **));
}
index[locationid & (LOCSEGSIZE-1)] = p;
}
cdr_(p) = *list;
locvalue_(p)= NULL;
p->users = NULL;
p->aliasusers = NULL;
locsynonym_(p) = NULL;
if (type == LOC_VAR) {
SET_BITMAP stg = bindstg_(id);
if (stg & (b_addrof | b_globalregvar |
bitofstg_(s_static) | bitofstg_(s_extern))) {
type = LOC_PVAR;
}
locbind_(p) = id;
locvartype_(p) = LOC_(j_memsize(load));
} else if (type == LOC_REG) {
locreg_(p) = k;
} else {
int32 n;
Exprn *b = AdconBaseK(base, &n);
if (b != NULL) {
J_OPCODE op = exop_(b) & J_TABLE_BITS;
if (op == J_ADCONF || op == J_ADCOND || op == J_ADCONLL)
loctypeflags |= LOC_CONST;
else if (op == J_ADCONV && !(bindstg_(e1b_(b)) & b_addrof))
loctypeflags |= LOC_LOCAL;
}
locbase_(p) = base;
locoff_(p) = k;
}
p->idandtype = mkidandtype_(locationid++, type | loctypeflags);
{ int32 i;
for (i = 0 ; i < LOCINDEXSIZE ; i++) {
Location **index = locindex[i];
int32 j;
if (index == 0) break;
for (j = 0 ; j < LOCSEGSIZE ; j++) {
Location *q = index[j];
AliasType a;
if (q == 0) break;
a = possiblealias(q, p);
if (a != NotAlias) cseset_union(p->aliasusers, q->users);
if (a == IsSynonym) locsynonym_(p) = q, locsynonym_(q) = p;
}
}
}
p->load = (type == LOC_REG) ? NULL :
find_loadexprn(load, p, U_NOTDEF+U_NOTREF);
return (*list = p);
}
static J_OPCODE cse_J_LDRK_w[] = MEM_to_J_LDRxK_table;
static J_OPCODE j_to_ldrk(J_OPCODE a) {
return (cse_J_LDRK_w[j_memsize(a)] & ~J_ALIGNMENT) | (a & J_ALIGNMENT);
}
static bool is_narrow(Location const *loc)
{
int32 type = loctype_(loc);
return (type == LOC_(MEM_B) || type == LOC_(MEM_W));
}
static bool is_flavoured(J_OPCODE op, Location const *loc)
{
return (op & J_SIGNbits) ? is_narrow(loc) : NO;
}
static Exprn *flavoured_load(J_OPCODE op, Location *loc, int flags)
{
return find_loadexprn(j_to_ldrk(op) | (op & J_SIGNbits), loc, flags);
}
static bool SignBitClear(Exprn const *e)
{ /* Can be improved to match AlreadyNarrowed() */
J_OPCODE op = exop_(e);
switch (op & J_TABLE_BITS)
{
case J_LDRBK: case J_LDRBR: case J_LDRBVK: /* j_memsize(op)==MEM_B */
case J_LDRWK: case J_LDRWR: case J_LDRWVK: /* j_memsize(op)==MEM_W */
if (op & J_UNSIGNED) return YES;
break;
case J_MOVK:
if (e1k_(e) >= 0) return YES;
break;
case J_ANDK:
if (e2k_(e) >= 0) return YES;
break;
}
return NO;
}
static bool AlreadyNarrowed(Exprn const *e, J_OPCODE op)
{
/* The intent here is to catch values which have been explicitly narrowed.
But while we're at it, it's no great effort to notice some expressions
whose results are already narrow.
*/
/* op is known to be flavoured, so its size is either MEM_B or MEM_W */
int32 shift = 24, limit = 256;
J_OPCODE eop = exop_(e);
if (j_memsize(op) != MEM_B) shift = 16, limit = 0x10000;
if (op & J_UNSIGNED)
return (eop == J_ANDK && e2k_(e) >= 0 && e2k_(e) < limit) ||
(eop == J_MOVK && e1k_(e) >= 0 && e1k_(e) < limit);
else {
limit = limit >> 1;
return (( eop == J_ANDK && e2k_(e) >= 0 && e2k_(e) < limit) ||
( eop == (J_SHRK | J_SIGNED) && e2k_(e) >= shift &&
(exop_(e1_(e)) & ~J_SIGNbits) == J_SHRK &&
e2k_(e1_(e)) == e2k_(e)) ||
( eop == J_MOVK && e1k_(e) >= -limit && e1k_(e) < limit));
}
}
static ExSet *loc_read(Location *p, int exprnflags, J_OPCODE op)
{
/* op is to tell us about sign/zero-extension if the location is
a narrow one. */
ExSet *e = LiveExSet(locvalue_(p));
if (!IsLive(p->load)) e = NULL;
locvalue_(p) = e; /* Otherwise, if an exprn in locvalue_(p) subsequently
becomes live we are in trouble
*/
if (!(loctype_(p) & LOC_anyVAR) && locbase_(p) == heapptr) return NULL;
e = ExSet_Copy(e);
{ Exprn *load;
if (is_flavoured(op, p)) {
load = flavoured_load(op, p, exprnflags);
} else {
load = p->load;
if ( !IsLive(load) && is_narrow(p) && !(op & J_SIGNbits)) {
/* If we have a plain load of a narrow location, the value
from a previous flavoured load will do. (This works only
locally, of course - a way to do it non-locally would
supersede this code
*/
Exprn *e1 = flavoured_load(op | J_SIGNED, p, U_NOTREF+U_NOTDEF+U_PEEK);
if (e1 != NULL && IsLive(e1)) {
load = e1;
} else {
e1 = flavoured_load(op | J_UNSIGNED, p, U_NOTREF+U_NOTDEF+U_PEEK);
if (e1 != NULL && IsLive(e1))
load = e1;
}
}
useoldexprn(load, exprnflags);
}
if (load != p->load) useoldexprn(p->load, U_NOTREF+U_NOTDEF2);
if (is_flavoured(op, p))
/* we must discard all but a correctly extended values for the flavour
of load wanted.
*/
e = NarrowedSet(e, op);
return ExSet_Insert(load, e);
}
}
static ExSet *locs_read(LocSet *p, int exprnflags, J_OPCODE op) {
ExSet *e = NULL;
for (; p != NULL; p = cdr_(p)) {
Location *loc = p->loc;
ExSet *locval = loc_read(loc, exprnflags, op);
e = e == NULL ? locval : ExSet_Union(e, locval);
if (locsynonym_(loc) != NULL)
e = ExSet_Union(e, loc_read(locsynonym_(loc), exprnflags, op));
}
return e;
}
static bool AddToLocs(Exprn *e, void *loc) {
exlocs_(e) = LocList_New(exlocs_(e), (Location *)loc);
return YES;
}
static void setlocvalue(Location *p, ExSet *val, VRegSetP localiases)
{
if (locbase_(p) == heapptr) return;
locvalue_(p) = ExSet_Copy(val);
ExSet_Map(val, AddToLocs, p);
if (localiases == NULL) {
cseset_difference(availableexprns, p->aliasusers);
cseset_difference(liveexprns, p->aliasusers);
} else {
VRegSetP es = cseset_copy(p->aliasusers);
cseset_difference(availableexprns, es);
cseset_difference(es, localiases);
cseset_difference(liveexprns, es);
cseset_discard(es);
}
cseset_insert(locid_(p), killedlocations, NULL);
/* Now for any locations whose known values depended on p, we don't know
* their values anymore. It's horribly expensive to go through them here,
* though - instead, we check for liveness when we look at the value. In
* addition, we need to ensure that the value doesn't become live again in
* between - so every time an expression becomes live, we destroy the value
* of all locations with that value.
*/
}
static bool SetExWasLive(Exprn *e, void *ignore) {
IGNORE(ignore);
exwaslive_(e) = YES;
if (exop_(e) == J_RESULT2) exwaslive_(e1_(e)) = YES;
return YES;
}
static void setreg(VRegnum reg, ExSet *val, bool newvalue)
{
RegValue **prevp = &knownregs, *r;
if (isany_realreg_(reg)) {
Exprn *ex = find_loadr(reg, U_NOTDEF+U_NOTREF);
Location *loc = exloadrloc_(ex);
cseset_difference(availableexprns, loc->users);
cseset_difference(liveexprns, loc->users);
cseset_insert(locid_(loc), killedlocations, NULL);
}
/* LOADRs are never available */
for (; (r = *prevp) != NULL ; prevp = &cdr_(r)) {
if (rv_reg_(r) == reg) {
if (newvalue && val != rv_val_(r)) {
/* the second condition covers the case of a register being */
/* copied to itself, as a result of optimisation of one of */
/* the few cases where register reuse is permitted */
ExSet_Discard(rv_val_(r));
rv_val_(r) = NULL;
}
if (val == NULL) {
*prevp = RegValue_DiscardOne(r);
return;
}
break;
}
}
if (r == NULL ) {
if (val== NULL) return;
knownregs = RegValue_New(knownregs, reg, NULL);
r = knownregs;
}
rv_val_(r) = ExSet_Append(val, rv_val_(r));
ExSet_Map(val, SetExWasLive, NULL);
}
static ExSet *valueinreg(VRegnum reg)
{ /* Returns the value held in the argument register if it is known,
* otherwise NULL.
*/
RegValue **prevp = &knownregs, *r;
for (; (r = *prevp) != NULL ; prevp = &cdr_(r))
if (rv_reg_(r) == reg) {
ExSet *e = LiveExSet(rv_val_(r));
if (e == NULL)
*prevp = RegValue_DiscardOne(r);
else
rv_val_(r) = e;
return e;
}
return NULL;
}
static ExSet *readreg(VRegnum reg)
{ /* Returns the value held in the argument register if it is known,
* otherwise an Exprn describing the register (used only for base/
* index registers of store accesses).
*/
ExSet *res = valueinreg(reg);
if (res != NULL) return res;
{ Exprn *r = find_loadr(reg, U_NOTDEF+U_NOTREF);
cseset_insert(exid_(r), loadrs, NULL);
cseset_insert(exid_(r), liveexprns, NULL);
res = ExprnToSet(r);
setreg(reg, res, YES);
return res;
}
}
static void setmem(Location *p, ExSet *val, VRegSetP localiases)
{
setlocvalue(p, val, localiases);
}
static void setvar(Location *p, ExSet *val, VRegSetP localiases)
{
int32 i;
setlocvalue(p, val, localiases);
/* Now if p may be an alias for anything, we must discard
the known value of that thing. */
for (i = 0 ; i < LOCINDEXSIZE ; i++) {
Location **index = locindex[i];
int32 j;
if (index == 0) break;
for (j = 0 ; j < LOCSEGSIZE ; j++) {
Location *q = index[j];
if (q == 0) break;
if (possiblealias(p, q) != NotAlias) setlocvalue(q, NULL, localiases);
}
}
}
static void corruptmem(void)
{ int32 i;
for (i = 0 ; i < LOCINDEXSIZE ; i++) {
Location **index = locindex[i];
int32 j;
if (index == 0) break;
for (j = 0 ; j < LOCSEGSIZE ; j++) {
Location *q = index[j];
if (q == 0) break;
if (ispublic(q) && !locconst_(q)) setlocvalue(q, NULL, NULL); /* value of p may be changed */
}
}
/* Also, all future public expressions must be killed. We record this
* as location CALLLOC (real locations start at 0).
*/
cseset_insert(CALLLOC, killedlocations, NULL);
}
static int32 movcbaseid;
typedef struct MOVCTarget MOVCTarget;
struct MOVCTarget {
MOVCTarget *cdr;
Exprn *base;
int32 id;
VRegSetP locswithbase;
};
static MOVCTarget *movctargets;
static int32 BaseId(Exprn *base)
{ MOVCTarget *p = movctargets;
for (; p != NULL; p = cdr_(p))
if (p->base == base) return p->id;
p = CSENew(MOVCTarget);
cdr_(p) = movctargets;
p->base = base; p->id = --movcbaseid; p->locswithbase = NULL;
movctargets = p;
return p->id;
}
static void corruptlocswithbase(Exprn *base, int32 limit)
{ int32 i;
int32 ldop = alignof_struct < 4 ? J_LDRBK|J_ALIGN1 : J_LDRK|J_ALIGN4;
int32 mem = alignof_struct < 4 ? MEM_B : MEM_I;
find_memloc(LOC_(mem), base, 0, ldop, LOC_REALBASE);
for (i = 0 ; i < LOCINDEXSIZE ; i++) {
Location **index = locindex[i];
int32 j;
if (index == 0) break;
for (j = 0 ; j < LOCSEGSIZE ; j++) {
Location *q = index[j];
if (q == 0) break;
if (!(loctype_(q) & LOC_anyVAR) &&
locbase_(q) == base && locoff_(q) < limit)
setlocvalue(q, NULL, NULL);
}
}
cseset_insert(BaseId(base), killedlocations, NULL);
}
/*
* End of stuff about Locations.
*/
static void blocksetup(void)
{
int32 i;
for (i = 0 ; i != HASHSIZE ; i++) {
Exprn *p = cse_tab[i];
for ( ; p != NULL ; p = cdr_(p)) {
exwaslive_(p) = NO;
while (exlocs_(p) != NULL)
exlocs_(p) = LocList_DiscardOne(exlocs_(p));
}
}
availableexprns = NULL;
liveexprns = NULL;
cseset_insert(0, liveexprns, NULL);
wantedexprns = NULL;
killedlocations = NULL;
}
static void cse_corrupt_register(VRegnum r)
{
setreg(r, NULL, YES);
}
static bool ExprIsExprPlusK(ExSet *es1, ExSet *es2, int32 *p1, int32 *p2)
{
int32 n1 = 0, n2 = 0;
Exprn *ex1 = NULL, *ex2 = NULL;
ExSet *e2, *e1 = ExSet_OpMember(es1, J_ADDK, 0);
if (e1 != NULL)
n1 = e2k_(e1->exprn);
else {
e1 = ExSet_OpMember(es1, J_SUBK, 0);
if (e1 != NULL)
n1 = -e2k_(e1->exprn);
}
if (e1 != NULL) ex1 = e1_(e1->exprn);
e2 = ExSet_OpMember(es2, J_ADDK, 0);
if (e2 != NULL)
n2 = e2k_(e2->exprn);
else {
e2 = ExSet_OpMember(es2, J_SUBK, 0);
if (e2 != NULL) n2 = -e2k_(e2->exprn);
}
if (e2 != NULL) ex2 = e1_(e2->exprn);
if (ex2 != NULL) {
if (ex2 == ex1) {
*p1 = n1; *p2 = n2; return YES;
}
if (ExprnInSet(es1, ex2)) {
*p1 = 0; *p2 = n2; return YES;
}
}
if (ex1 != NULL && ExprnInSet(es2, ex1)) {
*p1 = n1; *p2 = 0; return YES;
}
return NO;
}
static void KillArc(BlockHead *block, LabelNumber *lab) {
if (!is_exit_label(lab)) {
BlockHead *b = lab->block;
if (blk_pred_(b) == NULL) return;
cse_RemovePredecessor(lab, block);
if (blk_pred_(b) != NULL || (blkflags_(b) & BLKSWITCH)) return;
if (blkflags_(b) & BLK2EXIT) KillArc(b, blknext1_(b));
KillArc(b, blknext_(b));
}
}
static void RemoveComparison_i(LabelNumber *dest, BlockHead *block) {
LabelNumber *conddest = blknext1_(block);
if (debugging(DEBUG_CSE))
cc_msg("Comparison removed: %sbranch always taken\n",
dest == conddest ? "" : "other ");
{ LabelNumber *other = dest != conddest ? conddest : blknext_(block);
blknext_(block) = dest;
blkflags_(block) &= ~(Q_MASK | BLK2EXIT);
currenticode->op = J_NOOP;
/* To give non-local value propagation a better chance, remove this block
from the predecessors of the block which is the target of the untakeable
branch (recursively, if that block then becomes unreachable).
*/
KillArc(block, other);
}
}
static void RemoveComparison1(bool taken, BlockHead *block) {
RemoveComparison_i(taken ? blknext1_(block) : blknext_(block), block);
}
static LabelNumber *ComparisonDest(int32 a, int32 b, BlockHead const *block) {
bool taken;
unsigned32 ua = just32bits_(a),
ub = just32bits_(b);
if (!(blkflags_(block) & BLK2EXIT)) return NULL;
switch (blkflags_(block) & Q_MASK) {
case Q_UEQ:
case Q_EQ: taken = (a == b); break;
case Q_UNE:
case Q_NE: taken = (a != b); break;
case Q_HS: taken = (ua >= ub); break;
case Q_LO: taken = (ua < ub); break;
case Q_HI: taken = (ua > ub); break;
case Q_LS: taken = (ua <= ub); break;
case Q_GE: taken = (a >= b); break;
case Q_LT: taken = (a < b); break;
case Q_GT: taken = (a > b); break;
case Q_LE: taken = (a <= b); break;
case Q_AL: taken = YES; break;
default: syserr(syserr_removecomparison, (long)blkflags_(block));
taken = NO;
}
return taken ? blknext1_(block) : blknext_(block);
}
static void RemoveComparison(int32 a, int32 b, BlockHead *block) {
LabelNumber *dest = ComparisonDest(a, b, block);
if (dest == NULL) return;
RemoveComparison_i(dest, block);
}
static ExSet *newexprnpart(int32 part, ExSet *set)
{
ExSet *res = NULL;
for (; set != NULL; set = cdr_(set)) {
Exprn *e = set->exprn;
Exprn *e1 = find_exprn(part, e, NULL, NULL, U_NOTREF+U_NOTDEF);
if (IsLive(e)) {
cseset_insert(exid_(e1), liveexprns, NULL);
cseset_insert(exid_(e1), availableexprns, NULL);
}
res = ExSet_Insert(e1, res);
}
return res;
}
static void add_store_access(LocSet *x) {
bool needed = NO;
if (!stores_r1(currenticode->op)) {
StoreAccessList *a, **ap = &storeaccesses;
while ((a = *ap) != NULL)
if (a->ic->op != J_NOOP && !stores_r1(a->ic->op) && LocSet_Subset(a->locs, x)) {
LocSet_Discard(a->locs);
*ap = StoreAccessList_DiscardOne(a);
} else
ap = &cdr_(a);
}
/* Ensure that stores to function arguments on the stack don't get */
/* removed as redundant. */
{ LocSet *p = x;
for (; p != NULL; p = cdr_(p)) {
Location *loc = p->loc;
if (loctype_(loc) < LOC_VAR) {
int32 n;
Exprn *adcon = AdconBaseK(locbase_(loc), &n);
if (adcon != NULL && exop_(adcon) == J_ADCONV) {
needed = (bindstg_(e1b_(adcon)) & b_unbound) != 0;
break;
}
}
}
}
storeaccesses = StoreAccessList_New(storeaccesses, x, needed, currenticode);
if (debugging(DEBUG_CSE) && CSEDebugLevel(4))
StoreAccessList_Print(storeaccesses, "\n");
}
#define LocInSet(a, s) generic_member((IPtr)a, (List const *)s)
static LocType MaxLocType(LocSet *locs, Location **locp) {
Location *loc = locs->loc;
LocType type = loctype_(loc);
while ((locs = cdr_(locs)) != NULL)
if (loctype_(locs->loc) > type) {
loc = locs->loc;
type = loctype_(loc);
}
*locp = loc;
return type;
}
static void KillOldUnusedStore(Location *loc, int ignorealiascount)
{ /* If the last reference to loc was in a store instruction, discard it.
We can ignore stores to something which may be an alias of loc,
but not loads from a possible alias.
*/
StoreAccessList *a = storeaccesses;
for (; a != NULL; a = cdr_(a), --ignorealiascount) {
Icode *ic = sa_ic_(a);
J_OPCODE op = ic->op;
if (locbase_(loc) != heapptr && LocInSet(loc, sa_locs_(a))) {
if (stores_r1(op) && !sa_needed_(a)) {
if (debugging(DEBUG_CSE)) {
cc_msg("-- killed unused");
print_jopcode(ic);
}
ic->op = J_NOOP;
}
return;
} else if (op != J_NOOP && !stores_r1(op) && ignorealiascount <= 0) {
bool notalias = YES;
LocSet *s = sa_locs_(a);
for (; s != NULL; s = cdr_(s))
if (possiblealias(loc, ls_loc_(s)))
notalias = NO;
else {
notalias = YES; break;
}
if (!notalias) return;
}
}
}
static void EnsureOldStore(Location *loc, int ignorealiascount)
{ /* If the last reference to loc was in a store instruction, ensure it
can't subsequently be discarded.
We can ignore stores to something which may be an alias of loc,
but not loads from a possible alias.
*/
StoreAccessList *a = storeaccesses;
for (; a != NULL; a = cdr_(a), --ignorealiascount) {
Icode *ic = sa_ic_(a);
J_OPCODE op = ic->op;
if (locbase_(loc) != heapptr && LocInSet(loc, sa_locs_(a))) {
if (stores_r1(op)) a->needed = YES;
return;
} else if (op != J_NOOP && !stores_r1(op) && ignorealiascount <= 0) {
bool notalias = YES;
LocSet *s = sa_locs_(a);
for (; s != NULL; s = cdr_(s))
if (possiblealias(loc, ls_loc_(s)))
notalias = NO;
else {
notalias = YES; break;
}
if (!notalias) return;
}
}
}
static bool CanAmalgamateStoreBytes(LocSet *locs) {
Location *baseloc = ls_loc_(locs);
Exprn *base = locbase_(baseloc);
int32 basek = locoff_(baseloc) & ~3;
StoreAccessList *a = storeaccesses;
int32 k, n = 0;
for (; a != NULL; a = cdr_(a)) {
LocSet *locs = sa_locs_(a);
if (loads_r1(sa_ic_(a)->op)) {
if (ls_loc_(locs)->load != base)
return NO;
} else {
Location *loc = NULL;
for (; locs != NULL; locs = cdr_(locs)) {
loc = ls_loc_(locs);
if (loctype_(loc) != LOC_(MEM_B))
return NO;
if (locbase_(loc) == base) break;
}
if (locs == NULL || (locoff_(loc) & ~3) != basek)
return NO;
k = locoff_(loc) & 3;
if (n & regbit(k))
return NO;
{ ExSet *locval = loc_read(loc, U_NOTREF+U_NOTDEF, j_to_ldrk(sa_ic_(a)->op));
int32 kval;
locval = MOVKinSet(locval);
if (locval == NULL)
return NO;
kval = e1k_(exs_ex_(locval));
if (kval != 0
&& (n != 0
|| (kval & 255) != kval
|| k != (target_lsbytefirst ? 0 : 3)))
return NO;
}
n |= regbit(k);
if (n == 15) {
StoreAccessList **prevp = &storeaccesses;
for (n = 0; n < 4;) {
StoreAccessList *a = *prevp;
Icode *ic = sa_ic_(a);
if (stores_r1(ic->op)) {
if (n > 0) {
if (debugging(DEBUG_CSE)) {
cc_msg("-- killed (amalgamated)");
print_jopcode(ic);
}
ic->op = J_NOOP;
}
n++;
*prevp = cdr_(a);
} else
prevp = &cdr_(a);
}
return YES;
}
}
}
return NO;
}
static Exprn *LocSetBase(LocSet *locs) {
Exprn *base = NULL;
for (; locs != NULL; locs = cdr_(locs))
if (!(loctype_(ls_loc_(locs)) & LOC_anyVAR)) {
if ((base = cse_AdconBase(locbase_(ls_loc_(locs)), YES)) != NULL)
break;
}
return base;
}
static int NonAliasLoadCount(LocSet *locs) {
Location *maxloc;
LocType maxtype = MaxLocType(locs, &maxloc);
StoreAccessList *a = storeaccesses;
int i = 0;
Exprn *base = (maxtype & LOC_anyVAR) ? NULL : LocSetBase(locs);
for (; a != 0; a = cdr_(a), i++)
if (a->ic->op != J_NOOP && !stores_r1(a->ic->op)) {
LocType type1; Location *loc1;
switch (type1 = MaxLocType(a->locs, &loc1)) {
case LOC_VAR:
case LOC_PVAR:
if (maxtype == type1) {
if (locbind_(loc1) == locbind_(maxloc))
goto DoReturn;
} else if (base == NULL ||
(exop_(base) == J_ADCONV && e1b_(base) == locbind_(loc1)))
goto DoReturn;
break;
default:
if (maxtype == LOC_VAR) break;
{ Exprn *base1 = LocSetBase(a->locs);
if (base == NULL || base1 == NULL || base1 == base)
goto DoReturn;
}
}
}
DoReturn:
return i;
}
static void KillRedundantStore(void) {
if (debugging(DEBUG_CSE)) {
cc_msg("-- redundant "); jopprint_opname(currenticode->op);
cc_msg("\n");
}
currenticode->op = J_NOOP;
}
static bool storein_i(VRegnum r1, ExSet *val, LocSet *locs, bool isvolatile) {
LocSet *p; ExSet *loadexs = NULL;
VRegSetP loads = NULL;
VRegSetP waslive = NULL;
int32 i;
bool old;
if (val != NULL && exop_(val->exprn) == CSE_LOADR)
val = cdr_(val);
for (i = 0, p = locs; p != NULL; i++, p = cdr_(p)) {
if (IsLive(ls_loc_(p)->load))
cseset_insert(i, waslive, &old);
ls_oldval_(p) = loc_read(ls_loc_(p), U_NOTREF, exop_(ls_loc_(p)->load));
}
if (!isvolatile)
for (p = locs; p != NULL; p = cdr_(p)) {
if (ExSetsOverlap(ls_oldval_(p), val)) {
for (p = locs; p != NULL; p = cdr_(p))
locvalue_(ls_loc_(p)) = ExSet_Append(val, ls_oldval_(p));
return YES;
}
}
{ int n = NonAliasLoadCount(locs);
for (i = 0, p = locs; p != NULL; i++, p = cdr_(p)) {
loadexs = ExSet_Insert(ls_loc_(p)->load, loadexs);
cseset_insert(exid_(ls_loc_(p)->load), loads, NULL);
if (cseset_member(i, waslive)) {
/* There is a load or store of this location within this block which
* is still valid. If a store, we may be able to eradicate it (if
* there is no intervening load from a possible alias).
*/
KillOldUnusedStore(ls_loc_(p), n);
}
}
}
{ int uflags = U_NOTREF+U_STORE;
if (r1 == GAP) uflags |= U_NOTDEF2;
for (p = locs; p != NULL; p = cdr_(p)) {
ExSet_Discard(ls_oldval_(p));
if (loctype_(ls_loc_(p)) & LOC_anyVAR)
setvar(ls_loc_(p), val, loads);
else
setmem(ls_loc_(p), val, loads);
useoldexprn(ls_loc_(p)->load, uflags);
exwaslive_(ls_loc_(p)->load) = YES;
}
}
cseset_discard(loads);
cseset_discard(waslive);
if (r1 != GAP) {
add_store_access(locs);
setreg(r1, loadexs, NO);
}
return NO;
}
static bool storein(VRegnum r1, Location *loc, ExSet *val, bool isvolatile) {
LocSet *locs = LocSet_New(NULL, loc);
if (locsynonym_(loc) != NULL) locs = LocSet_New(locs, locsynonym_(loc));
return storein_i(r1, val, locs, isvolatile);
}
static bool storeink(VRegnum r1, ExSet *val, LocType type, int32 m,
J_OPCODE load, ExSet *bases, bool isvolatile, LocSet **locp) {
LocSet *locs = NULL;
for (; bases != NULL; bases = cdr_(bases)) {
Location *loc = find_memloc(type, bases->exprn, m, load, LOC_REALBASE);
if (loc != NULL) {
locs = LocSet_New(locs, loc);
if (locsynonym_(loc) != NULL) locs = LocSet_New(locs, locsynonym_(loc));
}
}
if (locs == NULL) return NO;
*locp = locs;
return storein_i(r1, val, locs, isvolatile);
}
static VRegSetP deleteloadvariant(Location *loc, int32 variant, VRegSetP set)
{
Exprn *e = find_loadexprn(exop_(loc->load) | variant, loc,
U_NOTREF+U_NOTDEF+U_PEEK);
if (e != NULL)
return cseset_delete(exid_(e), set, NULL);
else
return set;
}
static VRegSetP deleteloads(Location *loc, VRegSetP set)
{
if (loc == NULL) return set;
cseset_delete(exid_(loc->load), set, NULL);
if (is_narrow(loc)) {
/* must remove all flavours of load */
set = deleteloadvariant(loc, J_SIGNED, set);
set = deleteloadvariant(loc, J_UNSIGNED, set);
}
return set;
}
static bool validdisplacement(J_OPCODE op, int32 n) {
return n >= MinMemOffset(op)
&& n <= MaxMemOffset(op)
&& (n & -MemQuantum(op)) == n;
}
static bool OpIs32MinusEx(Exprn const *e, Exprn const *ex) {
if (exop_(e) == J_SUBR) {
Exprn const *e1 = e1_(e);
return (exop_(e1) == J_MOVK && e1k_(e1) == 32 &&
e2_(e) == ex);
}
return NO;
}
static Exprn *SHRR_IsLogical(ExSet *e1, ExSet *e2) {
ExSet *e = NULL;
if ((e = ExSet_OpMember(e1, J_SHRR, J_SIGNbits)) == NULL) { /* @@@ J_TABLE_BITS */
if ((e = ExSet_OpMember(e2, J_SHRR, J_SIGNbits)) == NULL) {
return NULL;
} else {
ExSet *t = e1; e1 = e2; e2 = t;
}
}
{ Exprn *ee = e->exprn;
Exprn *shift = e2_(ee);
Exprn *ex;
e = ExSet_OpMember(e2, J_SUBK, 0);
if (e != NULL && e2k_(e->exprn) == 1) {
ex = e->exprn;
ex = e1_(ex);
if ((exop_(ex) & ~J_SIGNbits) == J_SHLR &&
exop_(e1_(ex)) == J_MOVK && e1k_(e1_(ex)) == 1 &&
OpIs32MinusEx(e2_(ex), shift))
return ee;
} else {
e = ExSet_OpMember(e2, J_NOTR, 0);
if (e != NULL) {
ex = e1_(e->exprn);
if ((exop_(ex) & ~J_SIGNbits) == J_SHLR &&
exop_(e1_(ex)) == J_MOVK && e1k_(e1_(ex)) == -1 &&
OpIs32MinusEx(e2_(ex), shift))
return ee;
}
}
}
return NULL;
}
#ifdef TARGET_HAS_ROTATE
static bool FindShiftPair(ExSet *e1, ExSet *e2, ExSet **shl, ExSet **shr) {
ExSet *e;
for (; (e1 = ExSet_OpMember(e1, J_SHLR, J_SIGNbits)) != NULL; e1 = cdr_(e1))
if ((e = OpInSetWithE1(e2, J_SHRR|J_UNSIGNED, 0, e1_(e1->exprn))) != NULL)
{
*shl = e1; *shr = e; return YES;
}
return NO;
}
static Exprn *ORRR_IsRORR(ExSet *e1, ExSet *e2) {
ExSet *ex1, *ex2;
if (!FindShiftPair(e1, e2, &ex1, &ex2) &&
!FindShiftPair(e2, e1, &ex1, &ex2))
return NULL;
{ Exprn *s1 = e2_(ex1->exprn),
*s2 = e2_(ex2->exprn);
if (OpIs32MinusEx(s2, s1) || OpIs32MinusEx(s1, s2))
if (IsLive(ex2->exprn))
return ex2->exprn;
}
return NULL;
}
#endif
static bool BottomBitsKnownZero(ExSet *e, int32 n) {
ExSet *ex = ExSet_OpMember(e, J_ANDK, 0);
if (ex != NULL && (e2k_(ex->exprn) & ((1L << n) - 1L)) == 0)
return YES;
ex = ExSet_OpMember(e, J_SHLK, J_SIGNbits);
if (ex != NULL && e2k_(ex->exprn) >= n)
return YES;
return NO;
}
static bool TopBitsKnownZero_e(Exprn *e, int32 n) {
if (exop_(e) == J_ANDK) {
if ((e2k_(e) & (0xffffffffL << (32-n))) == 0)
return YES;
} else if (exop_(e) == J_SHRK+J_UNSIGNED) {
int32 shift = e2k_(e);
if (shift >= n)
return YES;
else
return TopBitsKnownZero_e(e1_(e), n - shift);
}
#ifdef TARGET_HAS_SCALED_OPS
else if ((exop_(e) & ~(SHIFT_MASK<<J_SHIFTPOS)) == J_ANDR+(SHIFT_RIGHT<<J_SHIFTPOS)) {
int32 shift = (exop_(e) >> J_SHIFTPOS) & SHIFT_MASK;
if (shift >= n)
return YES;
else
return TopBitsKnownZero_e(e2_(e), n - shift);
}
#endif
return NO;
}
static bool TopBitsKnownZero(ExSet *e, int32 n) {
ExSet *ex = ExSet_OpMember(e, J_ANDK, 0);
if (ex != NULL)
return TopBitsKnownZero_e(ex->exprn, n);
ex = ExSet_OpMember(e, J_SHRK+J_UNSIGNED, 0);
if (ex != NULL)
return TopBitsKnownZero_e(ex->exprn, n);
#ifdef TARGET_HAS_SCALED_OPS
ex = ExSet_OpMember(e, J_ANDR+(SHIFT_RIGHT<<J_SHIFTPOS), SHIFT_MASK<<J_SHIFTPOS);
if (ex != NULL)
return TopBitsKnownZero_e(ex->exprn, n);
#endif
return NO;
}
#if defined TARGET_HAS_SCALED_ADDRESSING || defined TARGET_HAS_SCALED_OPS || \
defined TARGET_HAS_SCALED_ADD
static bool ShiftedOutBitsKnownZero(J_OPCODE op, ExSet *e) {
int32 shift = (op & J_SHIFTMASK) >> J_SHIFTPOS;
int32 shiftby = shift & SHIFT_MASK;
if (shiftby == 0)
return YES;
else if (shift & SHIFT_RIGHT)
return BottomBitsKnownZero(e, shiftby);
else
return TopBitsKnownZero(e, shiftby);
return NO;
}
#endif
#ifdef TARGET_ALLOWS_COMPARE_CSES
static bool AddCompare(Exprn *node, void *ignore) {
IGNORE(ignore);
cseset_insert(exid_(node), compares, NULL);
return YES;
}
#endif
static bool AddUse(Exprn *e, void *ignore) {
IGNORE(ignore);
if (!cseset_member(exid_(e), liveexprns))
exuses_(e) = ExprnUse_New(exuses_(e), 0, 0);
return YES;
}
#ifdef RANGECHECK_SUPPORTED
static bool ExprnWasntLive(Exprn *e, void *c) {
if (exwaslive_(e)) {
*(Exprn **)c = e;
return NO;
} else {
return YES;
}
}
#endif
static ExSet *FindRRSet(int32 op, ExSet *a, ExSet *b, int flags) {
ExSet *res = NULL;
int acount = 0, ocount = 0;
for (; a != NULL && (++acount <= 4 || ocount < 16); a = cdr_(a)) {
int bcount = 0;
ExSet *p = b;
for (; p != NULL && (++bcount <= 4 || ocount < acount * 4); p = cdr_(p)) {
Exprn *e = find_exprn(op, a->exprn, p->exprn, NULL, flags);
if (e != NULL) {
res = ExSet_Insert(e, res);
ocount++;
}
}
}
return res;
}
static ExSet *FindRKSet(int32 op, ExSet *a, IPtr m, int flags) {
/* m is union {int32,pointer} */
ExSet *res = NULL;
for (; a != NULL; a = cdr_(a)) {
Exprn *e = find_exprn(op, a->exprn, (Exprn *)m, NULL, flags);
if (e != NULL)
res = ExSet_Insert(e, res);
}
return res;
}
/* @@@ pure OPSYSK */
static struct {
Binder *f;
int32 argres;
int commutative;
} fcsrec;
static ExSet *FindCallSet_aux(
ExSet *arg[], Exprn *argex[], int32 argno, int32 maxarg, ExSet *res) {
if (argno > maxarg) {
Exprn *e = find_exprn(J_CALLK, (Exprn *)fcsrec.f,
(Exprn *)(IPtr)fcsrec.argres, argex, fcsrec.commutative);
if (e != NULL) res = ExSet_Insert(e, res);
} else {
ExSet *p = arg[argno];
int32 n;
for (n = 0; p != NULL && n <= 4; p = cdr_(p), n++) {
argex[argno] = p->exprn;
res = FindCallSet_aux(arg, argex, argno+1, maxarg, res);
}
}
return res;
}
static ExSet *FindCallSet(
Binder *f, int32 restype, int32 argdesc, ExSet *arg[]) {
Exprn *argex[NANYARGREGS==0 ? 1 : NANYARGREGS];
/* /* AM: the use of k_setflags_() to add a VREGSORT to replace a K_FLAGS */
/* field looks jolly dubious here... */
if (debugging(DEBUG_CSE))
cc_msg("FindCallset $b %lx %lx\n", f, restype, argdesc);
fcsrec.commutative = k_iscommutative_(argdesc) ? U_COMMUTATIVEFN : 0;
fcsrec.f = f; fcsrec.argres = k_setflags_(argdesc, restype);
return FindCallSet_aux(arg, argex, 0, k_argregs_(argdesc)-1, NULL);
}
static ExSet *FindRes2CallSet(
Binder *f, int32 restype, int32 argdesc, ExSet *arg[], Icode *c) {
ExSet *res = FindCallSet(f, restype, argdesc, arg);
ExSet *p;
for (p = res; p != NULL; p = cdr_(p)) {
Exprn *e = p->exprn;
/* care needs to be exercised here - the call of find_exprn
will have made e live, so its use in the RESULT2 exprn below
will always set exwaslive_.
*/
bool live = exwaslive_(e);
Exprn *e2 = find_exprn(J_RESULT2, e, NULL, NULL, U_NOTREF+U_NOTDEF2);
if (!live) {
exwaslive_(e) = NO;
exwaslive_(e2) = NO;
}
if (&useicode_(exuses_(e)) == c)
setvalno_(exuses_(e), 1);
p->exprn = e2;
}
return res;
}
static ExSet *Find2ResCallSet(
ExSet **res2, Binder *f, int32 restype, int32 argdesc, ExSet *arg[], Icode *c) {
ExSet *res = FindCallSet(f, restype, argdesc, arg);
ExSet *r2 = NULL;
ExSet *p;
for (p = res; p != NULL; p = cdr_(p)) {
Exprn *e = p->exprn;
bool live = exwaslive_(e);
Exprn *e2 = find_exprn(J_RESULT2, e, NULL, NULL, U_NOTREF+U_NOTDEF2);
if (!live) {
exwaslive_(e) = NO;
exwaslive_(e2) = NO;
}
if (&useicode_(exuses_(e)) == c)
setnvals_(exuses_(e), 1);
r2 = ExSet_Insert(e2, r2);
}
*res2 = r2;
return res;
}
static LocSet *rr_locs(J_OPCODE op, ExSet *e1, ExSet *e2) {
/* Note here that if scaled addressing is not supported the SUB option */
/* here will never get activated. The apparent test on the NEGINDEX bit */
/* is redundant but harmless. */
J_OPCODE op1 = OpWithShift(((op & NEGINDEX) ? J_SUBR : J_ADDR), op);
ExSet *rrset = FindRRSet(op1, e1, e2, U_NOTREF+U_NOTDEF);
LocSet *locs = NULL;
for (; rrset != NULL; rrset = cdr_(rrset))
locs = LocSet_New(locs,
find_memloc(loctype(op), rrset->exprn, 0, j_to_ldrk(op), 0));
return locs;
}
typedef struct {
J_OPCODE op;
LocSet *locs;
VRegnum r1;
bool isload;
} WTLRec;
static bool WorthTryingLocalCSE(Exprn *e, void *w) {
WTLRec *wp = (WTLRec *)w;
bool answ;
if (debugging(DEBUG_CSE) && CSEDebugLevel(5)) {
cc_msg("WorthTrying %ld(", (long)exid_(e));
jopprint_opname(wp->op);
cc_msg("%ld) %d ", (long)wp->r1, exwaslive_(e));
}
answ =
#if 0
( wp->isload &&
( extype_(e) != E_LOAD ||
!LocSet_Member(exloc_(e), wp->locs)
)
) /* That is, e is a propagated value */
? NO :
#endif
( ( exwaslive_(e) ||
( exop_(e) == J_RESULT2 &&
exwaslive_(e1_(e))
)
) &&
/* Surprisingly, it seems to be necessary here to make loads
of a non-known value into CSEs. That is,
( isload ? node != ... : (exwaslive_(node) || ...) )
produces a non-working compiler. What's going on here ?
*/
/* isany_realreg_(r1) means that the cost of making this a CSE
reference is likely to be larger by one MOVR. So if it is
anyway marginal, we don't make it a CSE. Something less
ad-hoc would be an improvement.
*/
!( isany_realreg_(wp->r1) &&
(wp->op == J_MOVK || wp->op == J_ADCON || wp->op == J_ADCONV)
)
);
if (debugging(DEBUG_CSE) && CSEDebugLevel(5))
cc_msg("=> %d\n", answ);
return answ;
}
/* Semi-global value propagation.
Handles forward propagation only (no loops in path)
*/
typedef struct LocValList LocValList;
typedef struct CompVals CompVals;
typedef struct CondList CondList;
struct CondList {
CondList *cdr;
int32 cond;
};
#define cl_cond_(p) ((p)->cond)
struct CompVals {
CompVals *cdr;
Exprn *ex;
CondList *cond;
};
#define cv_ex_(p) ((p)->ex)
#define cv_cond_(p) ((p)->cond)
struct LocValList {
LocValList *cdr;
Location *loc;
ExSet *vals;
};
#define lv_loc_(p) ((p)->loc)
#define lv_vals_(p) ((p)->vals)
struct SavedLocVals {
SavedLocVals *cdr;
BlockHead *exporter;
LocValList *locvals;
StoreAccessList *storeaccesses;
RegValue *exportedregs;
CompVals *comp;
};
#define sl_exporter_(p) ((p)->exporter)
#define sl_locvals_(p) ((p)->locvals)
#define sl_storeaccesses_(p) ((p)->storeaccesses)
#define sl_exportedregs_(p) ((p)->exportedregs)
#define sl_comp_(p) ((p)->comp)
#define mkSavedLocVals(a,b,c,d,e,f) (SavedLocVals *)syn_list6(a,b,c,d,e,f)
typedef struct {
int32 mask;
VRegnum r2;
ExSet *r2vals;
int32 m;
ExSet *cmpex;
} CmpRec;
#define cmp_mask_(p) ((p)->mask)
#define cmp_r2_(p) ((p)->r2)
#define cmp_r2vals_(p) ((p)->r2vals)
#define cmp_m_(p) ((p)->m)
#define cmp_ex_(p) ((p)->cmpex)
static CompVals *comparevalues;
#ifdef ENABLE_CSE
static void SavedLocVals_Print(LocValList const *p, char const *s1, char const *s2) {
cc_msg("%s{", s1);
for (; p != NULL; p = cdr_(p)) {
cc_msg(" {"); cse_print_loc(p->loc); cc_msg(" = "); ExSet_Print(p->vals, "}");
}
cc_msg("}%s", s2);
}
static void CompVals_Print(CompVals const *cv) {
for (; cv != NULL; cv = cdr_(cv)) {
CondList *cl = cv->cond;
cc_msg(" {%ld", (long)exid_(cv->ex));
for (; cl != NULL; cl = cdr_(cl))
cc_msg(" %s", condition_name(cl->cond));
cc_msg("}");
}
}
#else
static void SavedLocVals_Print(LocValList const *p, char const *s1, char const *s2) {
IGNORE(p); IGNORE(s1); IGNORE(s2);
}
static void CompVals_Print(CompVals const *cv, char const *s) {
IGNORE(cv); IGNORE(s);
}
#endif
static int32 Cond_Or(int32 a, int32 b) {
if (Q_implies(a, b)) return b;
if (Q_implies(b, a)) return a;
switch (Q_CondPair(a, b)) {
case Q_CondPair(Q_LT, Q_EQ):
case Q_CondPair(Q_LT, Q_UEQ): return Q_LE;
case Q_CondPair(Q_GT, Q_EQ):
case Q_CondPair(Q_GT, Q_UEQ): return Q_GE;
case Q_CondPair(Q_LO, Q_EQ):
case Q_CondPair(Q_LO, Q_UEQ): return Q_LS;
case Q_CondPair(Q_HI, Q_EQ):
case Q_CondPair(Q_HI, Q_UEQ): return Q_HS;
case Q_CondPair(Q_LT, Q_GT): return Q_NE;
case Q_CondPair(Q_LO, Q_HI): return Q_NE;
}
return Q_AL;
}
static int32 Cond_And(int32 a, int32 b) {
if (Q_implies(a, b)) return a;
if (Q_implies(b, a)) return b;
switch (Q_CondPair(a, b)) {
case Q_CondPair(Q_LE, Q_GE): return Q_EQ;
case Q_CondPair(Q_LS, Q_HS): return Q_EQ;
case Q_CondPair(Q_LE, Q_NE):
case Q_CondPair(Q_LE, Q_UNE): return Q_LT;
case Q_CondPair(Q_GE, Q_NE):
case Q_CondPair(Q_GE, Q_UNE): return Q_GT;
case Q_CondPair(Q_LS, Q_NE):
case Q_CondPair(Q_LS, Q_UNE): return Q_LO;
case Q_CondPair(Q_HS, Q_NE):
case Q_CondPair(Q_HS, Q_UNE): return Q_HI;
}
return Q_AL;
}
#define CondList_New(cl, cond) ((CondList *)CSEList2(cl, cond))
static CondList *CondList_Copy(CondList const *cl) {
CondList *p = NULL;
for (; cl != NULL; cl = cdr_(cl))
p = CondList_New(p, cl->cond);
return p;
}
static CondList *CondList_Insert(int32 cond, CondList *cl) {
CondList *p = NULL;
for (; cl != NULL; cl = cdr_(cl))
if (Q_implies(cond, cl->cond)) {
/* The condition to be inserted is narrower than an existing one: */
/* drop the existing one (and add the new one later) */
} else {
int32 newcond = Cond_And(cond, cl->cond);
if (newcond == Q_AL)
newcond = cl->cond;
else
cond = Q_AL;
p = CondList_New(p, newcond);
}
if (cond != Q_AL) p = CondList_New(p, cond);
return p;
}
#define CompVals_New(next, ex, conds) ((CompVals *)CSEList3(next, ex, conds))
static CompVals *CompVals_Copy(CompVals const *cv) {
CompVals *p = NULL;
for (; cv != NULL; cv = cdr_(cv))
p = CompVals_New(p, cv->ex, CondList_Copy(cv->cond));
return p;
}
static CompVals *CompVals_Delete(CompVals const *del, CompVals const *cv) {
CompVals *p = NULL;
for (; cv != NULL; cv = cdr_(cv))
if (cv != del)
p = CompVals_New(p, cv->ex, CondList_Copy(cv->cond));
return p;
}
static CompVals const *CompVals_ExprnMember(Exprn const *ex, CompVals const *cv) {
for (; cv != NULL; cv = cdr_(cv))
if (ex == cv->ex)
return cv;
return NULL;
}
static CompVals *CompVals_AddOne(CompVals *cv, Exprn *ex, int32 cond) {
CompVals const *p = CompVals_ExprnMember(ex, cv);
if (p != NULL) {
CondList *cl = p->cond;
for (; cl != NULL; cl = cdr_(cl))
if (Q_implies(cl->cond, cond))
return cv;
return CompVals_New(CompVals_Delete(p, cv), ex, CondList_Insert(cond, CondList_Copy(p->cond)));
}
return CompVals_New(cv, ex, CondList_Insert(cond, NULL));
}
static CompVals *CompVals_Add(CompVals *cv, ExSet const *ex, int32 cond) {
if (cond != Q_AL && cond != Q_NOT)
for (; ex != NULL; ex = cdr_(ex))
cv = CompVals_AddOne(cv, ex->exprn, cond);
return cv;
}
static CompVals *CompVals_Intersect(CompVals *a, CompVals const *b) {
CompVals *p, **pp = &a;
for (; (p = *pp) != NULL;) {
CompVals const *bp = CompVals_ExprnMember(p->ex, b);
if (bp == NULL
|| cdr_(p->cond) != NULL || cdr_(bp->cond) != NULL)
*pp = cdr_(p);
else {
int32 cond = Cond_Or(p->cond->cond, bp->cond->cond);
if (cond == Q_AL)
*pp = cdr_(p);
else {
p->cond->cond = cond;
pp = &cdr_(p);
}
}
}
return a;
}
static LocValList *LocValList_New(LocValList *next, Location *loc, ExSet *vals) {
return (LocValList *)CSEList3(next, loc, vals);
}
static LocValList *LocValList_DiscardOne(LocValList *vals) {
return (LocValList *)discard3((VoidStar)vals);
}
static LocValList *LocValList_FindLoc(LocValList *vals, Location const *loc) {
for (; vals != NULL; vals = cdr_(vals))
if (vals->loc == loc) return vals;
return NULL;
}
static LocValList *LocValList_Copy(LocValList const *v) {
LocValList *res = NULL, **resp = &res;
for (; v != NULL; v = cdr_(v)) {
LocValList *p = LocValList_New(NULL, v->loc, ExSet_Copy(v->vals));
*resp = p; resp = &cdr_(p);
}
return res;
}
static LocValList *LocValList_Intersect(LocValList *a, LocValList *b) {
/* Destructively modifies a, removing everything not also present in b */
LocValList *v, **vp = &a;
for (; (v = *vp) != NULL;) {
LocValList *t = LocValList_FindLoc(b, v->loc);
if (t == NULL) {
ExSet_Discard(v->vals);
*vp = LocValList_DiscardOne(v);
} else {
v->vals = ExSet_Intersection(v->vals, t->vals);
if (v->vals == NULL)
*vp = LocValList_DiscardOne(v);
else
vp = &cdr_(v);
}
}
return a;
}
static RegValue *MergeRegValues(RegValue *rv1, RegValue *rv2) {
RegValue *res = NULL;
for (; rv2 != NULL; rv2 = cdr_(rv2)) {
VRegnum r = rv_reg_(rv2);
RegValue *p = rv1;
for (; p != NULL; p = cdr_(p))
if (rv_reg_(p) == r) {
ExSet *ex = ExSet_Copy(rv_val_(p));
ex = ExSet_Intersection(ex, rv_val_(rv2));
if (ex != NULL) res = RegValue_New(res, r, ex);
break;
}
}
return res;
}
static VRegnum CheckForTernaryExprn(SavedLocVals const *sv, Exprn **tep) {
SavedLocVals *sv1 = cdr_(sv);
if (cdr_(sv1) == NULL) {
CompVals *cv = sl_comp_(sv);
for (; cv != NULL; cv = cdr_(cv)) {
CompVals const *cv1 = CompVals_ExprnMember(cv_ex_(cv), sl_comp_(sv1));
if (cv1 != NULL) {
CondList *cl = cv_cond_(cv);
for (; cl != NULL; cl = cdr_(cl)) {
CondList *cl1 = cv_cond_(cv1);
for (; cl1 != NULL; cl1 = cdr_(cl1))
if (cl_cond_(cl) == Q_NEGATE(cl_cond_(cl1))) {
RegValue *rv = sl_exportedregs_(sv);
for (; rv != NULL; rv = cdr_(rv)) {
RegValue const *rv1 = RegValue_RegMember(rv_reg_(rv), sl_exportedregs_(sv1));
if (rv1 != NULL && !ExSetsOverlap(rv_val_(rv), rv_val_(rv1))) {
Exprn *e2 = exs_ex_(rv_val_(rv));
Exprn *e3 = exs_ex_(rv_val_(rv1));
if (extype_(e2) != E_LOADR && extype_(e3) != E_LOADR) {
*tep = find_exprn(CSE_COND|cl->cond, cv_ex_(cv), e2, &e3, 0);
return rv_reg_(rv);
}
}
}
}
}
break;
}
}
}
return GAP;
}
static VRegSetP setnotused;
static void ImportLocVals(BlockHead *block) {
comparevalues = NULL;
if (blk_pred_(block) != NULL && !(var_cc_private_flags & 64L)) {
if (debugging(DEBUG_CSE) && CSEDebugLevel(2)) {
SavedLocVals *p = blk_locvals_(block);
BlockList *pred = blk_pred_(block);
char *s = "\n ";
cc_msg(" predecessors");
for (; pred != NULL; pred = pred->blklstcdr)
cc_msg(" %ld", blklabname_(pred->blklstcar));
for (; p != NULL; p = cdr_(p)) {
cc_msg(" %s [%ld] ", s, blklabname_(sl_exporter_(p)));
SavedLocVals_Print(sl_locvals_(p), "", " ");
if (sl_storeaccesses_(p) != NULL) StoreAccessList_Print(sl_storeaccesses_(p), " ");
if (sl_exportedregs_(p) != NULL) RegValue_Print(sl_exportedregs_(p), "");
if (sl_comp_(p) != NULL) CompVals_Print(sl_comp_(p));
cc_msg("\n");
s = "+ ";
}
}
if (length((List *)blk_pred_(block)) == length((List *)blk_locvals_(block))) {
SavedLocVals *sv = blk_locvals_(block);
/* LocValLists are now no longer shared, but we still need to make a copy
since the original LocValLists may be wanted later */
LocValList *vals = LocValList_Copy(sv->locvals);
Exprn *ternaryex = NULL;
if (cdr_(sv) == NULL)
storeaccesses = StoreAccessList_Copy(sl_storeaccesses_(sv));
else
blk_ternaryr_(block) = CheckForTernaryExprn(sv, &ternaryex);
knownregs = sl_exportedregs_(sv);
comparevalues = CompVals_Copy(sl_comp_(sv));
for (; (sv = cdr_(sv)) != NULL; ) {
vals = LocValList_Intersect(vals, sl_locvals_(sv));
knownregs = MergeRegValues(knownregs, sl_exportedregs_(sv));
comparevalues = CompVals_Intersect(comparevalues, sl_comp_(sv));
}
if (ternaryex != NULL) {
VRegnum r = blk_ternaryr_(block);
knownregs = RegValue_New(knownregs, r, ExprnToSet(ternaryex));
cseset_insert(r, setnotused, NULL);
}
if (debugging(DEBUG_CSE) && CSEDebugLevel(2))
if (cdr_(blk_pred_(block)) != NULL) {
SavedLocVals_Print(vals, " => ", " ");
if (knownregs != NULL) RegValue_Print(knownregs, "");
if (comparevalues != NULL) CompVals_Print(comparevalues);
cc_msg("\n");
}
for (; vals != NULL; vals = LocValList_DiscardOne(vals)) {
ExSet *s;
bool old;
locvalue_(lv_loc_(vals)) = lv_vals_(vals);
ExSet_Map(lv_vals_(vals), AddToLocs, lv_loc_(vals));
for (s = lv_vals_(vals); s != NULL; s = cdr_(s))
cseset_insert(exid_(s->exprn), liveexprns, &old);
cseset_insert(exid_(lv_loc_(vals)->load), liveexprns, &old);
}
{ StoreAccessList *sa;
RegValue *rv;
CompVals *cv;
bool old;
for (sa = storeaccesses; sa != NULL; sa = cdr_(sa)) {
LocSet *locs = sa_locs_(sa);
for (; locs != NULL; locs = cdr_(locs))
cseset_insert(exid_(ls_loc_(locs)->load), liveexprns, &old);
}
for (rv = knownregs; rv != NULL; rv = cdr_(rv)) {
ExSet *vals = rv_val_(rv);
cseset_insert(rv_reg_(rv), setnotused, NULL);
for (; vals != NULL; vals = cdr_(vals))
cseset_insert(exid_(vals->exprn), liveexprns, &old);
}
for (cv = comparevalues; cv != NULL; cv = cdr_(cv))
cseset_insert(exid_(cv_ex_(cv)), liveexprns, &old);
}
}
}
}
static void SavedLocVals_Add(BlockHead *block, BlockHead *b, LocValList *lv,
StoreAccessList *sa, RegValue *rv, CompVals *comp) {
blk_locvals_(block) = mkSavedLocVals(blk_locvals_(block), b, lv, sa, rv, comp);
}
static void SaveLocVals(
BlockHead *block, LabelNumber *lab, LocValList *locvals,
J_OPCODE op, ExSet *r2vals, int32 n,
StoreAccessList *sl, RegValue *rv, CompVals *comp) {
if (!is_exit_label(lab) && !blk_scanned_(lab->block)) {
LocValList *lv = LocValList_Copy(locvals);
if (op != J_NOOP) {
for (; r2vals != NULL; r2vals = cdr_(r2vals)) {
int32 n1 = n;
Location *loc = NULL;
Exprn *r2ex = r2vals->exprn;
if (extype_(r2ex) == E_LOAD)
loc = exloc_(r2ex);
else if ((exop_(r2ex) == J_ADDK || exop_(r2ex) == J_SUBK) &&
extype_(e1_(r2ex)) == E_LOAD) {
loc = exloc_(e1_(r2ex));
if (exop_(r2ex) == J_ADDK)
n1 -= e2k_(r2ex);
else
n1 += e2k_(r2ex);
}
if (loc != NULL) {
Exprn *ex = find_unaryk(op, n1, U_NOTDEF2+U_NOTREF);
LocValList *p = LocValList_FindLoc(lv, loc);
if (p == NULL)
lv = LocValList_New(lv, loc, ExprnToSet(ex));
else
p->vals = ExSet_Insert(ex, p->vals);
}
}
}
SavedLocVals_Add(lab->block, block, lv, StoreAccessList_Copy(sl), rv, comp);
}
}
static RegValue *RegValue_CopyList(RegValue const *rv) {
RegValue *p = NULL;
for (; rv != NULL; rv = cdr_(rv))
p = RegValue_New(p, rv_reg_(rv), ExSet_Copy(rv_val_(rv)));
return p;
}
static RegValue *RegValueForReg(VRegnum r) {
ExSet *rvals = valueinreg(r);
return (rvals == NULL) ? NULL :
RegValue_New(NULL, r, ExSet_Copy(rvals));
}
static RegValue *ExportedR2Val(RegValue *exportedr, BlockHead *bfrom, CmpRec *cmpk, LabelNumber *lab) {
if (!is_exit_label(lab) && !blk_scanned_(lab->block)) {
BlockHead *bto = lab->block;
if (exportedr != NULL)
exportedr = RegValue_CopyList(exportedr);
if (((blkflags_(bto) & BLK2EXIT) && blklength_(bto) <= 1)
|| (cmp_mask_(cmpk) != Q_AL && (blkflags_(bfrom) & BLKREXPORTED))) {
RegValue *p = RegValueForReg(cmp_r2_(cmpk));
if (p == NULL)
return exportedr;
else {
if (exportedr != NULL)
cdr_(p) = exportedr;
return p;
}
} else if (blklength_(bfrom) == 0) {
RegValue *rv = knownregs;
for (; rv != NULL; rv = cdr_(rv)) {
RegValue *q = RegValueForReg(rv->reg);
if (q != NULL) { cdr_(q) = exportedr; exportedr = q; }
}
}
return exportedr;
}
return NULL;
}
static void RewriteNext(BlockHead *b, LabelNumber *oldlab, LabelNumber *newlab,
SavedLocVals *sv) {
bool ok = NO;
if (blkflags_(b) & BLKSWITCH) {
int32 n = blktabsize_(b);
LabelNumber **table = blktable_(b);
for (; --n >= 0; )
if (table[n] == oldlab)
ok = YES, table[n] = newlab;
} else {
if ((blkflags_(b) & BLK2EXIT) && blknext1_(b) == oldlab)
ok = YES, blknext1_(b) = newlab;
if (blknext_(b) == oldlab)
ok = YES, blknext_(b) = newlab;
}
if (!ok) syserr(cse_rewritenext, blklabname_(b), lab_name_(oldlab));
if (!is_exit_label(newlab)) {
BlockHead *newdest = newlab->block;
if (cse_AddPredecessor(newlab, b) && !blk_scanned_(newlab->block)) {
RegValue *rv = sv->exportedregs;
RegValue *newrv = rv == NULL ? NULL :
RegValue_New(NULL, rv_reg_(rv), ExSet_Copy(rv_val_(rv)));
SavedLocVals_Add(newdest, sv->exporter, LocValList_Copy(sv->locvals),
StoreAccessList_Copy(sv->storeaccesses),
newrv,
CompVals_Copy(sv->comp));
} else {
SavedLocVals *newsv = blk_locvals_(newdest);
for (; newsv != NULL; newsv = cdr_(newsv))
if (newsv->exporter == b) {
sl_locvals_(newsv) = LocValList_Intersect(sl_locvals_(newsv), sl_locvals_(sv));
sl_exportedregs_(newsv) = MergeRegValues(sl_exportedregs_(newsv), sl_exportedregs_(sv));
sl_comp_(newsv) = CompVals_Intersect(sl_comp_(newsv), sl_comp_(sv));
break;
}
}
}
}
static void ELV_cb(int32 n, void *arg) {
RegValue **pp = (RegValue **)arg;
RegValue *rv = RegValueForReg(n);
if (rv != NULL) {
cdr_(rv) = *pp;
*pp = rv;
}
}
static void ExportLocVals(BlockHead *block, CmpRec *cmpk,
bool sideeffectfree, VRegSetP exportedregs) {
/* Also, as a side effect, clear the known value of all Locations */
int32 i;
SavedLocVals *sv = blk_locvals_(block);
LocValList *locvals = NULL;
CompVals *cv, *compvals = NULL;
RegValue *exportedr = NULL;
if (sideeffectfree &&
!(blkflags_(block) & (BLKLOOP|BLK2EXIT|BLKSWITCH|BLKREXPORTED)) &&
!is_exit_label(blknext_(block)) && !blk_scanned_(blknext_(block)->block)) {
LabelNumber *lab = blklab_(block);
if (lab != blknext_(block))
for (; sv != NULL; sv = cdr_(sv)) {
BlockHead *prev = sl_exporter_(sv);
if (debugging(DEBUG_CSE) && CSEDebugLevel(2))
cc_msg("Block %ld successor rewritten from %ld to %ld\n",
blklabname_(prev), lab_name_(lab), lab_name_(blknext_(block)));
RewriteNext(prev, lab, blknext_(block), sv);
KillArc(prev, lab);
}
}
if (blklength_(block) != 0) {
VRegSetP rs = cseset_copy(exportedregs);
bool old;
for (i = R_A1; i < R_A1 + NARGREGS; i++)
rs = cseset_insert(i, rs, &old);
cseset_map(rs, ELV_cb, &exportedr);
}
for (sv = blk_locvals_(block); sv != NULL; sv = cdr_(sv)) {
LocValList *lv = sl_locvals_(sv);
for (; lv != 0; lv = LocValList_DiscardOne(lv))
ExSet_Discard(lv->vals);
sl_locvals_(sv) = NULL;
StoreAccessList_Discard(sl_storeaccesses_(sv));
}
for (cv = comparevalues; cv != NULL; cv = cdr_(cv)) {
if (!cse_KilledInBlock(exid_(cv->ex)))
compvals = CompVals_New(compvals, cv->ex, CondList_Copy(cv->cond));
}
for (i = 0 ; i < LOCINDEXSIZE ; i++) {
Location **index = locindex[i];
int32 j;
if (index == 0) break;
for (j = 0 ; j < LOCSEGSIZE ; j++) {
Location *q = index[j];
ExSet *vals;
if (q == NULL) break;
vals = locvalue_(q);
locvalue_(q) = NULL;
if (q->load != NULL && IsLive(q->load)) {
vals = LiveExSet(vals);
if (vals != NULL) locvals = LocValList_New(locvals, q, vals);
} else
ExSet_Discard(vals);
}
}
if (blk_pred_(block) != NULL || block == top_block) {
if (!(var_cc_private_flags & 64L)) {
if (blkflags_(block) & BLKSWITCH) {
int32 n = blktabsize_(block);
LabelNumber **table = CSENewN(LabelNumber *, n);
memcpy(table, blktable_(block), (size_t)n * sizeof(LabelNumber *));
while (--n > 0) {
LabelNumber *lab = table[n];
if (lab != NULL) {
int32 j;
J_OPCODE op = J_MOVK;
for (j = n; --j >= 0; )
if (table[j] == lab) op = J_NOOP, table[j] = 0;
SaveLocVals(block, lab, locvals, op, cmp_r2vals_(cmpk), n-1, NULL,
RegValue_CopyList(exportedr), compvals);
}
}
if (table[0] != NULL)
SaveLocVals(block, table[0], locvals, J_NOOP, NULL, 0, NULL,
RegValue_CopyList(exportedr), compvals);
} else if (blkflags_(block) & BLK2EXIT) {
J_OPCODE op, op1;
if (cmp_mask_(cmpk) == Q_EQ)
op = J_NEK, op1 = J_MOVK;
else if (cmp_mask_(cmpk) == Q_NE)
op = J_MOVK, op1 = J_NEK;
else
op = op1 = J_NOOP;
SaveLocVals(block, blknext1_(block), locvals, op1, cmp_r2vals_(cmpk), cmp_m_(cmpk),
NULL, ExportedR2Val(exportedr, block, cmpk, blknext1_(block)),
CompVals_Add(compvals, cmp_ex_(cmpk), cmp_mask_(cmpk)));
SaveLocVals(block, blknext_(block), locvals, op, cmp_r2vals_(cmpk), cmp_m_(cmpk),
NULL, ExportedR2Val(exportedr, block, cmpk, blknext_(block)),
CompVals_Add(compvals, cmp_ex_(cmpk), Q_NEGATE(cmp_mask_(cmpk))));
} else {
/* Remove from storeaccesses everything that isn't live, since
liveness info isn't a thing that gets exported.
*/
StoreAccessList **slp = &storeaccesses, *sl;
for (; (sl = *slp) != NULL;) {
LocSet **locsp = &sa_locs_(sl), *locs;
for (; (locs = *locsp) != NULL;) {
Location *loc = locs->loc;
if (!IsLive(loc->load)) {
*locsp = cdr_(locs);
if (!stores_r1(sa_ic_(sl)->op)) {
/* This is a load : all possibly aliasing earlier stores */
/* must be removed (or they may later be discarded as */
/* unwanted */
StoreAccessList **slp2 = &cdr_(sl), *sl2;
for (; (sl2 = *slp2) != NULL;) {
LocSet **locsp2 = &sa_locs_(sl2), *locs2;
for (; (locs2 = *locsp2) != NULL;) {
Location *loc2 = locs2->loc;
if (loc == loc2 || possiblealias(loc, loc2))
*locsp2 = cdr_(locs2);
else
locsp2 = &cdr_(locs2);
}
if (sa_locs_(sl2) == NULL)
*slp2 = cdr_(sl2);
else
slp2 = &cdr_(sl2);
}
}
} else
locsp = &cdr_(locs);
}
if (sl->locs == NULL)
*slp = cdr_(sl);
else
slp = &cdr_(sl);
}
if (cmpk->mask != Q_AL)
exportedr = ExportedR2Val(exportedr, block, cmpk, blknext_(block));
SaveLocVals(block, blknext_(block), locvals, J_NOOP, NULL, 0,
storeaccesses, exportedr, compvals);
}
}
}
for (; locvals != NULL; locvals = LocValList_DiscardOne(locvals))
ExSet_Discard(locvals->vals);
}
#define SetTaken(val) (*taken = (val), YES)
static bool ComparisonValueKnown(bool *taken, CmpRec const *cmpk, CompVals const *cv) {
for (; cv != NULL; cv = cdr_(cv)) {
Exprn *ex = cv_ex_(cv);
if (!cse_KilledInBlock(exid_(ex))) {
if (ExSet_Member(ex, cmp_ex_(cmpk))) {
CondList *cl = cv_cond_(cv);
for (; cl != NULL; cl = cdr_(cl))
if (Q_implies(cl_cond_(cl), cmp_mask_(cmpk)))
return SetTaken(YES);
else if (Q_implies(cl_cond_(cl), Q_NEGATE(cmp_mask_(cmpk))))
return SetTaken(NO);
return NO;
} else if (exop_(ex) == J_CMPK
&& cmp_ex_(cmpk) != NULL
&& exop_(exs_ex_(cmp_ex_(cmpk))) == J_CMPK) {
ExSet *es = cmp_ex_(cmpk);
Exprn *e1 = e1_(ex);
for (; es != NULL; es = cdr_(es)) {
if (e1 == e1_(exs_ex_(es))) {
int32 k1 = e2k_(ex),
k2 = e2k_(exs_ex_(es));
CondList *cl = cv_cond_(cv);
for (; cl != NULL; cl = cdr_(cl)) {
switch (cl_cond_(cl)) {
case Q_GE:
case Q_GT: if (k1 > k2)
switch (cmp_mask_(cmpk)) {
case Q_GT: case Q_GE: case Q_NE:
return SetTaken(YES);
case Q_LT: case Q_LE: case Q_EQ:
return SetTaken(NO);
}
break;
case Q_LE:
case Q_LT: if (k1 < k2)
switch (cmp_mask_(cmpk)) {
case Q_LT: case Q_LE: case Q_NE:
return SetTaken(YES);
case Q_GT: case Q_GE: case Q_EQ:
return SetTaken(NO);
}
break;
case Q_HS:
case Q_HI: if ((uint32)k1 > (uint32)k2)
switch (cmp_mask_(cmpk)) {
case Q_HI: case Q_HS: case Q_NE:
return SetTaken(YES);
case Q_LO: case Q_LS: case Q_EQ:
return SetTaken(NO);
}
break;
case Q_LS:
case Q_LO: if ((uint32)k1 < (uint32)k2)
switch (cmp_mask_(cmpk)) {
case Q_LS: case Q_LO: case Q_NE:
return SetTaken(YES);
case Q_HI: case Q_HS: case Q_EQ:
return SetTaken(NO);
}
break;
}
}
}
}
}
}
}
return NO;
}
#undef SetTaken
static void MaybeKillBranchToBlock(BlockHead *block, CmpRec *cmpk) {
/* <block> ends with a CMPK, and is known to be otherwise side-effect */
/* free. For any predecessors for which the result of the comparison */
/* is known, we may change the successor <block> to the appropraite */
/* successor of <block>. */
SavedLocVals *sv = blk_locvals_(block),
*nextsv;
LabelNumber *lab = blklab_(block);
for (; sv != NULL; sv = nextsv) {
/* We must take a copy here, because if the arc from sv->exporter */
/* to block is killed, sv is removed from block and attached to */
/* the arc's new destination. */
nextsv = cdr_(sv);
if (!(blkflags_(sl_exporter_(sv)) & BLKSWITCH)) {
ExSet *p;
BlockHead *prev = sl_exporter_(sv);
LabelNumber *nextlab = NULL;
/* First try for the value of the comparison being known because */
/* a variable with known value is its subject */
if (cmpk->r2vals == NULL) {
RegValue const *rv = RegValue_RegMember(cmp_r2_(cmpk), sl_exportedregs_(sv));
if (rv != NULL) {
ExSet *c1 = MOVKinSet(rv_val_(rv));
if (c1 != NULL)
nextlab = ComparisonDest(e1k_(exs_ex_(c1)), cmp_m_(cmpk), block);
}
} else for (p = cmp_r2vals_(cmpk); p != NULL; p = cdr_(p))
if (extype_(exs_ex_(p)) == E_LOAD) {
LocValList *vals = LocValList_FindLoc(sl_locvals_(sv), exloc_(exs_ex_(p)));
if (vals != NULL) {
ExSet *c1 = MOVKinSet(lv_vals_(vals));
if (c1 != NULL) {
nextlab = ComparisonDest(e1k_(exs_ex_(c1)), cmp_m_(cmpk), block);
break;
} else {
/* Otherwise, see whether the subject of the comparison */
/* is known not to have the value compared against. This */
/* is not the same as the case below, because knowledge */
/* that it doesn't have a particular value need not come */
/* from there having been a comparison. For example, */
/* &global is known non-zero if global isn't weak. */
c1 = ExSet_OpMember(lv_vals_(vals), J_NEK, 0);
if (c1 != NULL && e1k_(exs_ex_(c1)) == cmp_m_(cmpk)) {
if (cmp_mask_(cmpk) == Q_EQ) {
nextlab = blknext_(block);
break;
} else if (cmp_mask_(cmpk) == Q_NE) {
nextlab = blknext1_(block);
break;
}
}
}
}
}
if (nextlab == NULL) {
/* Finally, see whether the result of the comparison can be */
/* inferred from one whose result is known */
bool taken;
if (cmp_ex_(cmpk) == NULL)
for (p = cmpk->r2vals; p != NULL; p = cdr_(p)) {
Exprn *e = find_binaryk(J_CMPK, exs_ex_(p), cmp_m_(cmpk), U_PEEK);
if (e != NULL)
cmp_ex_(cmpk) = ExSet_Insert(e, cmp_ex_(cmpk));
}
if (ComparisonValueKnown(&taken, cmpk, sl_comp_(sv)))
nextlab = taken ? blknext1_(block) : blknext_(block);
}
if (nextlab != NULL && lab != nextlab) {
if (debugging(DEBUG_CSE) && CSEDebugLevel(2))
cc_msg("Block %ld successor rewritten from %ld to %ld\n",
blklabname_(prev), lab_name_(lab), lab_name_(nextlab));
RewriteNext(prev, lab, nextlab, sv);
KillArc(prev, lab);
}
}
}
}
typedef struct {
Binder *base;
int32 k;
} AdconRec;
static J_OPCODE AdconInSet(ExSet *e, AdconRec *ad) {
ExSet *c;
J_OPCODE op;
if ((c = ExSet_OpMember(e, J_ADDK, 0)) != NULL) {
Exprn *e = c->exprn;
J_OPCODE opa = exop_(e1_(e));
op = opa & ~J_BASEALIGN4;
if (op == J_ADCONV || op == J_ADCON) {
ad->k = e2k_(e);
ad->base = e1b_(e1_(e));
return opa;
}
}
if ((c = ExSet_OpMember(e, J_ADCONV, J_BASEALIGN4)) != NULL ||
(c = ExSet_OpMember(e, J_ADCON, J_BASEALIGN4)) != NULL) {
Exprn *e = c->exprn;
ad->k = 0;
ad->base = e1b_(e);
return exop_(e);
}
return 0;
}
static void OpRewritten(Icode const *c) {
if (debugging(DEBUG_CSE) && CSEDebugLevel(1)) {
cc_msg("rewritten: ");
print_jopcode(c);
}
}
static void KillExpr(ExSet *s, Icode *p) {
ptrdiff_t icoden = p - blkcode_(cse_currentblock);
bool wasLocalCSE = cse_KillExprRef(s, p);
for (; s != NULL; s = cdr_(s)) {
Exprn *ex = s->exprn;
ExprnUse *use, **usep;
for (usep = &exuses_(ex); (use = *usep) != NULL; usep = &cdr_(use))
if (use->block == cse_currentblock && icoden_(use) == icoden) {
*usep = cdr_(use);
if (!wasLocalCSE) {
cseset_delete(exid_(ex), availableexprns, NULL);
cseset_delete(exid_(ex), wantedexprns, NULL);
}
break;
}
}
}
#define setnotused_insert(x, s) \
if (x >= NMAGICREGS) { cseset_insert(x, s, NULL); } else sideeffectfree = NO
#define setnotused_delete(x, s) cseset_delete(x, s, NULL)
/* These are now functions in preparation for use of J_VOLATILE. */
static bool load_isvolatile(Icode const *c, Icode const *limit)
{ Icode const *nextic = c + 1;
return nextic < limit &&
(nextic->op== J_USE || nextic->op == J_USEF || nextic->op == J_USED);
}
static bool store_isvolatile(Icode const *c, Icode const *limit)
{ Icode const *nextic = c + 1;
return nextic < limit && nextic->op == J_VSTORE;
}
static void corrupt_f(RealRegister r, RealRegSet_MapArg *a)
{ IGNORE(a);
cse_corrupt_register(r);
}
static void cse_scanblock(BlockHead *block)
{
Icode *c, *limit;
CmpRec cmpk;
LocSet *locs = NULL;
int32 flags = blkflags_(block); /* remember these now, because they may */
LabelNumber *exit = blknext_(block); /* get altered (by value propagation to */
#ifdef ENABLE_CSE
LabelNumber *exit1 = blknext1_(block); /* a compare) before we reach the end. */
#endif
bool sideeffectfree = YES;
int callcount = 0;
bool istop = block == top_block;
cmpk.mask = Q_AL;
setnotused = NULL;
storeaccesses = NULL;
cse_currentblock = block;
currenticode = blkcode_(block)-1;
blocksetup();
ImportLocVals(block);
for (c = blkcode_(block), limit = c + blklength_(block); c < limit; ++c) {
#ifdef TARGET_IS_ARM_OR_THUMB
RealRegUse reg;
#endif
ExSet *values = NULL;
ExSet *values2 = NULL;
ExSet *valuesToStore;
ExSet *e1, *e2;
Exprn *node = NULL;
int32 op = c->op;
VRegInt r1 = c->r1, r2 = c->r2, r3 = c->r3, r4 = c->r4;
int32 atmp;
bool isload = NO,
isvolatile = NO,
maybelocalcse = YES,
sideeffectfree_prev = sideeffectfree;
int32 nvals = 0, valno = 0;
currenticode = c;
if (debugging(DEBUG_CSE) && CSEDebugLevel(1)) {
cc_msg("%6d:", c - blkcode_(block));
print_jopcode(c);
}
e1 = NULL; e2 = NULL; node = NULL;
/*
* Convert all instructions to nodes of the DAG.
* Do copy propagation on the fly.
*/
/*
* Setnotused records information about register which have been written but not
* yet read. This is used in order to find basic blocks which don't
* do anything useful and to find exported registers. If a virtual register is
* written and read in the same basic block, all other reads are assumed to be local.
* This may not be the case for physical registers (eg inline assembler), but we're
* only interested in the set of rexported virtual registers...
* Physical registers are considered global, so any instruction which sets these
* is considered to have side effects (setnotused_insert).
*/
if (reads_r1(op)) { e1 = valueinreg(r1.r); setnotused_delete(r1.r, setnotused); }
if (reads_r2(op)) { e1 = valueinreg(r2.r); setnotused_delete(r2.r, setnotused); }
if (reads_r3(op)) { e2 = valueinreg(r3.r); setnotused_delete(r3.r, setnotused); }
if (reads_r4(op)) { setnotused_delete(r4.r, setnotused); }
if (has_side_effects(c)) {
sideeffectfree = NO;
}
if (loads_r1(op)) {
if (op != J_INIT && op != J_INITF && op != J_INITD) {
setnotused_insert(r1.r, setnotused);
}
}
if (loads_r2(op)) {
setnotused_insert(r2.r, setnotused);
}
if (sets_psr(c)) {
sideeffectfree = NO;
}
switch (op & J_TABLE_BITS) {
case J_SHRK:
case J_SHRR:
if (op & J_SIGNED && !OpIsShifted(op) && OpInSetFn(e1, SignBitClear)) {
c->op = op = op ^ (J_SIGNED | J_UNSIGNED);
OpRewritten(c);
}
break;
#ifdef TARGET_HAS_ROTATE
/* It is probably best to treat ROTATEs like SHIFT. There are hence */
/* 4 of them RO{LR}{RK}, but if TARGET_LACKS_ROL then ROL's are done */
/* with a ROR of 32-n, thus improving current code (for n non-const). */
/* ARM should probably have: TARGET_HAS_ROTATE, TARGET_LACKS_ROL */
/* By the way, unless TARGET_HAS_SCALED_OPS then this code catches */
/* rotates by variables, but not by constants! */
case J_ADDR:
case J_ORRR:
#ifdef TARGET_HAS_SCALED_ADDRESSING
if (OpIsShifted(op)) {
int32 shift = (op & J_SHIFTMASK) >> J_SHIFTPOS;
ExSet *ex;
if ( ( ( !(shift & SHIFT_RIGHT) &&
(ex = ExSet_OpMember(e1, J_SHRK | J_UNSIGNED, 0)) != NULL) ||
( (shift & (SHIFT_RIGHT+SHIFT_ARITH)) == SHIFT_RIGHT &&
(ex = ExSet_OpMember(e1, J_SHLK, J_SIGNbits)) != NULL) ) &&
ExSet_Member(e1_(ex->exprn), e2) &&
(shift & SHIFT_MASK) == (32 - e2k_(ex->exprn)) &&
IsLive(ex->exprn)) {
Icode *ip = &useicode_(exuses_(ex->exprn));
c->op = op = J_RORK;
c->r2 = r2 = ip->r2;
c->r3.i = r3.i = (shift & SHIFT_RIGHT) ? 32 - e2k_(ex->exprn) : e2k_(ex->exprn);
OpRewritten(c);
e1 = e2;
e2 = (ExSet *)DUFF_ADDR;
}
} else
#endif
{
Exprn *shex = ORRR_IsRORR(e1, e2);
if (shex != NULL && IsLive(shex)) {
Icode *ip = &useicode_(exuses_(shex));
e1 = ExprnToSet(e1_(shex));
e2 = ExprnToSet(e2_(shex));
c->op = op = J_RORR;
c->r2 = r2 = ip->r2;
c->r3 = r3 = ip->r3;
OpRewritten(c);
}
}
break;
#endif
case J_ANDR:
{
#ifdef TARGET_HAS_SCALED_ADDRESSING
int32 shift = (op & J_SHIFTMASK) >> J_SHIFTPOS;
if (shift & SHIFT_RIGHT) {
ExSet *c1 = MOVKinSet(e1);
if (c1 != NULL) {
shift &= SHIFT_MASK;
if (just32bits_(e1k_(c1->exprn)) ==
(1L << (32 - shift)) - 1L) {
c->op = op = J_SHRK | J_UNSIGNED;
c->r2 = r3;
c->r3.i = r3.i = shift;
OpRewritten(c);
e1 = e2;
e2 = (ExSet *) DUFF_ADDR;
}
}
} else if (shift == 0)
#endif
{
Exprn *shex = SHRR_IsLogical(e1, e2);
if (shex != NULL && IsLive(shex)) {
Icode *ip = &useicode_(exuses_(shex));
e1 = ExprnToSet(e1_(shex));
e2 = ExprnToSet(e2_(shex));
c->op = op = J_SHRR | J_UNSIGNED;
c->r2 = r2 = ip->r2;
c->r3 = r3 = ip->r3;
OpRewritten(c);
}
}
}
break;
case J_ANDK:
if (r3.i != -1)
{ int32 k = ~r3.i;
int32 lowones = logbase2(k & -k);
if (TopBitsKnownZero(e1, 32 - lowones)) {
c->op = op = J_MOVR;
c->r3 = r3 = r2;
c->r2.r = r2.r = GAP;
OpRewritten(c);
e2 = e1; e1 = NULL;
}
}
break;
}
switch (op & J_TABLE_BITS) {
case J_CALLK:
#ifdef TARGET_HAS_DIVREM_FUNCTION
if ( (Expr *)r3.b == arg1_(sim.divfn)
|| (Expr *)r3.b == arg1_(sim.udivfn))
c->r2.i = r2.i = k_setresultregs_(r2.i, 2);
if ( (Expr *)r3.b == sim.llsdiv || (Expr *)r3.b == sim.llsrdv
|| (Expr *)r3.b == sim.lludiv || (Expr *)r3.b == sim.llurdv)
c->r2.i = r2.i = k_setresultregs_(r2.i, 4);
#endif
case J_CALLR:
if (e2 != NULL) {
/* (won't be if op is J_CALLK) */
ExSet *e = ExSet_OpMember(e2, J_ADCON, 0);
if (e != NULL) {
c->op = op = J_CALLK;
c->r3.b = r3.b = e1b_(e->exprn);
OpRewritten(c);
e2 = NULL;
}
}
case J_OPSYSK: /* @@@ pure OPSYSK */
{ int32 i;
sideeffectfree = NO;
if (op == J_CALLK) {
ExSet *arg[NANYARGREGS==0 ? 1 : NANYARGREGS];
int32 val;
int32 nargs = k_argregs_(r2.i);
DRes dres;
for (i = 0 ; i < nargs; i++) {
VRegnum r = k_argisfp_(r2.i,i) ? R_FA1+i : R_A1+i-k_fltregs_(r2.i);
setnotused_delete(r, setnotused);
arg[i] = valueinreg(r);
}
if (CSE_EvaluableIntValuedCall(r3.ex, r1.r, r2.i, arg, &val)) {
r3.i = val;
r1 = c->r1;
goto ForgeMOVK;
}
#ifdef TARGET_HAS_DIV_10_FUNCTION
if (
#ifndef TARGET_HAS_DIVREM_FUNCTION
r3.ex == arg1_(sim.remfn) ||
r3.ex == arg1_(sim.uremfn) ||
#endif
r3.ex == arg1_(sim.divfn) ||
r3.ex == arg1_(sim.udivfn) ) {
ExSet *v1 = MOVKinSet(arg[0]);
if (v1 != NULL && e1k_(v1->exprn) == 10) {
Icode *a1p = NULL, *a2p = NULL;
Icode *p = c, *base = blkcode_(block);
for (; --p >= base; ) {
if (loads_r1(p->op)) {
if (a1p == NULL && p->r1.r == R_A1) {
a1p = p;
if (a2p != NULL) break;
} else if (a2p == NULL && p->r1.r == R_A1+1) {
a2p = p;
if (a1p != NULL) break;
}
}
}
if (a1p != NULL && a2p != NULL) {
arg[0] = arg[1];
a2p->r1.r = R_A1;
a1p->r1.r = vregister(INTREG);
r2.i = c->r2.i = k_argdesc_(1, 0, 1, 0, 2, r2.i & K_FLAGS);
r3.ex = c->r3.ex =
#ifndef TARGET_HAS_DIVREM_FUNCTION
r3.ex == arg1_(sim.remfn) ? arg1_(sim.rem10fn) :
r3.ex == arg1_(sim.uremfn) ? arg1_(sim.urem10fn) :
#endif
r3.ex == arg1_(sim.divfn) ? arg1_(sim.div10fn) :
arg1_(sim.udiv10fn);
OpRewritten(c);
}
}
}
#endif
if (CSE_EvaluableDoubleValuedCall(r3.ex, r1.r, r2.i, arg, &dres)) {
if (r1.r != R_F0) {
/* The call returns two integer registers. To replace it */
/* it, there must be two preceding instructions which we */
/* can overwrite (as yet, we're not extending the block): */
/* the replacement is ADCONx + two loads. */
Icode *blockstart = blkcode_(block);
Icode *prev1 = c-1,
*prev2;
for (; prev1 > blockstart && prev1->op == J_SETSPENV; prev1--) continue;
prev2 = prev1 - 1;
if (prev2 > blkcode_(block)
&& loads_r1(prev1->op) && prev1->r1.r < nargs
&& ( (loads_r1(prev2->op) && prev2->r1.r < nargs)
|| (prev1->op == J_MOVR
&& loads_r1(prev2->op) && prev2->r1.r == prev1->r3.r))) {
VRegnum res1, res2, r = vregister(ADDRREG);
/* Kill any CSE definitions OR references of the 2 LDRKs */
KillExpr(arg[prev1->r1.r], prev1);
if (prev2->r1.r < nargs)
KillExpr(arg[prev2->r1.r], prev2);
else
KillExpr(arg[prev1->r1.r], prev2);
if (dres.isdouble) {
INIT_IC(*prev2, J_ADCOND);
prev2->r3.f = CSE_NewDCon(&dres.val.d);
} else {
INIT_IC(*prev2, J_ADCONLL);
prev2->r3.i64 = CSE_NewLLCon(&dres.val.i);
}
/* Unfortunately, we can't do the following (though in */
/* principle we should) because a load will have killed */
/* an earlier instance of the same load in the list */
/* (for performance reasons). The only effect is that */
/* we won't be able to optimise away a redundant store. */
#if 0
while (storeaccesses != NULL
&& (sa_ic_(storeaccesses) == prev1
|| sa_ic_(storeaccesses) == prev2))
storeaccesses = StoreAccessList_DiscardOne(storeaccesses);
#endif
prev2->r1.r = r;
if (c+2 < limit
&& reads_r1(c[1].op) && c[1].r1.r == r1.r
&& reads_r1(c[2].op) && c[2].r1.r == r1.r+1) {
res1 = vregister(INTREG); res2 = vregister(INTREG);
c[1].r1.r = res1;
c[2].r1.r = res2;
} else {
res1 = r1.r; res2 = r1.r+1;
}
INIT_IC(*prev1, J_LDRK+J_ALIGN4);
prev1->r1.r = res1;
prev1->r2.r = r;
prev1->r3.i = 0;
INIT_IC(*c, J_LDRK+J_ALIGN4);
c->r1.r = res2;
c->r2.r = r;
c->r3.i = 4;
/* Now rescan the 3 inserted instructions */
c -= 3;
continue;
} else {
/* We can't replace the call by its value, but we do */
/* know what that value is, and must remember it in */
/* order to be able to fold it as an operand of further */
/* expressions. */
Exprn *base = (dres.isdouble)
? find_exprn(J_ADCOND, (Exprn *)CSE_NewDCon(&dres.val.d), 0, NULL, U_NOTREF+U_NOTDEF2)
: find_exprn(J_ADCONLL, (Exprn *)CSE_NewLLCon(&dres.val.i), 0, NULL, U_NOTREF+U_NOTDEF2);
Exprn *r0ex = locload_(find_memloc(loctype(J_LDRK), base, 0, J_LDRK+J_ALIGN4, 0));
Exprn *r1ex = locload_(find_memloc(loctype(J_LDRK), base, 4, J_LDRK+J_ALIGN4, 0));
cseset_insert(exid_(r0ex), liveexprns, NULL);
cseset_insert(exid_(r1ex), liveexprns, NULL);
values = ExprnToSet(r0ex);
values2 = ExprnToSet(r1ex);
maybelocalcse = NO;
}
break;
} else {
r3.f = CSE_NewDCon(&dres.val.d);
goto ForgeMOVDK;
}
}
if ((r2.i & K_PURE) &&
#ifdef TARGET_FP_ARGS_IN_FP_REGS
/* @@@ the 2 here is a bit dubious */
k_intregs_(r2.i)+2*k_fltregs_(r2.i) == k_argwords_(r2.i)
#else
k_argregs_(r2.i) == k_argwords_(r2.i)
#endif
) {
/* It is not clear to AM that we need vregsort below, the reg suffices! */
{ int32 nres = k_resultregs_(r2.i);
/* We need a better way of handling the divide + remainder functions */
if (nres > 1) {
if (r1.r == R_A1+1 && nres == 2) {
/* Call is of a function returning two distinct results */
/* - only the second is used here. (div+rem fn, this */
/* is use of rem) */
values = FindRes2CallSet(r3.b, vregsort(r1.r), r2.i, arg, c);
valno = r1.r-R_A1;
} else
/* either the div case of the above, or a function */
/* returning a single result in multiple registers. */
/* k_resultregs can't distinguish. */
if (r3.ex == arg1_(sim.div10fn) || r3.ex == arg1_(sim.udiv10fn)
|| r3.ex == arg1_(sim.divfn) || r3.ex == arg1_(sim.udivfn))
values = FindCallSet(r3.b, vregsort(r1.r), r2.i, arg);
else {
values = Find2ResCallSet(&values2, r3.b, vregsort(r1.r), r2.i, arg, c);
nvals = 1;
valno = r1.r-R_A1;
}
} else {
values = FindCallSet(r3.b, vregsort(r1.r), r2.i, arg);
}
}
} else {
corruptmem();
}
} else {
corruptmem();
}
callcount++;
}
if (op == J_CALLK &&
!(var_cc_private_flags & 32L) &&
returnsheapptr(bindsym_(r3.b)))
node = heapptr;
break;
case J_ADCON:
node = find_unaryb(op, r3.b, 0);
if (r3.b != datasegment
&& ((bindstg_(r3.b) & (bitofstg_(s_static)+u_loctype+b_undef+b_fnconst)) == bitofstg_(s_static))
&& bindaddr_(r3.b) == 0) {
values = ExprnToSet(node);
node = find_unaryb(op, datasegment, 0);
values = ExSet_Insert(node, values);
}
break;
case J_FNCON:
case J_ADCONV:
node = find_unaryb(op, r3.b, 0);
break;
case J_PUSHR:
case J_PUSHF:
case J_PUSHL:
case J_PUSHD:
sideeffectfree = NO;
break;
case J_LDRVK: case J_LDRLVK:
case J_LDRFVK: case J_LDRDVK:
case J_LDRBVK: case J_LDRWVK:
TransformedToLDRVK:
{ Exprn *base = find_unaryb(J_ADCONV, r3.b, U_NOTDEF+U_NOTREF);
isvolatile = load_isvolatile(c,limit);
locs = LocSet_New(NULL,
find_memloc(loctype(op), base, r2.i, j_to_ldrk(op), 0));
values = locs_read(locs, 0, op);
if (debugging(DEBUG_CSE) && CSEDebugLevel(1))
ExSet_Print(values, " LDRVK values\n");
if (op == J_LDRVK) {
StoreAccessList *a = storeaccesses;
for (; a != NULL; a = cdr_(a))
if (a->ic->op != J_NOOP && stores_r1(a->ic->op)) {
if (IsLive(locs->loc->load) && LocSet_Member(locs->loc, a->locs)) {
c->op = op = J_MOVR;
c->r2.r = r2.r = GAP;
c->r3 = r3 = a->ic->r1;
OpRewritten(c);
} else
a = NULL;
break;
}
if (a != NULL) break;
}
}
isload = YES;
break;
case J_STRVK: case J_STRLVK:
case J_STRFVK: case J_STRDVK:
case J_STRBVK: case J_STRWVK:
TransformedToSTRVK:
{ Exprn *base = find_unaryb(J_ADCONV, r3.b, U_NOTDEF+U_NOTREF);
ExSet *val = valueinreg(r1.r);
isvolatile = store_isvolatile(c,limit);
sideeffectfree = NO;
locs = LocSet_New(NULL,
find_memloc(loctype(op), base, r2.i, j_to_ldrk(op), 0));
if (storein_i(r1.r, val, locs, isvolatile)) KillRedundantStore();
if ((op & J_TABLE_BITS) == J_STRBVK && alignof_toplevel_auto >= 4)
if (CanAmalgamateStoreBytes(locs)) {
c->op = op = J_STRVK+J_ALIGN4;
c->r2.i = r2.i = r2.i & ~3;
OpRewritten(c);
goto TransformedToSTRVK;
}
}
break;
case J_LDRR: case J_LDRLR:
case J_LDRFR: case J_LDRDR:
case J_LDRBR: case J_LDRWR:
{ ExSet *c2;
e1 = readreg(r2.r);
e2 = readreg(r3.r);
c2 = MOVKinSet(e2);
if (c2 != NULL) {
int32 a2 = ShiftedVal(op, e1k_(c2->exprn));
if (validdisplacement(op, a2)) {
c->op = op = j_to_ldrk(op) | (op & J_SIGNbits);
c->r3.i = r3.i = a2;
OpRewritten(c);
goto TransformedToLDRK;
}
}
isvolatile = load_isvolatile(c,limit);
locs = rr_locs(op, e1, e2);
if (locs != NULL) values = locs_read(locs, 0, op);
}
isload = YES;
break;
case J_LDRBK:
{ ExSet *p = ExSet_OpMember(e1, J_STRING, 0);
if (p != NULL) {
int32 n = r3.i;
StringSegList *s = e1s_(p->exprn);
for (; s != NULL; n -= s->strseglen, s = s->strsegcdr)
if (n < s->strseglen) {
r3.i = (op & J_SIGNED) ? ((signed char *)s->strsegbase)[n] :
s->strsegbase[n];
goto ForgeMOVK;
}
if (n == 0) {
r3.i = 0;
goto ForgeMOVK;
}
}
}
case J_LDRK: case J_LDRLK:
case J_LDRFK: case J_LDRDK:
case J_LDRWK:
e1 = readreg(r2.r);
TransformedToLDRK:
{ ExSet *p = e1;
AdconRec ad;
J_OPCODE adcon = AdconInSet(p, &ad);
if (adcon == J_ADCONV) {
c->op = op = J_addvk(op);
c->r2.i = r2.i = r3.i + ad.k;
c->r3.b = r3.b = ad.base;
OpRewritten(c);
goto TransformedToLDRVK;
} else if (adcon == J_ADCON+J_BASEALIGN4 && (ad.k & 3) == 0)
c->op = op |= J_BASEALIGN4;
isvolatile = load_isvolatile(c,limit);
locs = NULL;
for (; p != NULL; p = cdr_(p)) {
Location *loc =
find_memloc(loctype(op), p->exprn, r3.i, j_to_ldrk(op), LOC_REALBASE);
if (loc != NULL) locs = LocSet_New(locs, loc);
}
}
if (locs != NULL) values = locs_read(locs, 0, op);
isload = YES;
break;
case J_STRR: case J_STRLR:
case J_STRFR: case J_STRDR:
case J_STRBR: case J_STRWR:
{ ExSet *c2;
sideeffectfree = NO;
valuesToStore = valueinreg(r1.r);
e1 = readreg(r2.r);
e2 = readreg(r3.r);
c2 = MOVKinSet(e2);
if (c2 != NULL) {
int32 a2 = ShiftedVal(op, e1k_(c2->exprn));
if (validdisplacement(op, a2)) {
c->op = op = J_LDtoST(j_to_ldrk(op));
c->r3.i = r3.i = a2;
OpRewritten(c);
goto TransformedToSTRK;
}
}
isvolatile = store_isvolatile(c,limit);
locs = rr_locs(op, e1, e2);
if (locs != NULL && storein_i(r1.r, valuesToStore, locs, isvolatile))
KillRedundantStore();
}
break;
case J_STRK: case J_STRLK:
case J_STRFK: case J_STRDK:
case J_STRBK: case J_STRWK:
sideeffectfree = NO;
valuesToStore = valueinreg(r1.r);
e1 = readreg(r2.r);
TransformedToSTRK:
{ AdconRec ad;
J_OPCODE adcon = AdconInSet(e1, &ad);
if (adcon == J_ADCONV) {
op = c->op = J_addvk(op);
r2.r = c->r2.r = r3.i + ad.k;
r3.b = c->r3.b = ad.base;
OpRewritten(c);
e1 = valuesToStore;
goto TransformedToSTRVK;
} else if (adcon == J_ADCON+J_BASEALIGN4 && (ad.k & 3) == 0)
c->op = op |= J_BASEALIGN4;
isvolatile = store_isvolatile(c,limit);
{ LocSet *locs = NULL;
if (storeink(r1.r, valuesToStore, loctype(op), r3.i, j_to_ldrk(op), e1, isvolatile, &locs))
KillRedundantStore();
if ((op & J_TABLE_BITS) == J_STRBK && (op & J_BASEALIGN4))
if (CanAmalgamateStoreBytes(locs)) {
c->op = op = J_STRK+J_ALIGN4+J_BASEALIGN4;
c->r3.i = r3.i = r3.i & ~3;
OpRewritten(c);
goto TransformedToSTRK;
}
}
}
break;
case J_LDRV1: case J_LDRLV1: case J_LDRFV1: case J_LDRDV1:
break;
case J_LDRV: case J_LDRLV: case J_LDRFV: case J_LDRDV:
isvolatile = load_isvolatile(c,limit);
locs = LocSet_New(NULL, find_varloc(r3.b, j_to_ldrk(op), 0));
values = locs_read(locs, 0, op);
isload = YES;
break;
case J_STRV: case J_STRLV: case J_STRFV: case J_STRDV:
isvolatile = store_isvolatile(c,limit);
sideeffectfree = NO;
locs = LocSet_New(NULL, find_varloc(r3.b, j_to_ldrk(op), 0));
if (storein_i(r1.r, e1, locs, isvolatile))
KillRedundantStore();
break;
ForgeMOVR:
e2 = ExSet_Copy(e1); e1 = NULL;
c->op = op = J_MOVR;
c->r3.r = r3.r = r2.r;
c->r2.r = r2.r = GAP;
OpRewritten(c);
case J_MOVR:
#ifdef never
>> if (EvalUnary(op, &atmp, e2))
>> { r3.i = atmp;
>> goto ForgeMOVK;
>> }
#endif
if (isany_realreg_(r3.r) && e2 == NULL) {
node = find_loadr(r3.r, U_NOTDEF2+U_NOTREF);
if (istop) {
/* handle the MOVR virtreg, realreg jopcodes present at function entry
to initialise argument binders (really, these ought to be STRVs)
*/
BindList *bl = argument_bindlist;
Binder *thisarg = NULL;
if (currentfunction.structresult != NULL
&& r1.r == bindxx_(currentfunction.structresult)) {
/* A structure result pointer is guaranteed non-NULL */
/* (this is important in C++ if there's an inlined copy */
/* constructor: we avoid a test and allocation call) */
thisarg = currentfunction.structresult;
node = find_unaryk(J_NEK, 0, U_NOTDEF2+U_NOTREF);
} else
for (; bl != NULL; bl = cdr_(bl))
if (r1.r == bindxx_(bl->bindlistcar)) {
thisarg = bl->bindlistcar;
break;
}
if (thisarg != NULL) { /* j_to_ldrk(J_LDRK) */
Location *loc = find_varloc(thisarg, J_LDRK|J_ALIGN4, 0);
if (storein(GAP, loc, ExprnToSet(node), NO))
KillRedundantStore();
}
}
break;
} else if (isany_realreg_(r1.r)) {
ExSet *e = ExSet_OpMember(e2, CSE_LOADR, 0);
if (e != NULL && exloadr_(e->exprn) == r1.r) {
r3.r = c->r3.r = r1.r;
OpRewritten(c);
values = e2;
break;
}
}
case J_MOVFR: case J_MOVDR:
if (e2 != NULL) {
values = e2;
ExSet_Map(e2, AddUse, NULL);
}
break;
#ifdef TARGET_HAS_BLOCKMOVE
/* AM: In the following 'n' is a multiple of alignof_struct. However, */
/* it may be desirable to know whether the front-end can guarantee */
/* that a MOVC of (say) 12 can is word-aligned if alignof_struct=1. */
/* Future direction: use J_SHIFTMASK for this? */
case J_CLRC: /* CLRC dest, -, n */
e1 = NULL;
case J_MOVC: /* MOVC dest, source, n */
/* These have implications for value propagation, and for
elimination of unwanted stores.
Also, they may (depending on target) destroy some registers.
Because this is in flux, there are no written rules.
*/
e2 = valueinreg(r1.r);
{ ExSet *e;
int32 offset = 0;
int32 load = J_LDRK | (op & J_ALIGNMENT);
sideeffectfree = NO;
for (e = e2; e != NULL; e = cdr_(e))
if (AdconBaseK(e->exprn, &offset) != NULL)
break;
if (e == NULL) {
corruptmem();
} else {
if (r3.i <= 32 && (r3.i & 3) == 0) {
ExSet *vals[8];
int32 i;
for (i = r3.i>>2; --i >= 0; ) {
LocSet *locs = NULL;
ExSet *p;
vals[i] = NULL;
for (p = e1; p != NULL; p = cdr_(p)) {
Location *loc =
find_memloc(LOC_(MEM_I), p->exprn, 4*i, load, LOC_REALBASE);
if (loc != NULL) {
locs = LocSet_New(locs, loc);
EnsureOldStore(loc, 0);
}
}
if (locs != NULL) vals[i] = locs_read(locs, U_NOTREF+U_NOTDEF2, load);
for (; locs != NULL; locs = cdr_(locs)) {
StoreAccessList *a = storeaccesses;
for (; a != NULL; a = cdr_(a)) {
LocSet *slocs = a->locs;
for (; slocs != NULL; slocs = cdr_(slocs))
if (possiblealias(locs->loc, slocs->loc)) {
a->needed = YES;
break;
}
}
}
}
{ bool redundant = YES;
for (i = r3.i>>2; --i >= 0; )
if (!storeink(GAP, vals[i], LOC_(MEM_I), 4*i, load, e2, NO, &locs))
redundant = NO;
if (redundant) KillRedundantStore();
}
} else {
corruptlocswithbase(e->exprn, r3.i);
}
}
{ StoreAccessList *a = storeaccesses;
for (; a != NULL; a = cdr_(a)) {
LocSet *locs = a->locs;
for (; locs != NULL; locs = cdr_(locs)) {
Location *loc = locs->loc;
if (!(loctype_(loc) & LOC_anyVAR)) {
int32 off = locoff_(loc);
if (ExSet_Member(locbase_(loc), e1) &&
0 <= off && off < r3.i) {
a->needed = YES;
break;
}
}
}
}
}
}
node = NULL;
break;
#endif
case J_SETSPENV:
#ifdef NOT_YET
/* Not yet convinced by the worth of this */
{ int32 nb = length((List *)r3.bl) - length((List *)r2.bl);
if (nb < 0) {
/* Leaving a scope: all stores to stack objects going out of */
/* scope (which haven't been used) can be killed. This is */
/* mainly useful for address-taken things (others regalloc can */
/* kill, maybe after structure splitting). Structure arguments */
/* for evaluated functions are the prime case to catch. */
BindList *bl = r2.bl;
LocSet *kills = NULL;
for (; ++nb <= 0; bl = cdr_(bl)) {
Location *loc = find_varloc(bl->bindlistcar, j_to_ldrk(J_LDRV), LOC_PEEK);
StoreAccessList *sa;
Exprn *base;
if (loc != NULL && IsLive(locload_(loc)))
kills = LocSet_New(kills, loc);
base = find_unaryb(J_ADCONV, bl->bindlistcar, U_PEEK);
if (base != NULL)
for (sa = storeaccesses; sa != NULL; sa = cdr_(sa)) {
LocSet *locs = sa_locs_(sa);
for (; locs != NULL; locs = cdr_(locs)) {
loc = ls_loc_(locs);
if (!(loctype_(loc) & LOC_anyVAR)
&& locbase_(loc) == base
&& IsLive(locload_(loc))
&& !LocSet_Member(loc, kills))
kills = LocSet_New(kills, loc);
}
}
}
for (; kills != NULL; kills = LocSet_DiscardOne(kills))
KillOldUnusedStore(ls_loc_(kills), 0);
}
}
#endif
case J_SETSPGOTO:
setsplist = (SetSPList*)CSEList3((IPtr)setsplist,
(IPtr)cse_currentblock,
(IPtr)currenticode);
case J_ENTER:
case J_INIT: case J_INITF: case J_INITD:
case J_INFOLINE: case J_INFOSCOPE: case J_INFOBODY:
case J_COUNT:
case J_WORD:
case J_ORG:
sideeffectfree = NO;
node = NULL;
break;
case J_THUNKTABLE:
case J_CASEBRANCH:
sideeffectfree = NO;
node = NULL;
cmp_r2vals_(&cmpk) = e1;
break;
case J_CMPFK:
{ ExSet *c1 = MOVFKinSet(e1);
int r;
if (c1 != NULL && CSE_Compare_F(&r, &e1f_(c1->exprn)->floatbin.fb, &r3.f->floatbin.fb)) {
RemoveComparison(r, 0, block);
break;
}
}
e2 = ExprnToSet((Exprn *)CSE_CanonicalFPConst(r3.f));
goto CmpF;
case J_CMPDK:
{ ExSet *c1 = MOVDKinSet(e1);
int r;
if (c1 != NULL && CSE_Compare_D(&r, e1f_(c1->exprn), r3.f)) {
RemoveComparison(r, 0, block);
break;
}
}
e2 = ExprnToSet((Exprn *)CSE_CanonicalFPConst(r3.f));
goto CmpF;
case J_CMPFR:
{ ExSet *c1 = MOVFKinSet(e1);
ExSet *c2 = MOVFKinSet(e2);
int r;
if (c1 != NULL && c2 != NULL &&
CSE_Compare_F(&r, &e1f_(c1->exprn)->floatbin.fb, &e1f_(c2->exprn)->floatbin.fb)) {
RemoveComparison(r, 0, block);
break;
}
}
goto CmpF;
case J_CMPDR:
{ ExSet *c1 = MOVDKinSet(e1);
ExSet *c2 = MOVDKinSet(e2);
int r;
if (c1 != NULL && c2 != NULL &&
CSE_Compare_D(&r, e1f_(c1->exprn), e1f_(c2->exprn))) {
RemoveComparison(r, 0, block);
break;
}
}
CmpF: if (e1 != NULL && e2 != NULL) {
bool taken;
cmp_mask_(&cmpk) = op & CSE_COMPARE_MASK;
cmp_ex_(&cmpk) = FindRRSet(op & ~CSE_COMPARE_MASK, e1, e2, U_NOTDEF+U_NOTREF);
cmp_r2vals_(&cmpk) = NULL;
if (ComparisonValueKnown(&taken, &cmpk, comparevalues)) {
RemoveComparison1(taken, block);
break;
}
#ifdef TARGET_ALLOWS_COMPARE_CSES
values = FindRRSet(op & ~CSE_COMPARE_MASK, e1, e2, 0);
ExSet_Map(values, AddCompare, NULL);
blk_cmp_(block) = ExSet_Copy(values);
#endif
}
break;
#ifdef RANGECHECK_SUPPORTED
case J_CHKLR: case J_CHKUR:
{ ExSet *c2 = MOVKinSet(e2);
if (c2 == NULL) {
values = FindRRSet(op, e1, e2, 0);
break;
}
r3.i = ShiftedVal(op, e1k_(c2->exprn));
}
/* and fall through */
case J_CHKLK: case J_CHKUK:
{ ExSet *c1 = MOVKinSet(e1);
if (c1 != NULL) {
int32 index = e1k_(c1->exprn);
int32 baseop = op & J_TABLE_BITS;
if ((baseop == J_CHKLK || baseop == J_CHKLR) ? (index >= r3.i) :
(index <= r3.i))
goto KillOp;
}
}
values = FindRKSet(op, e1, r3.i, 0);
break;
case J_CHKNEK:
{ ExSet *c1 = MOVKinSet(e1);
if (c1 != NULL && e1k_(c1->exprn) != r3.i)
goto KillOp;
}
values = FindRKSet(op, e1, r3.i, 0);
break;
KillOp:
op = c->op = J_NOOP;
OpRewritten(c);
node = NULL;
break;
case J_CHKNEFR:
case J_CHKNEDR:
break;
#endif
case J_CMPR:
if (e1 == NULL || e2 == NULL)
break;
{ ExSet *c2 = MOVKinSet(e2);
int32 cond = op & (Q_MASK & ~Q_UBIT);
int32 n1 = 0, n2 = 0;
bool taken;
if (c2 == NULL) {
if ((c2 = MOVKinSet(e1)) != NULL) {
#ifdef TARGET_HAS_SCALED_ADDRESSING
if ((cond == Q_EQ || cond == Q_NE) &&
ShiftedOutBitsKnownZero(op, e2)) {
n1 = e1k_(c2->exprn);
n2 = ShiftedVal(op ^ (SHIFT_RIGHT << J_SHIFTPOS), n1);
if (ShiftedVal(op, n2) != n1) {
RemoveComparison(0, 1, block);
break;
} else {
e1 = e2;
r2.r = c->r2.r = r3.r;
goto ConvertToCMPK;
}
}
#endif
if (!OpIsShifted(op) && (cond & ~Q_UBIT) != Q_UKN && cond != Q_UNDEF) {
op = Q_swap(op);
blkflags_(block) = flags = Q_swap(flags);
n2 = e1k_(c2->exprn);
e1 = e2;
r2.r = c->r2.r = r3.r;
goto ConvertToCMPK;
}
} else if (!OpIsShifted(op) && ExSetsOverlap(e1, e2)) {
RemoveComparison(0, 0, block);
break;
} else if (!OpIsShifted(op) && (cond == Q_EQ || cond == Q_NE || !(op & Q_UBIT)) &
ExprIsExprPlusK(e1, e2, &n1, &n2)) {
/* Comparison for equality are completely safe.
Signed comparisons for order are arguably OK because of the
undefinedness of signed overflow.
*/
RemoveComparison(n1, n2, block);
break;
}
cmp_mask_(&cmpk) = op & CSE_COMPARE_MASK;
cmp_ex_(&cmpk) = FindRRSet(op & ~CSE_COMPARE_MASK, e1, e2, U_NOTDEF+U_NOTREF);
cmp_r2vals_(&cmpk) = NULL;
if (ComparisonValueKnown(&taken, &cmpk, comparevalues)) {
RemoveComparison1(taken, block);
break;
}
#ifdef TARGET_ALLOWS_COMPARE_CSES
values = FindRRSet(op & ~CSE_COMPARE_MASK, e1, e2, 0);
ExSet_Map(values, AddCompare, NULL);
blk_cmp_(block) = ExSet_Copy(values);
#endif
break;
} else {
ExSet *c1 = MOVKinSet(e1);
n2 = ShiftedVal(op, e1k_(c2->exprn));
if (c1 != NULL) {
RemoveComparison(e1k_(c1->exprn), n2, block);
break;
}
}
ConvertToCMPK:
op = c->op = J_RTOK(UnshiftedOp(op));
r3.i = c->r3.i = n2;
OpRewritten(c);
}
/* and the second arg. constant, first not case falls through */
case J_CMPK:
{ ExSet *c1 = MOVKinSet(e1);
int32 mask = op & (Q_MASK & ~Q_UBIT);
AdconRec ad;
cmp_mask_(&cmpk) = op & CSE_COMPARE_MASK;
cmp_r2_(&cmpk) = r2.r;
cmp_r2vals_(&cmpk) = e1;
cmp_m_(&cmpk) = r3.i;
cmp_ex_(&cmpk) = NULL;
if (c1 != NULL) {
RemoveComparison(e1k_(c1->exprn), r3.i, block);
} else if ( (mask == Q_EQ || mask == Q_NE)
&&
( /* Special for CFront's demented constructor invocation */
(r3.i == 0 && AdconInSet(e1, &ad) != 0 && !(bindstg_(ad.base) & bitofstg_(s_weak)))
|| ( (c1 = ExSet_OpMember(e1, J_NEK, 0)) != NULL && e1k_(c1->exprn) == r3.i) ) )
RemoveComparison(1, 0, block);
else if ((mask == Q_LT || mask == Q_GE) &&
r3.i == 0 && TopBitsKnownZero(e1, 1))
RemoveComparison(1, 0, block);
else {
bool taken;
if (sideeffectfree_prev && Q_RealMask(op & Q_MASK)
&& setnotused == NULL && !(flags & BLKREXPORTED))
MaybeKillBranchToBlock(block, &cmpk);
cmp_ex_(&cmpk) = FindRKSet(op & ~CSE_COMPARE_MASK, e1, r3.i, U_NOTDEF+U_NOTREF);
if (ComparisonValueKnown(&taken, &cmpk, comparevalues)) {
RemoveComparison1(taken, block);
break;
}
if (!immed_cmp(r3.i)) {
op = J_MOVK;
node = find_movk(r3.i, 0);
break;
}
#ifdef TARGET_ALLOWS_COMPARE_CSES
if (e1 != NULL) {
values = FindRKSet(op & ~CSE_COMPARE_MASK, e1, r3.i, 0);
ExSet_Map(values, AddCompare, NULL);
blk_cmp_(block) = ExSet_Copy(values);
}
#endif
}
}
break;
case J_USE: case J_USEF: case J_USED:
case J_VSTORE:
/* I think I have to assume that this directly follows a load
* or store. I can't get from the register to the store location
* in the case of stores, if the value being stored was known.
*/
sideeffectfree = NO;
if (storeaccesses->ic == c-1) {
LocSet *locs = storeaccesses->locs;
for (; locs != NULL; locs = cdr_(locs)) {
Location *loc = locs->loc;
wantedexprns = deleteloads(loc, wantedexprns);
availableexprns = deleteloads(loc, availableexprns);
liveexprns = deleteloads(loc, liveexprns);
/* All of which is a bit over-enthusiastic. wanted need not be
changed if there's an earlier non-volatile load of the same
location; live and available need not really change at all (the
volatile load/store provides a perfectly good value to a later
non-volatile load). Still, this is only relevant if volatile
and non-volatile accesses to the same location are mixed, and
doing it requires more care to be taken elsewhere.
*/
}
}
node = NULL;
break;
case J_MOVIFR: case J_MOVIDR: case J_MOVFIR:
cse_corrupt_register(r1.r);
node = NULL;
break;
case J_MOVDIR:
if (e2 != NULL)
{ /* General code (at the end of the switch) will deal with setting
r1 & r2.
*/
values2 = newexprnpart(CSE_WORD2, e2);
values = newexprnpart(CSE_WORD1, e2);
break;
}
/* drop through */
case J_MOVLIR:
cse_corrupt_register(r1.r);
cse_corrupt_register(r2.r);
node = NULL;
break;
case J_MOVDFR:
{ ExSet *c1 = MOVDKinSet(e2);
if (c1 != NULL) {
FloatCon *fc = e1f_(c1->exprn);
FloatBin f;
if (fltrep_narrow(&fc->floatbin.db, &f) <= flt_ok) {
r3.f = real_of_string(fc->floatstr ? fc->floatstr : "<expr>", 0);
r3.f->floatlen = ts_float;
r3.f->floatbin.fb = f;
goto ForgeMOVFK;
}
}
}
if (e2 != NULL)
values = FindRKSet(op, e2, 0, 0);
break;
case J_ADDDK: case J_MULDK: case J_SUBDK: case J_DIVDK:
if (e1 != NULL) {
FloatCon *a = CSE_EvalBinary_D(op, e1, r3.f);
if (a != NULL) {
r3.f = a;
goto ForgeMOVDK;
}
values = FindRKSet(op, e1, (IPtr)CSE_CanonicalFPConst(r3.f), 0);
}
break;
case J_ADDDR: case J_MULDR: case J_SUBDR: case J_DIVDR:
if (e1 != NULL && e2 != NULL) {
ExSet *c2 = MOVDKinSet(e2);
if (c2 != NULL) {
FloatCon *a = CSE_EvalBinary_D(J_RTOK(op), e1, e1f_(c2->exprn));
if (a != NULL) {
r3.f = a;
goto ForgeMOVDK;
}
#ifdef TARGET_HAS_FP_LITERALS
/* Maybe rewrite as xxxDK */
#endif
}
values = FindRRSet(op, e1, e2, 0);
}
break;
ForgeMOVDK:
op = c->op = J_MOVDK;
c->r3 = r3;
c->r2.r = GAP;
OpRewritten(c);
case J_ADCOND:
case J_MOVDK:
node = find_exprn(op, (Exprn *)CSE_CanonicalFPConst(r3.f), 0, NULL, 0);
break;
case J_ADCONLL:
node = find_exprn(op, (Exprn *)CSE_CanonicalLLConst(r3.i64), 0, NULL, 0);
break;
case J_MOVFDR:
{ ExSet *c1 = MOVFKinSet(e2);
if (c1 != NULL) {
FloatCon *fc = e1f_(c1->exprn);
r3.f = real_of_string(fc->floatstr ? fc->floatstr : "<expr>", 0);
r3.f->floatlen = ts_double;
fltrep_widen(&fc->floatbin.fb, &r3.f->floatbin.db);
goto ForgeMOVDK;
}
}
if (e2 != NULL)
values = FindRKSet(op, e2, 0, 0);
break;
case J_ADDFK: case J_MULFK: case J_SUBFK: case J_DIVFK:
if (e1 != NULL) {
FloatCon *a = CSE_EvalBinary_F(op, e1, r3.f);
if (a != NULL) {
r3.f = a;
goto ForgeMOVFK;
}
values = FindRKSet(op, e1, (IPtr)CSE_CanonicalFPConst(r3.f), 0);
}
break;
case J_ADDFR: case J_MULFR: case J_SUBFR: case J_DIVFR:
if (e1 != NULL && e2 != NULL) {
ExSet *c2 = MOVFKinSet(e2);
if (c2 != NULL) {
FloatCon *a = CSE_EvalBinary_F(J_RTOK(op), e1, e1f_(c2->exprn));
if (a != NULL) {
r3.f = a;
goto ForgeMOVFK;
}
#ifdef TARGET_HAS_FP_LITERALS
/* Maybe rewrite as xxxFK */
#endif
}
values = FindRRSet(op, e1, e2, 0);
}
break;
ForgeMOVFK:
op = c->op = J_MOVFK;
c->r3 = r3;
c->r2.r = GAP;
OpRewritten(c);
case J_ADCONF:
case J_MOVFK:
node = find_exprn(op, (Exprn *)CSE_CanonicalFPConst(r3.f), 0, NULL, 0);
break;
case J_STRING:
node = find_exprn(op, (Exprn *)r3.s, 0, NULL, 0);
break;
case J_NEGR:
case J_NOTR:
case J_FIXFR: case J_FIXDR:
case J_FIXFRM: case J_FIXDRM:
if (CSE_EvalUnary_I(op, &atmp, e2)) {
r3.i = atmp;
goto ForgeMOVK;
}
goto UnaryR;
case J_NEGFR:
case J_FLTFR:
if (e2 != NULL) {
FloatCon *f = CSE_EvalUnary_F(op, e2);
if (f != NULL) {
r3.f = f;
goto ForgeMOVFK;
}
}
goto UnaryR;
case J_NEGDR:
case J_FLTDR:
if (e2 != NULL) {
FloatCon *f = CSE_EvalUnary_D(op, e2);
if (f != NULL) {
r3.f = f;
goto ForgeMOVDK;
}
}
UnaryR:
if (e2 != NULL)
values = FindRKSet(op, e2, 0, 0);
break;
case J_INLINE1: case J_INLINE1F: case J_INLINE1D:
if (e1 != NULL)
values = FindRKSet(op, e1, r3.i, 0);
break;
case J_EORR:
case J_SUBR:
case J_RSBR:
if (!OpIsShifted(op) && ExSetsOverlap(e1, e2)) {
r3.i = 0;
goto ForgeMOVK;
}
goto BinaryR;
case J_ANDR: case J_ORRR:
if (!OpIsShifted(op) && ExSetsOverlap(e1, e2))
goto ForgeMOVR;
goto BinaryR;
case J_ADDR: case J_MULR:
case J_DIVR: case J_REMR:
case J_SHLR: case J_SHRR: case J_RORR:
BinaryR:
if (e1 != NULL && e2 != NULL) {
ExSet *c2 = MOVKinSet(e2);
if (c2 != NULL) {
int32 a2 = ShiftedVal(op, e1k_(c2->exprn));
ExSet *c1 = MOVKinSet(e1);
if (c1 != NULL &&
CSE_EvalBinary_I(J_RTOK(UnshiftedOp(op)), &atmp, c1->exprn, a2)) {
r3.i = atmp;
goto ForgeMOVK;
} else if (jop_canRTOK(UnshiftedOp(op))) {
op = UnshiftedOp(op);
r3.i = a2;
goto ForgeIOpK;
}
}
if (!OpIsShifted(op) && j_is_commutative(op)) {
ExSet *c1 = MOVKinSet(e1);
if (c1 != NULL && jop_canRTOK(op)) {
e1 = e2;
c->r2.r = r2.r = r3.r;
r3.i = e1k_(c1->exprn);
goto ForgeIOpK;
}
}
values = FindRRSet(op, e1, e2, 0);
}
break;
ForgeIOpK:
c->op = op = J_RTOK(op);
c->r3.i = r3.i;
e2 = NULL;
OpRewritten(c);
/* fall through to handle rewrite as OpK */
case J_ADDK: case J_MULK: case J_ANDK: case J_ORRK: case J_EORK:
case J_SUBK: case J_DIVK: case J_RSBK: case J_REMK:
case J_SHLK: case J_SHRK: case J_RORK:
case J_EXTEND:
if (e1 != NULL) {
ExSet *c1 = MOVKinSet(e1);
if (c1 != NULL && CSE_EvalBinary_I(op, &atmp, c1->exprn, r3.i) ) {
r3.i = atmp;
goto ForgeMOVK;
} else {
switch (op & ~Q_MASK) {
case J_ORRK:
if (r3.i == -1) goto ForgeMOVK;
case J_ADDK: case J_SUBK: case J_EORK:
if (r3.i == 0) goto ForgeMOVR;
break;
case J_MULK: case J_DIVK:
if (r3.i == 1) goto ForgeMOVR;
break;
case J_ANDK:
if (r3.i == 0) goto ForgeMOVK;
if (r3.i == -1) goto ForgeMOVR;
{ int32 x = r3.i + 1;
if ((x & (-x)) == x) {
int32 bits = logbase2(x);
if (BottomBitsKnownZero(e1, bits)) {
r3.i = 0;
goto ForgeMOVK;
} else if (TopBitsKnownZero(e1, 32-bits))
goto ForgeMOVR;
}
x = ~r3.i + 1;
if ((x & (-x)) == x) {
int32 bits = logbase2(x);
if (TopBitsKnownZero(e1, 32-bits)) {
r3.i = 0;
goto ForgeMOVK;
} else if (BottomBitsKnownZero(e1, bits))
goto ForgeMOVR;
}
}
break;
case J_EXTEND:
/* Kill extend applied to an already extended value. Regalloc will
* also handle this (though maybe not if the value has passed
* through a variable), but by turning the load into a plain one.
* Killing the extend is sometimes better, never worse.
*/
if (r3.i == 2) {
if (ExSet_OpMember(e1, J_LDRWK+J_SIGNED, J_ALIGNMENT)
|| ExSet_OpMember(e1, J_LDRWVK+J_SIGNED, J_ALIGNMENT)
|| ExSet_OpMember(e1, J_LDRWR+J_SIGNED, J_ALIGNMENT))
goto ForgeMOVR;
} else if (r3.i == 1) {
if (ExSet_OpMember(e1, J_LDRBK+J_SIGNED, J_ALIGNMENT)
|| ExSet_OpMember(e1, J_LDRBVK+J_SIGNED, J_ALIGNMENT)
|| ExSet_OpMember(e1, J_LDRBR+J_SIGNED, J_ALIGNMENT))
goto ForgeMOVR;
}
}
values = FindRKSet(op, e1, r3.i, 0);
}
}
break;
ForgeMOVK:
op = c->op = J_MOVK;
c->r2.r = GAP;
c->r3.i = r3.i;
OpRewritten(c);
case J_MOVK:
/* J_STRV and TARGET_IS_ALPHA? */
node = find_movk(c->r3.i, immed_op(r3.i, op) &&
( c+1 == limit ||
(c+1)->op == (J_STRV|J_ALIGN4) ||
isany_realreg_(r1.r) ) ? U_NOTDEF2+U_NOTREF
: 0);
break;
#ifdef ARM_INLINE_ASSEMBLER
case J_BL:
corruptmem();
callcount++;
break;
#endif
default:
/* syserr(syserr_scanblock, (long)op); */
node = NULL;
break;
} /* switch */
/* Now update the CSE state */
if (corrupts_psr(c))
cse_corrupt_register(R_PSR);
if (corrupts_r1(c))
cse_corrupt_register(r1.r);
if (corrupts_r2(c))
cse_corrupt_register(r2.r);
#ifdef TARGET_IS_ARM_OR_THUMB
{
/* Mark all registers which are either written or corrupted as 'corrupted'.
* This is because CSE marks all registers with an unknown value as corrupted.
* If defined registers are not included CSE thinks the value didn't change...
* Later the value may be set to a known value using setreg.
*/
RealRegisterUse(c, ®);
map_RealRegSet(®.c_in, corrupt_f, NULL);
map_RealRegSet(®.c_out, corrupt_f, NULL);
map_RealRegSet(®.def, corrupt_f, NULL);
}
#endif
if (values == NULL && node != NULL)
values = ExprnToSet(node);
if (debugging(DEBUG_CSE) && CSEDebugLevel(1))
ExSet_Print(values, "\n");
#ifdef RANGECHECK_SUPPORTED
if (j_is_check(op) && values != NULL) {
if (!ExSet_Map(values, ExprnWasntLive, &node)) {
c->op = J_NOOP;
if (debugging(DEBUG_CSE) && CSEDebugLevel(1))
cc_msg("-- local CSE reference [%ld] -> NOOP\n", exid_(node));
} else {
ExSet_Map(values, SetExWasLive, NULL);
}
} else
#endif
/* J_MOVDIR sets r1 (and this causes setreg(r1,NULL,YES) below), but */
/* the previous PUSHD/POP/POP sequence didn't. Hence next line's hack. */
/* Without the hack K_PURE fn calls don't get CSE'd. */
if (loads_r1(op)) {
/* what I really want to say here is try for a local cse only if nothing
in values suggests it's not sensible
*/
WTLRec wtlrec;
wtlrec.op = op; wtlrec.locs = locs;
wtlrec.r1 = r1.r; wtlrec.isload = isload;
if ( !isvolatile &&
maybelocalcse &&
values != NULL &&
!register_movep(op) &&
(node = ExSet_Some(values, WorthTryingLocalCSE, &wtlrec)) != NULL ) {
if (exop_(node) == J_RESULT2) {
Exprn *e1 = e1_(node);
if (cseset_member(exid_(e1), availableexprns))
isload = isload & !cse_AddLocalCSE(e1, 1, 0, block);
} else if (exop_(node) != CSE_WORD1 && exop_(node) != CSE_WORD2) {
if (cseset_member(exid_(node), availableexprns))
isload = isload & !cse_AddLocalCSE(node, valno, nvals, block);
}
/* If addlocalcse returned NO, maybe we should think about
patching the load (if isload). Or maybe we should do it
anyway, since the CSE might later be discarded. If we don't,
the CSE had better not be discarded! (or a believed to be
redundant store of the value used here may be killed).
*/
}
if (isload && locs != NULL)
add_store_access(locs);
setreg(r1.r, values, YES);
}
if (loads_r2(op))
setreg(r2.r, values2, YES);
else if (values2 != NULL) {
if (op == J_CALLK)
setreg(r1.r+1, values2, YES);
else
syserr("cse_scanblock values2");
}
#ifdef TARGET_ALLOWS_COMPARE_CSES
if (alterscc(c))
cseset_insert(CCLOC, killedlocations, NULL);
#endif
}
if (!(flags & BLK2EXIT) && is_exit_label(exit)) {
/* We may kill all unused stores to local objects. regalloc will do
better with non-address-taken binders, but not with address-taken
ones or local structs.
*/
StoreAccessList *a;
for (a = storeaccesses; a != NULL; a = cdr_(a)) {
Icode *ic = a->ic;
if (stores_r1(ic->op)) {
Location *loc;
LocType type = MaxLocType(a->locs, &loc);
if (type & LOC_anyVAR) {
if (IsLive(loc->load) &&
(bindstg_(locbind_(loc)) &
(bitofstg_(s_auto) | b_globalregvar))
== bitofstg_(s_auto))
KillOldUnusedStore(loc, 0);
} else {
LocSet *locs = a->locs;
for (; locs != NULL; locs = cdr_(locs))
if (exop_(locbase_(loc)) == J_ADCONV) {
if (IsLive(loc->load))
KillOldUnusedStore(loc, 0);
break;
}
}
}
}
}
if (blklength_(block) > 0 && c[-1].op == J_MOVK
&& !is_exit_label(exit) && !(blkflags_(block) & BLK2EXIT)) {
BlockHead *bdest = exit->block;
if (blkflags_(bdest) & BLK2EXIT) {
int32 destlen = blklength_(bdest);
Icode const *const destic = blkcode_(bdest);
if (0 < destlen && (destic[destlen - 1].op & ~Q_MASK) == J_CMPK) {
Icode const *ic = destic;
VRegnum prevr1 = c[-1].r1.r;
int32 i = 0;
bool matches = YES;
--destlen; /* look at all but last */
for (; i < destlen; ++i, ++ic) {
if (ic->op == J_SETSPENV)
continue;
if (!(ic->op == J_MOVR && ic->r3.r == prevr1)
&& !((ic->op == J_ANDK || ic->op == J_EXTEND)
&& ic->r2.r == prevr1)) {
matches = NO;
break;
}
prevr1 = ic->r1.r;
}
if (matches && ic->r2.r == prevr1) {
LabelNumber *newl = nextlabel();
BlockHead *newb = (BlockHead *)BindAlloc(sizeof(BlockHead));
if (debugging(DEBUG_CSE))
cc_msg("Cloning block %ld as successor of block %ld\n",
(long)lab_name_(exit), (long)blklabname_(block));
newl->block = newb;
*newb = *bdest;
blklab_(newb) = newl;
blkdown_(newb) = blkdown_(block);
blkup_(newb) = block;
blkup_(blkdown_(block)) = newb; blkdown_(block) = newb;
blkcse_(newb) = CSEBlockHead_New();
blk_dominators_(newb) = cseset_copy(blk_dominators_(bdest));
blk_pred_(newb) = NULL;
cse_AddPredecessor(newl, block);
cse_AddPredecessor(blknext_(newb), newb);
cse_AddPredecessor(blknext1_(newb), newb);
KillArc(block, exit);
blknext_(block) = exit = newl;
{ int32 n = blklength_(bdest);
Icode *ic_old = blkcode_(bdest);
Icode *ic_new = (Icode *)BindAlloc(n * sizeof(Icode));
memcpy(ic_new, ic_old, (size_t)n * sizeof(Icode));
blkcode_(newb) = ic_new;
}
}
}
}
}
ExportLocVals(block, &cmpk, sideeffectfree && setnotused == NULL, setnotused);
blk_scanned_(block) = YES;
for (; knownregs != NULL; knownregs = RegValue_DiscardOne(knownregs))
ExSet_Discard(rv_val_(knownregs));
StoreAccessList_Discard(storeaccesses);
storeaccesses = NULL;
#ifdef ENABLE_CSE
if (debugging(DEBUG_CSE) && CSEDebugLevel(1))
cse_printexits(flags, exit, exit1);
#endif
/* Take account of evaluated function calls. Since no calls have been
introduced, we need merely to clear the BLKxCALL bits if appropriate
*/
if (callcount < 1)
blkflags_(block) &= ~(BLKCALL+BLK2CALL);
else if (callcount == 1)
blkflags_(block) &= ~BLK2CALL;
if (setnotused != NULL && !is_exit_label(exit)) {
blkflags_(block) |= BLKREXPORTED;
if (debugging(DEBUG_CSE) || debugging(DEBUG_CG)) {
cc_msg("Block %ld marked RExported: ", (long)blklabname_(block));
cse_printset(setnotused);
cc_msg("\n");
}
}
blk_available_(block) = availableexprns;
blk_wanted_(block) = wantedexprns;
blk_killed_(block) = killedlocations;
}
static void csescan_setup(void)
{
memclr(exprnindex, EXPRNINDEXSIZE * sizeof(Exprn **));
cse_tab = CSENewN(Exprn *, HASHSIZE);
memclr(cse_tab, HASHSIZE * sizeof(Exprn **));
memclr(locindex, LOCINDEXSIZE * sizeof(Location **));
locations = CSENewN(Location *, LOCHASHSIZE);
memclr(locations, LOCHASHSIZE * sizeof(Location **));
cseidsegment = CSEIDSEGSIZE;
heapptr = CSENew(Exprn);
exop_(heapptr) = J_HEAPPTR;
heapptr->nodeid = mknodeid_(0, EX_ALIAS|E_UNARYK);
exuses_(heapptr) = NULL;
exwaslive_(heapptr) = YES;
exleaves_(heapptr) = NULL;
csealiasid = csealiaslimit = 1;
csenonaliasid = 0; csenonaliaslimit = CSEIDSEGSIZE;
locationid = 0;
floatconlist = NULL;
int64conlist = 0;
knownregs = NULL;
loadrs = NULL;
movcbaseid = MOVCLOC; movctargets = NULL;
#ifdef TARGET_ALLOWS_COMPARE_CSES
compares = NULL;
#endif
}
#ifdef EXPERIMENT_PRUNEEXPRNS
/* Temporarily disabled, because it was pruning too much (see comment below) */
static void renumber_cb(int32 id, VoidStar arg)
{
VRegSetP *newp = (VRegSetP *)arg;
int32 newid = exnewid_(exprn_(id));
if (newid != 0) {
bool oldp;
cseset_insert(newid, *newp, &oldp);
}
}
static VRegSetP renumber(VRegSetP set)
{
VRegSetP newset = NULL;
vregset_map(set, renumber_cb, (VoidStar)&newset);
vregset_discard(set);
return newset;
}
static void pruneandrenumberexprns(BlockHead *top)
{
int32 i, j, count = 0;
Exprn *left = NULL;
cseidsegment = CSEIDSEGSIZE;
csealiasid = csealiaslimit = 0;
csenonaliasid = 0; csenonaliaslimit = CSEIDSEGSIZE;
if (debugging(DEBUG_CSE)) cc_msg("\nDiscarding exprns");
for (i = 0; i < EXPRNINDEXSIZE; i++) {
Exprn **p = exprnindex[i];
if (p == NULL) break;
for (j = 0; j < EXPRNSEGSIZE; j++) {
Exprn *ex = p[j];
if (ex != NULL) {
ExprnUse *use = exuses_(ex);
/* if this is activated, only-once subexpressions of more-than-once
expressions will not be considered for lifting out of the whole
function "loop", and so will get loaded twice if the larger
expression is lifted.
*/
if (use == NULL) syserr(syserr_prune);
if (cdr_(use) == NULL && !(flags_(use) & U_LOCALCSE) &&
blknest_(use->block) <= 1) {
if (debugging(DEBUG_CSE)) {
cc_msg(" %ld", exid_(ex));
if ((++count) % 20 == 0) cc_msg("\n");
}
exnewid_(ex) = 0;
} else {
if (exalias_(ex)) {
if (++csealiasid >= csealiaslimit) {
csealiasid = cseidsegment;
csealiaslimit = (cseidsegment += CSEIDSEGSIZE);
}
exnewid_(ex) = csealiasid;
} else {
if (++csenonaliasid >= csenonaliaslimit) {
csenonaliasid = cseidsegment;
csenonaliaslimit = (cseidsegment += CSEIDSEGSIZE);
}
exnewid_(ex) = csenonaliasid;
}
cdr_(ex) = left;
left = ex;
}
}
}
}
if (debugging(DEBUG_CSE)) cc_msg(" [%ld]\n", count);
{ BlockHead *bp;
for (bp = top; bp != NULL; bp = blkdown_(bp)) {
blk_available_(bp) = renumber(blk_available_(bp));
blk_wanted_(bp) = renumber(blk_wanted_(bp));
}
}
for (i = 0 ; i < LOCINDEXSIZE ; i++) {
Location **index = locindex[i];
if (index == 0) break;
for (j = 0 ; j < LOCSEGSIZE ; j++) {
Location *q = index[j];
if (q == 0) break;
q->users = renumber(q->users);
q->aliasusers = renumber(q->aliasusers);
}
}
for (i = 0; i < EXPRNINDEXSIZE; i++) {
Exprn **p = exprnindex[i];
if (p == NULL) break;
for (j = 0; j < EXPRNSEGSIZE; j++) {
p[j] = NULL;
}
}
for (; left != NULL; left = cdr_(left)) {
int32 newid = exnewid_(left);
left->nodeid = mknodeid_(newid, left->nodeid & EX_ALIASandTYPE);
exprn_(newid) = left;
}
}
#endif
static void addkilledexprns(int32 locno, VoidStar arg)
{
Location *loc = loc_(locno);
VRegSetP *s = (VRegSetP *) arg;
cseset_union(*s, loc->aliasusers);
}
void cse_scanblocks(BlockHead *top)
{ /* For each block, record the set of expressions evaluated within it.
* Multiple occurrences of the same expression (with the same value) get
* flattened at this stage.
* Output:
* available the set of expressions evaluated within and reaching the
* end of the block
* wanted the set of expressions evaluated within the block and not
* killed within it (so could be evaluated earlier).
* killed the set of LOCATIONS killed in the block
*/
BlockHead *p;
clock_t t0 = clock();
csescan_setup();
if (debugging(DEBUG_CSE | DEBUG_STORE)) {
cc_msg("CSE available expression scan\n");
}
for (p = top; p != NULL; p = blkdown_(p)) {
if (debugging(DEBUG_CSE) && CSEDebugLevel(1))
cc_msg("L%li\n", (long)blklabname_(p));
cse_scanblock(p);
cseset_discard(liveexprns);
}
{ clock_t now = clock();
if (debugging(DEBUG_CSE | DEBUG_STORE))
cc_msg("%ld Exprns, %ld Locations - %d csecs\n",
(long)(cseidsegment-1), (long)(locationid), now-t0);
t0 = now;
}
#ifdef EXPERIMENT_PRUNEEXPRNS
pruneandrenumberexprns(top);
#endif
{ MOVCTarget *mt;
VRegSetP universe = NULL, callkills = NULL;
int32 ul;
{ int32 i;
for (i = 1 ; i < cseidsegment ; i++)
cseset_insert(i, universe, NULL);
for (i = csealiasid+1 ; i < csealiaslimit ; i++)
cseset_delete(i, universe, NULL);
for (i = csenonaliasid+1 ; i < csenonaliaslimit ; i++)
cseset_delete(i, universe, NULL);
for (i = 0 ; i < LOCINDEXSIZE ; i++) {
Location **index = locindex[i];
int32 j;
if (index == 0) break;
for (j = 0 ; j < LOCSEGSIZE ; j++) {
Location *q = index[j];
if (q == 0) break;
if (ispublic(q))
cseset_union(callkills, q->users);
if (!(loctype_(q) & LOC_anyVAR)) {
Exprn *base = locbase_(q);
for (mt = movctargets; mt != NULL; mt = cdr_(mt))
if (mt->base == base) {
cseset_insert(locid_(q), mt->locswithbase, NULL);
break;
}
}
}
}
}
ul = cseset_size(universe);
for (p = top; p != NULL; p = blkdown_(p)) {
/* Turn the set of killed locations now recorded with each block into a
* set of killed expressions. We couldn't do this earlier, because the
* full set of expressions which have a given location as leaf is available
* only after the first pass.
*/
VRegSetP s = NULL;
bool present;
VRegSetP locs = cseset_delete(CALLLOC, blk_killed_(p), &present);
if (present) s = cseset_copy(callkills);
#ifdef TARGET_ALLOWS_COMPARE_CSES
locs = cseset_delete(CCLOC, blk_killed_(p), &present);
if (present) cseset_union(s, compares);
#endif
for (mt = movctargets; mt != NULL; mt = cdr_(mt)) {
locs = cseset_delete(mt->id, blk_killed_(p), &present);
if (present) cseset_union(locs, mt->locswithbase);
}
cseset_map(locs, addkilledexprns, (VoidStar) &s);
cseset_discard(locs);
if (s != NULL) cseset_union(s, loadrs);
{ int32 n = cseset_size(s);
if (n >= ul/2) {
VRegSetP s1 = cseset_copy(universe);
cseset_difference(s1, s);
if (cseset_size(s1) >= n) {
cseset_discard(s1);
} else {
cseset_discard(s);
s = s1;
blk_killedinverted_(p) = YES;
}
}
blk_killed_(p) = s;
}
}
cseset_discard(universe);
cseset_discard(callkills);
cseset_discard(loadrs);
#ifdef TARGET_ALLOWS_COMPARE_CSES
cseset_discard(compares);
#endif
for (mt = movctargets; mt != NULL; mt = cdr_(mt))
cseset_discard(mt->locswithbase);
}
{ int32 i;
for (i = 0 ; i < LOCINDEXSIZE ; i++) {
Location **index = locindex[i];
int32 j;
if (index == 0) break;
for (j = 0 ; j < LOCSEGSIZE ; j++) {
Location *q = index[j];
if (q == 0) break;
cseset_discard(q->users);
cseset_discard(q->aliasusers);
}
}
}
if (debugging(DEBUG_CSE | DEBUG_STORE)) {
cc_msg("constructed killed(blocks) - %d csecs\n", clock()-t0);
}
}
/* end of mip/csescan.c */
|
stardot/ncc | cfe/simplify.c | <reponame>stardot/ncc<filename>cfe/simplify.c
/*
* simplify.c: tree optimisation phase of C compiler
* Copyright (C) Codemist Ltd, 1988-1992.
* Copyright (C) Acorn Computers Ltd., 1988-1990.
* Copyright 1991-1997 Advanced Risc Machines Limited. All rights reserved
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$ Codemist 13
* Checkin $Date$
* Revising $Author$
*/
#include <setjmp.h>
#include "globals.h"
#include "simplify.h"
#include "sem.h"
#include "bind.h"
#include "aetree.h"
#include "builtin.h"
#include "store.h"
#include "aeops.h"
#include "errors.h"
/* AM nov-88: add code to allow mcrep fns to return a flag if the */
/* object requires double alignment (e.g. some structs) */
/* As a transition this is only enabled if alignof_double > alignof_int. */
/* AM 24-sep-87: created from sem.c, but the idea is soon to put tree */
/* replacement bits of cg.c in here too. */
/* Fix (unreleased) bug in *(int *)&x caused by over-keen optimisation */
/* Re-fix to kill bug in (LDS's) extern int a[]; return *a; */
/* optimise0() is called after parsing an expression (generally by syn.c) */
/* which has been type-checked on the way by sem.c. It does tree-like */
/* optimisations, such as removing casts between objects which have the */
/* same run-time representation (e.g. char* -> int* -> long) */
/* expression optimiser:
* Current aims for optimise():
* 0) Remove s_invisible nodes introduced while parsing for error messages.
* 1) reduce constant operations. Most (e.g. 1+2) is done when
* building tree nodes, however, this is a good place to spot
* (x+1)+2, or (x.a).b. Unfortunately this is not done yet so
* genpointer() in vargen.c and the CG both do similar things with the
* result of optimise(). Also turn x+0 to x soon.
* 2) Transform &*x to x, and &x.a to &x + a.
* 3) Regroup certain arithmetic expressions so as to allow more
* constant folding to occur.
* The resultant tree is normalised to some extent. E.g. & is only
* applied to s_binder's.
*/
/* forward references... */
static Expr *optimisefnap(Expr *);
static jmp_buf optimise0_jb;
/* The following routine fixes LDS's bug (in 1.57) alluded to above. */
/* It is not the final word, since we can clearly sometimes do better */
/* at detecting same pointers, but is intended to keep LDS happy with */
/* 'minimal change to code'. */
static bool same_pointedto_types(Expr *e, Expr *e1)
{ TypeExpr *x = prunetype(typeofexpr(e));
TypeExpr *x1 = prunetype(typeofexpr(e1));
if (x == x1) return 1;
/* Careful not to pass arrays/structs/fns to mcrepofexpr() */
/* (and thence sizeoftype which can issue error messages). */
/* The next line duplicates previous behaviour on t_fnap types. */
if (h0_(x) == t_fnap && h0_(x1) == t_fnap)
return 1;
if (h0_(x) == t_subscript || h0_(x) == t_fnap || isclasstype_(x))
return 0;
if (h0_(x1) == t_subscript || h0_(x1) == t_fnap || isclasstype_(x1))
return 0;
return mcrepofexpr(e) == mcrepofexpr(e1);
}
bool is_same(Expr *a, Expr *b)
/* Expressions are considered the same if they compute the same value */
/* and do not have any side-effects. */
{
AEop op;
for (;;)
{ if ((op = h0_(a)) != h0_(b))
{ AEop opb = h0_(b);
if (isrelational_(op) && isrelational_(opb)
&& integer_constant(arg2_(a)))
{ int32 ka = result2;
if (integer_constant(arg2_(b)))
{ int32 kb = result2;
int32 asort = mcrepofexpr(arg1_(a)) & MCR_SORT_MASK,
bsort = mcrepofexpr(arg1_(a)) & MCR_SORT_MASK;
if (asort == bsort)
switch (op)
{
case s_less:
return (opb == s_lessequal && ka == kb+1
&& (asort == MCR_SORT_UNSIGNED ? ka != 0 : ((ka ^ kb) > 0 || ka == 0)));
case s_lessequal:
return (opb == s_less && kb == ka+1
&& (asort == MCR_SORT_UNSIGNED ? kb != 0 : ((ka ^ kb) > 0 || kb == 0)));
case s_greater:
return (opb == s_greaterequal && kb == ka+1
&& (asort == MCR_SORT_UNSIGNED ? kb != 0 : ((ka ^ kb) > 0 || kb == 0)));
case s_greaterequal:
return (opb == s_greater && ka == kb+1
&& (asort == MCR_SORT_UNSIGNED ? ka != 0 : ((ka ^ kb) > 0 || ka == 0)));
}
}
}
return NO;
}
if (isvolatile_expr(a) || isvolatile_expr(b)) return NO;
switch (op)
{
case s_binder:
return a == b; /* volatile attribute already checked */
case s_integer:
return intval_(a) == intval_(b);
case_s_any_string
case s_floatcon:
return a == b; /* improve? */
case s_dot:
if (exprdotoff_(a) != exprdotoff_(b)) return NO;
a = arg1_(a), b = arg1_(b);
continue;
case s_cast:
/* equivtype is probably too strong on the next line (we should */
/* probably use a more machine-oriented test on types) but, before */
/* changing it to the logical mcrepofexpr()=mcrepofexpr(), note that */
/* casts on empty arrays to pointers can cause mcrepofexpr() to cc_err. */
/* @@@ Then again, perhaps is_same should be elided by cse.c now? */
if (!equivtype(type_(a), type_(b))) return NO;
case s_addrof:
case s_bitnot:
case s_boolnot:
case s_neg:
case s_content:
case s_monplus:
a = arg1_(a);
b = arg1_(b);
continue;
case s_equalequal:
case s_notequal:
case s_times:
case s_plus:
case s_and:
case s_or:
case s_xor:
if (is_same(arg1_(a), arg1_(b)))
{ a = arg2_(a);
b = arg2_(b);
continue;
} else if (is_same(arg2_(a), arg1_(b)))
{ a = arg1_(a);
b = arg2_(b);
continue;
}
return NO;
case s_andand:
case s_oror:
case s_greater:
case s_greaterequal:
case s_less:
case s_lessequal:
case s_comma:
case s_minus:
case s_div:
case s_leftshift:
case s_rem:
case s_rightshift:
if (!is_same(arg1_(a), arg1_(b))) return NO;
a = arg2_(a);
b = arg2_(b);
continue;
case s_cond:
if (!is_same(arg1_(a), arg1_(b))) return NO;
if (!is_same(arg2_(a), arg2_(b))) return NO;
a = arg3_(a);
b = arg3_(b);
continue;
default:
return NO;
}
}
}
static Expr *optimise_cast(Expr *e)
{ Expr *a1 = arg1_(e);
int32 e_mode = mcrepofexpr(e), e_len;
int32 a_mode = mcrepofexpr(a1), a_len;
TypeExpr *destntype = typeofexpr(e);
TypeExpr *sourcetype = typeofexpr(a1);
TypeExpr *te = princtype(typeofexpr(e));
if (h0_(te) == t_content) te = typearg_(te);
if (isfntype(te)) return e; /* leave in casts to fn type */
/* a cast to the same type is ineffectual */
if (e_mode == a_mode &&
!((recursivequalifiers(destntype) | recursivequalifiers(sourcetype))
& bitoftype_(s_volatile)))
return a1;
e_len = e_mode & MCR_SIZE_MASK;
e_mode >>= MCR_SORT_SHIFT;
a_len = a_mode & MCR_SIZE_MASK;
a_mode >>= MCR_SORT_SHIFT;
/* A cast is ineffectual if it does not change the m/c representation. */
if (e_mode < 2 && a_mode < 2) /* cast of integral to integral */
{
if (e_mode == a_mode && e_len > a_len)
return a1; /* vacuous signedness-preserving widening */
/* Things like (int)(unsigned char)x are NOT vacuous, even though cg */
/* will generate no code for them, because (double)(int)(unsigned char)x */
/* (double)(unsigned char)x and (double)(signed char)x are all different.*/
/* Even (unsigned int)(int) has a role: consider:- */
/* double d; (double)(unsigned)(int)d; - what can be elided? Nothing! */
}
if (h0_(a1) == s_cast)
{
/* The inner casts are irrelevant in the following cases: */
/* (float) (double) x */
/* (double) (float) x where x is shorter than int */
/* (char) (short) x (char) (int) x (short) (int) x */
/* So are the corresponding unsigned cases. */
if ( (e_mode < 2 && a_mode < 2 && e_len < a_len)
|| (e_mode == 2 && a_mode == 2
&& (e_len < a_len
|| (mcrepofexpr(arg1_(a1)) & MCR_SIZE_MASK) < 2)))
/* /* Revisit this code to handle short longer than a float's mantissa */
/* (or int shorter, for that matter) */
{
arg1_(e) = arg1_(a1);
}
}
return e;
}
/*
AM: expressions such as structfn().a[i] are odd -- the ANSI spec seems
to be very unclear about whether they illegally require the address
of a function result. To ease implementation all calls to structfn()
are mapped to (let t; t=structfn(),t) but this transformation is
undone if we know where the result is going, e.g. x = structfn().
*/
static SynBindList *new_binders;
static bool Div_SignBitClear(Expr *x, int32 rep) {
/* We don't try too hard here at present: look for just widening of an
unsigned type and positive constants.
*/
if (h0_(x) == s_cast) {
int32 xrep = mcrepofexpr(arg1_(x));
return (xrep >> MCR_SORT_SHIFT) == 1 &&
(xrep & MCR_SIZE_MASK) < (rep & MCR_SIZE_MASK);
} else if (h0_(x) == s_integer)
return intval_(x) > 0;
else
return NO;
}
static Expr *Div_CastToUnsigned(Expr *x, TypeExpr *t) {
/* (signbitclear(x, ..) is true) */
return (h0_(x) == s_cast) ?
mk_expr1(s_cast, t, arg1_(x)) :
mkintconst(t, intval_(x), 0);
}
static Expr *IgnoreSignednessChange(Expr *e) {
int32 e_mode = mcrepofexpr(e);
int32 e_len = e_mode & MCR_SIZE_MASK;
e_mode &= MCR_SORT_MASK;
if (e_mode == MCR_SORT_SIGNED || e_mode == MCR_SORT_UNSIGNED)
while (h0_(e) == s_cast) {
int32 a_mode = mcrepofexpr(arg1_(e));
int32 a_len = a_mode & MCR_SIZE_MASK;
a_mode &= MCR_SORT_MASK;
if (a_len == e_len &&
(a_mode == MCR_SORT_SIGNED || a_mode == MCR_SORT_UNSIGNED))
e = arg1_(e);
else
return e;
}
return e;
}
static Expr *RemovableSignOrZeroExtension(Expr *a, uint32 mask) {
if (h0_(a) == s_and && h0_(arg2_(a)) == s_integer &&
(~intval_(arg2_(a)) & mask) == 0)
return arg1_(a);
a = IgnoreSignednessChange(a);
if (h0_(a) == s_rightshift && h0_(arg2_(a)) == s_integer) {
int32 sl = 0, sr = intval_(arg2_(a));
if ((((unsigned32)-1 >> sr) & mask) == mask) {
a = IgnoreSignednessChange(arg1_(a));
if (h0_(a) == s_leftshift) {
if (h0_(arg2_(a)) != s_integer)
return NULL;
sl = intval_(arg2_(a));
a = arg1_(a);
}
if (sl < sr) {
TypeExpr *t = typeofexpr(a);
return mk_expr2(s_rightshift, t, a, mkintconst(t, sr - sl, 0));
} else if (sl == sr)
return a;
}
}
return NULL;
}
/* Beware highly: optimise currently side-effects the tree.
Moreover, s_invisible and (more serious) nodes for ++, += etc can
share sub-structure. Only binders I believe in the latter case
so that all should be OK. Also the use of recursive use of optimise()
in case s_addrof requires it to be idempotent.
*/
static Expr *EvalBinaryOp(AEop op, TypeExpr *t, Expr *e1, Expr *e2) {
/* e1 and e2 known to be of sort s_integer. This is not a call to mkbinary()
* because that may generate unwanted warnings about overflow. Also, we would
* need to fiddle with the types of constants in pointer expressions to avoid
* incorrect extra scaling.
*/
int32 k1 = intval_(e1),
k2 = intval_(e2);
switch (op) {
case s_times: k1 *= k2; break;
case s_plus: k1 += k2; break;
case s_minus: k1 -= k2; break;
case s_and: k1 &= k2; break;
case s_or: k1 |= k2; break;
case s_xor: k1 ^= k2; break;
default: syserr("EvalBinaryOp %ld", op);
}
return mkintconst(t, k1, 0);
}
static int in_args = 0;
static Expr *optimise1(Expr *e, bool valneeded, bool *pure);
static Expr *optimise1b(Expr *e, Expr *a1, Expr *a2,
bool purea1, bool purea2, bool valneeded);
static Expr *mkb(AEop op, TypeExpr *t, Expr *a1, Expr *a2, bool valneeded) {
Expr *e = mk_expr2(op, t, a1, a2);
if (debugging(DEBUG_AETREE) && syserr_behaviour > 0) {
pr_exproftype("optimise1b: ", e);
}
e = optimise1b(e, a1, a2, NO, NO, valneeded);
if (debugging(DEBUG_AETREE) && syserr_behaviour > 0) {
pr_exproftype("optimise1b= ", e);
}
return e;
}
static bool HasIntegralType(Expr *e)
{ int32 rep = mcrepofexpr(e) & MCR_SORT_MASK;
return rep < MCR_SORT_FLOATING;
}
static Expr *DistributedOp(
AEop op1, AEop op2, TypeExpr *type,
Expr *a1, Expr *a21, Expr *a22, bool valneeded) {
bool pure;
return optimise1(mk_expr2(op1, type, a1, mk_expr2(op2, type, a21, a22)),
valneeded, &pure);
}
static Expr *optimise1b(Expr *e, Expr *a1, Expr *a2,
bool purea1, bool purea2, bool valneeded) {
AEop op = h0_(e);
TypeExpr *te = type_(e);
/* floating point tree optimisations moved here from cfe/sem.c */
/* beware IEEE conformance, in that we optimise X+0.0 to X (NaN/-0). */
if (purea1 && purea2 && HasIntegralType(a1) && h0_(a1) == h0_(a2))
if (((op == s_minus || op == s_plus) && h0_(a1) == s_times)
|| ((op == s_or || op == s_xor) && h0_(a1) == s_and)) {
Expr *a11 = arg1_(a1),
*a21 = arg2_(a1),
*a12 = arg1_(a2),
*a22 = arg2_(a2);
if (is_same(a11, a12))
return DistributedOp(h0_(a1), op, type_(e), a11, a21, a22, valneeded);
else if (is_same(a21, a12))
return DistributedOp(h0_(a1), op, type_(e), a21, a11, a22, valneeded);
else if (is_same(a11, a22))
return DistributedOp(h0_(a1), op, type_(e), a11, a21, a12, valneeded);
else if (is_same(a21, a22))
return DistributedOp(h0_(a1), op, type_(e), a21, a11, a12, valneeded);
}
if (op == s_minus) {
if (is_fpzero(a1)) { h0_(e) = s_neg; arg1_(e) = a2; return e; }
if (is_fpzero(a2)) return a1;
if (is_intzero(a2)) return a1;
if (is_intzero(a1)) return mk_expr1(s_neg, te, a2);
if (purea1 && purea2 && HasIntegralType(e) && is_same(a1, a2))
return mkintconst(te, 0, 0);
if (h0_(a2) == s_neg) {
/* a - -b => a + b */
h0_(e) = s_plus;
a2 = arg1_(a2);
} else
/* should also do -a - b => -(a + b)? */
if (h0_(a2) == s_integer) {
h0_(e) = op = s_plus;
a2 = mkintconst(type_(a2), -intval_(a2), 0);
} else if (h0_(a1) == s_plus && h0_(a2) == s_plus) {
Expr *a12 = arg2_(a1),
*a22 = arg2_(a2);
if (h0_(a12) == s_integer) {
if (h0_(a22) == s_integer) {
/* (a+k) - (b+k1) => (a-b) + (k1-k) */
a1 = mk_expr2(s_minus, te, arg1_(a1), arg1_(a2));
a2 = EvalBinaryOp(s_minus, te, a12, a22);
} else {
/* (a+k) - b => (a-b) + k */
a1 = mk_expr2(s_minus, te, arg1_(a1), a2);
a2 = a12;
}
} else if (h0_(a22) == s_integer) {
/* a - (b+k) => (a-b) + -k */
a1 = mk_expr2(s_minus, te, a1, arg1_(a2));
a2 = mkintconst(te, -intval_(a22), 0);
} else
goto symmetric_done;
h0_(e) = op = s_plus;
} else
goto symmetric_done;
} else if (op == s_div || op == s_rem) {
/* We deliberately avoid doing anything with 0/x here */
/* else a divide by zero could go undetected at runtime*/
/* (we could turn it into (divcheck(x), 0), but */
/* probably to little gain) */
TypeExpr *t = prunetype(te);
int32 rep = mcrepoftype(t);
/* Turn a signed division whose operands are both */
/* known to be positive into an unsigned division */
/* whose result is cast to signed. Rationale: s/w */
/* implementations of unsigned divide are likely to*/
/* be a little faster, and if the divisor is a */
/* constant power of two the improvement is */
/* substantial */
if ((rep & MCR_SORT_MASK) == MCR_SORT_SIGNED &&
Div_SignBitClear(a1, rep) &&
Div_SignBitClear(a2, rep) &&
h0_(t) == s_typespec) {
TypeExpr *t1 = primtype_(typespecmap_(t) | bitoftype_(s_unsigned));
bool dummy;
a1 = Div_CastToUnsigned(a1, t1);
a2 = Div_CastToUnsigned(a2, t1);
return optimise1(mk_expr1(s_cast,
t,
mk_expr2(op, t1, a1, a2)),
valneeded,
&dummy);
}
if (op == s_div && h0_(a2) == s_integer) {
if (h0_(a1) == s_div && h0_(arg2_(a1)) == s_integer) {
/* (a/k)/k1 => a/(k*k1) */
a2 = EvalBinaryOp(s_times, te, arg2_(a1), a2);
a1 = arg1_(a1);
}
if (intval_(a2) == 1) return a1;
if (intval_(a2) == -1 &&
(rep & MCR_SORT_MASK) == MCR_SORT_SIGNED) {
return mkunary(s_neg, a1);
}
}
goto symmetric_done;
}
/* N.B. symmetric things only until symmetric_done... */
if (h0_(a1) == s_integer || h0_(a1) == s_floatcon)
{ Expr *w = a1; /* move any const to arg2 */
a1 = a2; /* note both can't be consts. */
a2 = w;
}
if (h0_(a2) == s_integer && h0_(a1) == s_cond
&& (h0_(arg2_(a1)) == s_integer || h0_(arg3_(a1)) == s_integer)) {
Expr *newa1, *newa2;
if (h0_(arg2_(a1)) == s_integer)
newa1 = EvalBinaryOp(op, te, arg2_(a1), a2);
else
newa1 = optimise1(mk_expr2(op, type_(a1), arg2_(a1), a2), valneeded, &purea1);
if (h0_(arg3_(a1)) == s_integer)
newa2 = EvalBinaryOp(op, te, arg3_(a1), a2);
else
newa2 = optimise1(mk_expr2(op, type_(a1), arg3_(a1), a2), valneeded, &purea1);
return mk_expr3(s_cond, te, arg1_(a1), newa1, newa2);
}
if (op == s_and)
{ if (is_intzero(a2) && purea1) return mkintconst(te, 0, 0);
if (is_intminusone(a2)) return a1;
if (purea1 && purea2) {
if (is_same(a1, a2))
return a1;
else if (h0_(a2) == s_bitnot) {
if (is_same(a1, arg1_(a2)))
return mkintconst(te, 0, 0);
} else if (h0_(a1) == s_bitnot) {
if (is_same(a2, arg1_(a1)))
return mkintconst(te, 0, 0);
}
}
}
if (op == s_or)
{ if (is_intzero(a2)) return a1;
if (is_intminusone(a2) && purea1) return mkintconst(te, -1, 0);
if (purea1 && purea2) {
if (is_same(a1, a2))
return a1;
else if (h0_(a2) == s_bitnot) {
if (is_same(a1, arg1_(a2)))
return mkintconst(te, -1, 0);
} else if (h0_(a1) == s_bitnot) {
if (is_same(a2, arg1_(a1)))
return mkintconst(te, -1, 0);
}
}
}
if (op == s_xor)
{ if (is_intzero(a2)) return a1;
if (is_intminusone(a2)) {
if (h0_(a1) == s_bitnot)
return arg1_(a1);
else
return mk_expr1(s_bitnot, te, a1);
}
if (purea1 && purea2) {
if (is_same(a1, a2))
return mkintconst(te, 0, 0);
else if (h0_(a2) == s_bitnot) {
if (is_same(a1, arg1_(a2)))
return mkintconst(te, -1, 0);
} else if (h0_(a1) == s_bitnot) {
if (is_same(a2, arg1_(a1)))
return mkintconst(te, -1, 0);
}
}
}
if (op == s_plus)
{ if (is_fpzero(a2)) return a1;
if (is_intzero(a2)) return a1;
}
if (op == s_times)
{ if (is_fpone(a2)) return a1;
if (is_fpminusone(a2))
{ h0_(e) = s_neg; arg1_(e) = a1; return e; }
if (is_intzero(a2) && purea1) return mkintconst(te, 0, 0);
if (is_intone(a2)) return a1;
if (is_intminusone(a2)) return mk_expr1(s_neg, te, a1);
/* -a * -b => a*b */
if (h0_(a1) == s_neg) {
if (h0_(a2) == s_neg)
return mk_expr2(s_times, te, arg1_(a1), arg1_(a2));
else if (h0_(a2) == s_times) {
if (h0_(arg1_(a2)) == s_neg)
return mk_expr2(s_times, te,
arg1_(a1),
mk_expr2(s_times, te, arg1_(arg1_(a2)), arg2_(a2)));
else if (h0_(arg2_(a2)) == s_neg)
return mk_expr2(s_times, te,
arg1_(a1),
mk_expr2(s_times, te, arg1_(a2), arg1_(arg2_(a2))));
}
} else if (h0_(a2) == s_neg && h0_(a1) == s_times) {
if (h0_(arg1_(a1)) == s_neg)
return mk_expr2(s_times, te,
mk_expr2(s_times, te, arg1_(arg1_(a1)), arg2_(a1)),
arg1_(a2));
else if (h0_(arg2_(a1)) == s_neg)
return mk_expr2(s_times, te,
mk_expr2(s_times, te, arg1_(a1), arg1_(arg2_(a1))),
arg1_(a2));
}
}
if (h0_(a1) == op && h0_(arg2_(a1)) == s_integer) {
Expr *k1 = arg2_(a1);
if (h0_(a2) == s_integer) {
/* ((a op n) op m) => a op (n op m) */
a1 = arg1_(a1);
a2 = EvalBinaryOp(op, te, a2, k1);
/* This can convert (e.g.) (a + 1) + (-1) into (a + 0) which does not */
/* get simplified further here. The codegenerator will treat this as */
/* just a, and the seemingly spurious +0 will serve to preserve the */
/* proper type of the expression. */
} else if (h0_(a2) == op && h0_(arg2_(a2)) == s_integer) {
/* ((a op n) op (b op m)) => (a op b) op (m op n)) */
a1 = mkb(op, te, arg1_(a1), arg1_(a2), valneeded);
a2 = EvalBinaryOp(op, te, arg2_(a2), k1);
} else {
a1 = mkb(op, te, arg1_(a1), a2, valneeded);
a2 = k1;
}
}
if (h0_(a2) == op && h0_(arg2_(a2)) == s_integer) {
/* a op (b op n) => (a op b) op n */
a1 = mkb(op, te, a1, arg1_(a2), valneeded);
a2 = arg2_(a2);
}
if (h0_(a2) == s_integer) {
if (op == s_and) {
AEop op2 = h0_(a1);
Expr *a, *a11 = arg1_(a1);
int32 k = intval_(a2);
/* ((a & k1) op b) & k where (~k1 & k) == 0
* => (a op b) & k
* (((a << n) >> n) op b) & k (top n bits of k are 0)
* => (a op b) & k
* (((a << n) >> m) op b) & k (m > n, top m bits of k are 0)
* => ((a >> (m-n)) op b) & k
*
* additionally, for the first case and op == + or -,
* k must be 2^p-2^q. For simplicity, at no great cost,
* we require k = 2^p-1 for all cases.
*/
if ((op2 == s_and || op2 == s_or || op2 == s_xor) &&
(a = RemovableSignOrZeroExtension(a11, k)) != NULL)
arg1_(a1) = a;
else if (op2 == s_plus || op2 == s_minus) {
int32 n = k+1;
if ((n & -n) == n &&
(a = RemovableSignOrZeroExtension(a11, k)) != NULL)
arg1_(a1) = a;
}
/* ((a << n) >> n) & k (top n bits of k are 0)
* => a & k
* ((a << n) >> m) & k (m > n, top m bits of k are 0)
* => (a >> (m-n)) & k
* (the apparent transformation of (a & k) & k1 has already
* been handled above).
*/
else if ((a = RemovableSignOrZeroExtension(a1, k)) != NULL)
a1 = a;
/* (a | k1) & k => (a & k) | (k & k1) */
if (op2 == s_or && h0_(arg2_(a1)) == s_integer) {
Expr *x1 = a1;
a1 = mkb(s_and, type_(x1), arg1_(x1), a2, valneeded);
a2 = EvalBinaryOp(s_and, te, arg2_(x1), a2);
h0_(e) = op = s_or;
}
}
/* (a & ~k) | k gets transformed here to a | k, to cheer up
* a common bitfield-setting case
*/
if (op == s_or &&
h0_(a1) == s_and && h0_(arg2_(a1)) == s_integer &&
intval_(a2) == ~intval_(arg2_(a1)))
a1 = arg1_(a1);
if (op == s_times) {
/* (a << n) * m => a * (m << n)
* if (m << n) doesn't overflow
*/
if (h0_(a1) == s_leftshift && h0_(arg2_(a1)) == s_integer) {
int32 shift = intval_(arg2_(a1));
int32 n1 = intval_(a2), n2 = ((unsigned32)1 << shift);
int32 n3 = n1 * n2;
if ((n1 ^ n3 >= 0) && (n3 / n2 == n1)) {
a1 = arg1_(a1);
a2 = mkintconst(te_int, n3, 0);
}
}
if (h0_(a1) == s_plus && h0_(arg2_(a1)) == s_integer) {
/* (a + m) * n => (a * n) + (m * n) */
Expr *x1 = a1;
a1 = mk_expr2(s_times, type_(x1), arg1_(x1), a2);
a2 = EvalBinaryOp(s_times, te, arg2_(x1), a2);
h0_(e) = op = s_plus;
} else if (h0_(a1) == s_neg) {
/* (- a) * n => - (a * n) */
int32 n = intval_(a2);
if (n < 0)
return mk_expr2(s_times, te, arg1_(a1), mkintconst(te_int, n, 0));
else
return mk_expr1(s_neg, te, mk_expr2(s_times, te, arg1_(a1), a2));
}
}
}
if (op == s_plus) {
/* a + -b => a - b; -a + b => b-a */
if (h0_(a2) == s_neg)
h0_(e) = s_minus, a2 = arg1_(a2);
else if (h0_(a1) == s_neg) {
Expr *t = a2;
h0_(e) = s_minus, a2 = arg1_(a1);
a1 = t;
}
}
if (op == s_or &&
h0_(a1) == s_and && h0_(arg2_(a1)) == s_integer &&
h0_(a2) == s_and && h0_(arg2_(a2)) == s_integer) {
int32 k1 = intval_(arg2_(a1)),
k = intval_(arg2_(a2));
if (is_same(arg1_(a1), arg1_(a2))) {
/* (x & k1) | (x & k) => x & (k1 | k)
* Motivation: clean up expansion of bitfield &= k.
*/
return mkb(s_and, te, arg1_(a1), mkintconst(te, k | k1, 0), valneeded);
} else if (k1 == ~k) {
/* (x & ~k) | ((x op y) & k) => x op (y & k)
* op = or, xor, or
* op = plus or minus and k is the top n bits (some n)
* *not* op = and, which will clear bits outside k.
* Motivation: clean up expansion of bitfield op=.
*/
AEop op2 = h0_(arg1_(a1));
if (op2 == s_and || op2 == s_or || op2 == s_xor ||
op2 == s_plus || op2 == s_minus) {
Expr *t = a1; a1 = a2; a2 = t;
k = k1;
}
op2 = h0_(arg1_(a2));
if (( (op2 == s_and || op2 == s_or || op2 == s_xor) ||
( (op2 == s_plus || op2 == s_minus) &&
k + (k & -k) == 0)
) &&
is_same(arg1_(a1), arg1_(arg1_(a2)))) {
Expr *y = arg2_(arg1_(a2));
TypeExpr *t = type_(a2);
h0_(e) = op2;
a1 = arg1_(a1);
if (op2 == s_and) {
/* for op = and, the replacement is x & ~(~y & k) */
/* (equivalently, x & (y | ~k), but assuming k is */
/* compact and ~k isn't, the former is a better form.*/
if (h0_(y) == s_bitnot)
y = arg1_(y);
else if (h0_(y) == s_leftshift && h0_(arg2_(y)) == s_integer &&
((((int32)1 << intval_(arg2_(y))) - 1) & k) == 0 &&
h0_(IgnoreSignednessChange(arg1_(y))) == s_bitnot) {
Expr *shval = arg2_(y);
y = IgnoreSignednessChange(arg1_(y));
y = mk_expr2(s_leftshift, t, arg1_(y), shval);
} else
y = mk_expr1(s_bitnot, t, y);
a2 = mk_expr1(s_bitnot, t,
mk_expr2(s_and, t, y, arg2_(a2)));
} else
#ifdef TARGET_HAS_SCALED_OPS
/* if y has the form (z << n), change the transformation
* result x op (y & k) to x op ((z & (k >> n)) << n)
* (to allow the shift to be included in op)
*/
if (h0_(y) == s_leftshift && h0_(arg2_(y)) == s_integer)
a2 = mk_expr2(s_leftshift, t,
mk_expr2(s_and, t, arg1_(y),
mkintconst(t, (unsigned32)k >> intval_(arg2_(y)), 0)),
arg2_(y));
else
#endif
if (h0_(y) == s_integer)
a2 = mkintconst(t, k & intval_(y), 0);
else
a2 = mk_expr2(s_and, t, y, arg2_(a2));
}
}
}
symmetric_done:
arg1_(e) = a1;
arg2_(e) = a2;
return e;
}
static int32 checkdotoff(Expr const *e) {
int32 off = exprdotoff_(e);
if (off == OFFSET_UNSET) { syserr("undefined dot offset"); off = 0; }
return off;
}
typedef struct {
AEop op;
Expr *e;
int32 n;
} CompKDesc;
static bool IsCompareK(Expr *e, CompKDesc *kd) {
AEop op = h0_(e);
if (isinequality_(op)) {
int32 n;
if (h0_(arg2_(e)) == s_integer) {
kd->e = arg1_(e);
n = intval_(arg2_(e));
} else if (h0_(arg1_(e)) == s_integer) {
switch (op) {
case s_greater: op = s_less; break;
case s_greaterequal: op = s_lessequal; break;
case s_less: op = s_greater; break;
case s_lessequal: op = s_greaterequal; break;
}
kd->e = arg2_(e);
n = intval_(arg1_(e));
} else
return NO;
if (op == s_greater) {
if ((mcrepofexpr(kd->e) & MCR_SORT_MASK) == MCR_SORT_UNSIGNED) {
if (n == just32bits_(-1))
return NO;
} else {
if (n == 0x7fffffff)
return NO;
}
n++;
op = s_greaterequal;
}
kd->op = op;
kd->n = n;
return YES;
}
return NO;
}
static Expr *OptimiseComparePair(CompKDesc const *k1, CompKDesc const *k2) {
AEop op = s_nothing;
int32 low, high;
if (k1->op == s_greaterequal) {
low = k1->n;
if (k2->op == s_less || k2->op == s_lessequal) {
op = k2->op;
high = k2->n;
}
} else if (k1->op == s_less || k1->op == s_lessequal) {
op = k1->op;
high = k1->n;
if (k2->op == s_greaterequal) {
low = k2->n;
}
}
if (op != s_nothing) {
int32 mcr = mcrepofexpr(k1->e);
if (((mcr & MCR_SORT_MASK) == MCR_SORT_UNSIGNED
&& (uint32)low < (uint32)high)
|| (high - low) > 0) {
Binder *b = gentempbinder(te_uint);
TypeExpr *t = typeofexpr(k1->e);
Expr *a1 = low == 0 ? k1->e :
mk_expr2(s_minus, t, k1->e, mkintconst(t, low, 0));
return mk_exprlet(s_let, te_int, mkSynBindList(0, b),
mk_expr2(s_comma, te_int,
mk_expr1(s_cast, te_void,
mk_expr2(s_assign, te_uint, (Expr *)b,
mk_expr1(s_cast, te_uint, a1))),
mk_expr2(op, te_int, (Expr *)b,
mkintconst(te_uint, high-low, 0))));
}
}
return NULL;
}
static AEop NegateRelop(AEop op) {
switch (op) {
case s_equalequal: return s_notequal;
case s_notequal: return s_equalequal;
case s_greater: return s_lessequal;
case s_less: return s_greaterequal;
case s_greaterequal: return s_less;
case s_lessequal: return s_greater;
default: syserr("NegateRelop");
return s_nothing;
}
}
static Expr *MkBoolNot(Expr *e) {
if (isrelational_(h0_(e)))
return mk_expr2(NegateRelop(h0_(e)), type_(e), arg1_(e), arg2_(e));
else
return mk_expr1(s_boolnot, type_(e), e);
}
static Expr *optimise1(Expr *e, bool valneeded, bool *pure)
{ AEop op = h0_(e);
Expr *e1;
bool purea1, purea2;
*pure = YES;
if (debugging(DEBUG_AETREE) && syserr_behaviour > 0) {
#ifndef NO_RETURN_EXPRESSIONS
if (op != s_return)
#endif
pr_exproftype("optimise1: ", e);
}
switch (op)
{
#ifdef PASCAL /*ECN*/
case s_error:
return lit_zero;
#endif
case s_integer:
case s_int64con:
case s_floatcon:
case_s_any_string
#ifdef EXTENSION_VALOF
case s_valof:
#endif
case s_binder:
{ Binder *b = exb_(e);
/* Get rid of template arg binder */
if (valneeded && is_template_arg_binder(e) && bindconst_(b) != NULL)
e = bindconst_(b);
break;
}
case s_invisible:
e = optimise1(arg2_(e), valneeded, pure);
break;
case s_evalerror:
if (has_template_arg_scope() && arg3_(e) == NULL)
/* silent mode */
;
else
cc_warn((msg_t)arg3_(e), h0_(arg2_(e)));
e = optimise1(arg1_(e), valneeded, pure);
break;
case s_throw:
*pure = NO;
if (arg1_(e) != NULL) arg1_(e) = optimise1(arg1_(e), YES, &purea1);
break;
#ifndef NO_RETURN_EXPRESSIONS /* perhaps soon dropped for C too. */
case s_return:
e = arg1_(e);
if (h0_(e) != s_fnap) { e = optimise1(e, YES, pure); break; }
/* drop through */
#endif
case s_fnap:
*pure = NO;
e = optimisefnap(e);
#ifndef NO_RETURN_EXPRESSIONS
if (op == s_return) break;
#endif
/*
* Does this function return a struct ?. If so carry out a
* transformation from 'fn()' to (let x; x=fn(),x)'.
* Note: Temp binders are allocated in optimise0().
* CPLUSPLUS: beware _ctor/_dtor and temps.
* @@@ LDS 18-Oct-94: Partly fixed... reftemps() lifetimes wrong.
*/
/* The condition following looks weird, but can be explained by
the dualities:
double <-> MCR_SORT_STRUCT
single-word struct <-> int ie ~MCR_SORT_STRUCT
*/
if ((mcrepofexpr(e) & MCR_SORT_MASK) == MCR_SORT_STRUCT)
{ TypeExpr *t = typeofexpr(e);
Binder *gen;
bool usefancytemp = NO;
if (LanguageIsCPlusPlus)
{ TypeExpr *pt = princtype(t);
/* use a fancy C++ temp if this is an object of class type
that needs a ctor or has a dtor */
if (isclasstype_(pt) &&
tagbindbits_(typespectagbind_(pt)) & (TB_NEEDSCTOR|TB_HASDTOR))
usefancytemp = YES;
}
/* Note that this can't happen when optimise0 is called from
* cg, because then all structure-returning functions are on
* the rhs of assignments (assured by the call to optimise0
* before the tree is handed to cg), and for fn calls on the
* rhs of assignments optimise1 isn't called for the fn call,
* just optimisefnap (see below).
* If it could happen, the call to genreftemp / genexprtemp
* below would cause trouble, since the temporaries thus
* created wouldn't be bound.
*/
if (usefancytemp)
gen = (in_args || !valneeded) ? genexprtemp(t) : genreftemp(t);
else
{ gen = gentempbinder(t);
new_binders = mkSynBindList(new_binders, gen);
}
e = mk_expr2(s_assign, t, (Expr*)gen, e);
if (valneeded)
e = mk_expr2(s_comma, t, e, (Expr*)gen);
}
break;
case s_init:
case s_assign:
*pure = NO;
e1 = optimise1(arg1_(e), YES, &purea1);
/* Nastiness here in C++: consider: */
/* class B: virtual A { ...}; */
/* class D:B { ... }; */
/* B f() { ... } */
/* main() { D d; B &b = d; b = f(); } */
/* In general f() will CONSTRUCT a B in its implicit extra arg. */
/* It must also construct vbases/vfns for a B since it does not know */
/* the use the caller will make of it. Hence eliding the b = f() */
/* would corrupt b's and hence d's vbases/vfns. */
/* However, we could remove a 'struct_result = f()' copy ctor. */
/* Use 'isproperclass()' to determine this. */
/* @@@ hmm, for such a b with a vbase, we would have generated a fncall */
/* instead of an assign already (or a partial assign). */
/* Introduced by optimise1 for integer-like structs, but */
/* having no meaning on the lhs of an assignment */
if (h0_(e1) == s_cast) e1 = arg1_(e1);
arg1_(e) = e1;
if (h0_(e1) == s_cond) {
TypeExpr *t1 = typeofexpr(e1);
Binder *gen = gentempbinder(t1);
e = optimise1(
mk_exprlet(s_let, t1, mkSynBindList(0, gen),
mk_expr2(s_comma, t1,
mk_expr1(
s_cast, te_void,
mk_expr2(s_init, t1, (Expr *)gen, arg2_(e))),
mk_expr3(s_cond, t1,
arg1_(e1),
mk_expr2(s_assign, t1, arg2_(e1), (Expr *)gen),
mk_expr2(s_assign, t1, arg3_(e1), (Expr *)gen)))),
YES, &purea1);
break;
}
if (h0_(e1) == s_binder ||
h0_(e1) == s_content ||
h0_(e1) == s_content4)
/* s_dot is now impossible (it's been turned into *(a+k)) */
{ Expr *a2 = arg2_(e);
if (h0_(a2) == s_fnap)
/* Specifically avoid the temp introduction (case s_fnap above) for */
/* struct-returning functions whose result is directly */
/* assigned to a binder or via s_content... */
{ if (h0_(e1) != s_binder && (feature & FEATURE_FUSSY)
&& !returnsstructinregs(arg1_(a2)))
{ /* ...except in strict ANSI mode, if it is */
/* possible that the assignment target may */
/* overlap the source of the value returned by */
/* the called function (when the result is */
/* well-defined) */
arg2_(e) = optimise1(arg2_(e), YES, &purea1);
break;
}
arg2_(e) = optimisefnap(a2);
break;
}
if (h0_(a2) == s_let)
{ Expr *a22 = arg2_(a2);
if (h0_(a22) == s_fnap)
{ arg2_(a2) = optimisefnap(a22);
break;
}
}
}
{ Expr *a2 = optimise1(arg2_(e), YES, &purea1);
if ( !valneeded &&
h0_(a2) == s_cast &&
mcrepofexpr(arg1_(a2)) < MCR_SORT_FLOATING &&
(mcrepofexpr(e1) & MCR_SIZE_MASK) == 1 &&
h0_(e1) != s_binder)
a2 = arg1_(a2);
arg2_(e) = a2;
}
break;
case s_addrof:
e1 = optimise1(arg1_(e), YES, pure);
if (h0_(e1) == s_comma || h0_(e1) == s_let)
{ /* & (a, b) -> (a, & b); & (let x in e) -> (let x in & e) */
e = mk_expr2(h0_(e1), type_(e), arg1_(e1),
optimise1(mk_expr1(s_addrof, type_(e), arg2_(e1)), YES, &purea1));
break;
} else if (h0_(e1) == s_cond)
{ /* &(a ? b: c) -> (a ? &b : &c) */
e = mkcond(arg1_(e1), mkunary(s_addrof, arg2_(e1)),
mkunary(s_addrof, arg3_(e1)));
break;
} else if (h0_(e1) == s_assign || h0_(e1) == s_init)
{ /* & a = b -> (a = b, & a) */
/* @@@ AM: this is wrong for side-effects in 'a'!!!? */
e = mk_expr2(s_comma, type_(e), e1,
optimise1(mk_expr1(s_addrof, type_(e), arg1_(e1)), YES, &purea1));
break;
}
/* The following line fixes a problem that shouldn't occur, as &(cast) */
/* is illegal. However, it can occur because we recover from ++(type *)p */
/* even though ANSI disallow. Either way, a diagnostic has already been */
/* issued (or a warning in -pcc mode) so there seems to be little excuse */
/* for generating a syserr(). Note that it also legitimises &(cast)var; */
/* but not silently. Win some, lose some. */
while (h0_(e1) == s_cast) e1 = arg1_(e1);
arg1_(e) = e1;
if (h0_(e1) == s_content || h0_(e1) == s_content4) { e = arg1_(e1); break; }
if (isstring_(h0_(e1))) {
e = e1; /* cg thinks addr already */
break;
}
if (h0_(e1) == s_dot) syserr("s_dot output from optimise1");
if (h0_(e1) != s_binder && h0_(e1) != s_comma && h0_(e1) != s_int64con
&& h0_(e1) != s_floatcon
&& !istypevar(typeofexpr(e1))
&& !(software_floating_point_enabled && h0_(e1) == s_floatcon)
)
/* Check that we have a binder for &. However, beware we
* might have a structure returning function which will
* get transformed above. Should test for this fully but
* testing for s_comma is probably ok !.
*/
syserr("optimise&(%ld,$s)", (long)h0_(e1), h0_(e1));
/* syserr(syserr_optimise, (long)h0_(e1)); */
break;
case_content:
case s_content4:
case s_content: /* get rid of extra &'s and *'s introduced above */
arg1_(e) = e1 = optimise1(arg1_(e), YES, pure);
if (h0_(e1) == s_addrof &&
/* the next line ensures *(int*)&d -> d only if types match */
same_pointedto_types(e, arg1_(e1)))
{ e = arg1_(e1);
if (valneeded && e && h0_(e) == s_binder
&& bindconst_(exb_(e)) != NULL)
e = bindconst_(exb_(e));
}
break;
case s_dot: /* replace s_dot with s_content */
case s_qualdot: /* always an error or syserr */
e1 = arg1_(e);
if (e1 == NULL)
syserr("optimize1: bad null in dot expr");
if (h0_(e1) == s_binder && bindsym_(exb_(e1)) == NULL)
{ cc_err(simplify_err_illegal_use_of_mem_fn, exb_(arg2_(e)));
longjmp(optimise0_jb, 1);
}
if (op == s_qualdot)
syserr("optimize1: s_qualdot");
/* NB. all s_dot code can be removed from cg. */
if ((mcrepofexpr(e1) & MCR_SORT_MASK) != MCR_SORT_STRUCT)
{ /* Fetching a word from a single-word struct!. */
/* Probably just e (see cg_content_for_dot). */
/* @@@ Check 'volatile'. */
/* Insert cast so types are right (e.g. for cg_fnap). */
/* This code wouldn't work for a byte in a union! */
if (mcrepofexpr(e1) == 0x00000004 && exprdotoff_(e)==0)
{ e = optimise1(mk_expr1(s_cast, type_(e), e1), YES, pure);
break;
}
else
syserr("optimise(dot one word)");
}
else
{ TypeExpr *tp = ptrtotype_(type_(e));
Expr *e2 = mkintconst(te_int, checkdotoff(e), 0);
TypeExpr *te1 = typeofexpr(e1);
AEop op = ((config & CONFIG_STRUCT_PTR_ALIGN)
&& sizeoftypelegal(te1)
&& alignoftype(te1) >= 4) ? s_content4
: s_content;
/* Beware, assumes optimise(s_fnap(struct)) is address takeable!. */
e = mk_expr1(op, type_(e),
mk_expr2(s_plus, tp,
mk_expr1(s_addrof, tp, e1), e2));
}
goto case_content;
case s_dotstar:
e1 = arg1_(e);
if ((mcrepofexpr(e1) & MCR_SORT_MASK) != MCR_SORT_STRUCT)
{ /* Fetching a word from a single-word struct!. */
/* Replace with (e2, e1), i.e. eval e2 for side-effects */
/* and return e1. Implies p->*NULL == p->*(&S::s)!! */
if (mcrepofexpr(e1) == 0x00000004)
{ e = optimise1(
mk_expr2(s_comma, type_(e), arg2_(e), e1),
YES, pure);
break;
}
else
syserr("optimise(dotstar one word)");
}
else
{ TypeExpr *tp = ptrtotype_(type_(e));
Expr *e2 = arg2_(e);
/* follow [ES] suggestion for ptr-to-member rep. */
e2 = mk_expr2(s_minus, typeofexpr(e2), e2, lit_one);
/* Beware, assumes optimise(s_fnap(struct)) is address takeable!. */
e = mk_expr1(s_content, type_(e),
mk_expr2(s_plus, tp,
mk_expr1(s_addrof, tp, e1), e2));
}
goto case_content;
case s_cond:
e1 = e;
arg1_(e) = optimise1(arg1_(e), YES, &purea1);
if (is_intzero(arg3_(e)) && is_intone(arg2_(e))) {
*pure = purea1;
e = arg1_(e);
break;
} else if (is_intzero(arg2_(e)) && is_intone(arg3_(e))) {
*pure = purea1;
e = MkBoolNot(arg1_(e));
break;
}
if ((mcrepofexpr(e) & MCR_SORT_MASK) == MCR_SORT_STRUCT)
{ /* The expression is struct-valued */
TypeExpr *te = type_(e);
TypeExpr *pt = ptrtotype_(te);
type_(e) = pt;
e1 = mk_expr1(s_content, te, e);
arg2_(e) = mk_expr1(s_addrof, pt, arg2_(e));
arg3_(e) = mk_expr1(s_addrof, pt, arg3_(e));
}
arg2_(e) = optimise1(arg2_(e), valneeded, &purea2);
purea1 = purea1 & purea2;
arg3_(e) = optimise1(arg3_(e), valneeded, &purea2);
*pure = purea1 & purea2;
e = e1;
break;
case s_qualified|s_let:
case s_let:
arg2_(e) = optimise1(arg2_(e), valneeded, pure);
break;
case s_cast:
arg1_(e) = optimise1(arg1_(e), valneeded && mcrepofexpr(e) != 0, pure);
e = optimise_cast(e);
break;
case s_and:
case s_times:
case s_plus:
case s_or:
case s_xor: /* these are both commutative and associative */
case s_minus: /* this isn't -- see goto below */
case s_div: /* nor this */
case s_rem:
{ Expr *a1 = optimise1(arg1_(e), YES, &purea1);
Expr *a2 = optimise1(arg2_(e), YES, &purea2);
e = optimise1b(e, a1, a2, purea1, purea2, valneeded);
*pure = purea1 & purea2;
}
break;
#ifdef RANGECHECK_SUPPORTED
case s_rangecheck:
if (arg3_(e) != NULL) arg3_(e) = optimise1(arg3_(e), YES, pure);
/* drop through */
case s_checknot:
arg1_(e) = optimise1(arg1_(e), YES, &purea1);
if (arg2_(e) != NULL) arg2_(e) = optimise1(arg2_(e), YES, pure);
*pure = *pure & purea1;
break;
#endif
case s_greater:
case s_less:
case s_greaterequal:
case s_lessequal:
{ Expr *a1 = optimise1(arg1_(e), YES, &purea1);
Expr *a2 = optimise1(arg2_(e), YES, &purea2);
*pure = purea1 & purea2;
if (*pure && HasIntegralType(a1) && is_same(a1, a2)) {
e = mkintconst(te_int, op == s_greaterequal || op == s_lessequal, 0);
break;
}
arg1_(e) = a1;
arg2_(e) = a2;
break;
}
case s_equalequal:
case s_notequal:
{ Expr *a1 = optimise1(arg1_(e), YES, &purea1);
Expr *a2 = optimise1(arg2_(e), YES, &purea2);
*pure = purea1 & purea2;
if (h0_(a1) == s_integer) { Expr *w = a1; a1 = a2; a2 = w; }
if (*pure && HasIntegralType(a1) && is_same(a1, a2)) {
e = mkintconst(te_int, op == s_equalequal, 0);
break;
} else if (h0_(a2) == s_integer) {
int32 n = intval_(a2);
if (isrelational_(h0_(a1))
|| h0_(a1) == s_andand
|| h0_(a1) == s_oror) {
if ((op == s_notequal) != (n == 1))
e = a1;
else
e = MkBoolNot(a1);
break;
}
if (h0_(a1) == s_cond
&& (h0_(arg2_(a1)) == s_integer || h0_(arg3_(a1)) == s_integer)) {
Expr *newa1, *newa2;
if (h0_(arg2_(a1)) == s_integer)
newa1 = mkintconst(type_(e), (intval_(arg2_(a1)) == n) ^ (op != s_equalequal), 0);
else
newa1 = optimise1(mk_expr2(op, type_(e), arg2_(a1), a2), valneeded, &purea1);
if (h0_(arg2_(a1)) == s_integer)
newa2 = mkintconst(type_(e), (intval_(arg3_(a1)) == n) ^ (op != s_equalequal), 0);
else
newa2 = optimise1(mk_expr2(op, type_(e), arg3_(a1), a2), valneeded, &purea2);
e = optimise1(mk_expr3(s_cond, type_(e), arg1_(a1), newa1, newa2), valneeded, &purea1);
break;
}
/* in comparison of signed char for (in)equality against positive
* constant <= SCHAR_MAX, cast the signed char to unsigned char
* (in the belief that zero extension is cheaper than sign extn).
*/
if (h0_(a1) != s_binder &&
n >= 0 && n < (1 << 7)) {
TypeExpr *t = prunetype(typeofexpr(a1));
if (h0_(t) == s_typespec) {
SET_BITMAP tm = typespecmap_(t);
if ((tm & (bitoftype_(s_char)|bitoftype_(s_signed))) ==
(bitoftype_(s_char)|bitoftype_(s_signed))) {
tm ^= (bitoftype_(s_signed)|bitoftype_(s_unsigned));
a1 = optimise1(mkcast(s_cast, a1, primtype_(tm)), YES, &purea1);
}
}
}
if (h0_(a1) == s_or && h0_(arg2_(a1)) == s_integer) {
int32 n1 = intval_(arg2_(a1));
if (purea1 && (n & n1) != n1) {
e = mkintconst(te_int, op == s_notequal, 0);
break;
}
} else if (h0_(a1) == s_and && h0_(arg2_(a1)) == s_integer) {
int32 n1 = intval_(arg2_(a1));
if (purea1 && (n & n1) != n) {
e = mkintconst(te_int, op == s_notequal, 0);
break;
}
}
if (n == 0) {
a1 = IgnoreSignednessChange(a1);
if (h0_(a1) == s_and && h0_(arg2_(a1)) == s_integer) {
/* This is meant to improve comparisons of (unsigned) bitfields
* against 0. It turns the lh operand from (a shift n1) & n2
* into a & (n2 opposite_shift n1).
*/
int32 n1 = intval_(arg2_(a1));
Expr *a11 = IgnoreSignednessChange(arg1_(a1));
if (h0_(a11) == s_rightshift &&
h0_(arg2_(a11)) == s_integer) {
int32 n2 = intval_(arg2_(a11));
if ((n1 & ((int32)-1 << (32 - n2))) == 0 ||
(mcrepofexpr(a11) & MCR_SORT_MASK) == MCR_SORT_UNSIGNED) {
arg1_(a1) = arg1_(a11);
arg2_(a1) = mkintconst(type_(a1), n1 << n2, 0);
}
} else if (h0_(a11) == s_leftshift &&
h0_(arg2_(a11)) == s_integer) {
int32 n2 = intval_(arg2_(a11));
arg1_(a1) = arg1_(a11);
arg2_(a1) = mkintconst(type_(a1), just32bits_((unsigned32)n1) >> n2, 0);
}
} else if (h0_(a1) == s_rightshift && h0_(arg2_(a1)) == s_integer) {
/* This is meant to improve comparisons of (signed) bitfields
* against 0. It turns the lh operand from (a << n2) >> n1
* (n1 >= n2) into (a & k) where k has n2 ms and (n1-n2) ls 0s
* and other bits 1.
*/
int32 n1 = intval_(arg2_(a1)),
n2 = 0,
mask = 0;
Expr *a11 = IgnoreSignednessChange(arg1_(a1));
if (h0_(a11) == s_leftshift && h0_(arg2_(a11)) == s_integer) {
n2 = intval_(arg2_(a11));
a11 = arg1_(a11);
mask = (int32)1 << (32-n2);
/* relying on x<<0 having previously been transformed into x */
/* to avoid an undefined << 32. */
}
if (n2 <= n1) {
mask -= (int32)1 << (n1-n2);
h0_(a1) = s_and;
arg1_(a1) = a11;
arg2_(a1) = mkintconst(type_(a1), mask, 0);
}
}
}
}
arg1_(e) = a1;
arg2_(e) = a2;
break;
}
case s_leftshift:
case s_rightshift:
/* bitfield op=.
* turns ((((x >> n) op y) & m) << n)
* [already partly optimised from (((((x >> n) & m) op y) & m) << n)]
* into (x op (y << n)) & (m << n)
* (also ((((x >> n) & m) | y) << n), y constant, (y & m) == y, a
* mistaken transformation of the above)
*/
{ AEop op2 = s_nothing;
Expr *e0l = optimise1(arg1_(e), YES, &purea1);
Expr *e0r = optimise1(arg2_(e), YES, &purea2);
Expr *e1l = NULL, *e1r = NULL, *e2l = NULL, *e3r;
*pure = purea1 & purea2;
/* convert (a op n) op m -> a op (n+m) */
if (h0_(e0l) == op && h0_(e0r) == s_integer && h0_(arg2_(e0l)) == s_integer)
{
intval_(e0r) += intval_(arg2_(e0l));
e0l = arg1_(e) = arg1_(e0l);
}
if (op == s_leftshift && h0_(e0r) == s_integer) {
if (h0_(e0l) == s_and && h0_(e1r = arg2_(e0l)) == s_integer) {
e1l = arg1_(e0l);
op2 = h0_(e1l);
if (op2 == s_plus || op2 == s_minus ||
op2 == s_and || op2 == s_or || op2 == s_xor)
e2l = arg1_(e1l);
else if (op2 == s_rightshift)
e2l = e1l;
} else if (h0_(e0l) == s_or && h0_(e1r = arg2_(e0l)) == s_integer &&
h0_(e1l = arg1_(e0l)) == s_and && h0_(arg2_(e1l)) == s_integer &&
(intval_(e1r) & intval_(arg2_(e1l))) == intval_(e1r)) {
op2 = s_or;
e2l = arg1_(e1l);
e1r = arg2_(e1l);
e1l = e0l;
}
if (e2l != NULL &&
h0_(e2l) == s_rightshift &&
h0_((e3r = arg2_(e2l))) == s_integer) {
int32 nr = intval_(e3r),
nl = intval_(e0r);
Expr *a21l = arg2_(e1l),
*a1 = op2 == s_rightshift ?
arg1_(e2l) :
mk_expr2(
op2, type_(e0l),
arg1_(e2l),
h0_(a21l) == s_integer ?
mkintconst(type_(e0l), intval_(a21l) << nr, 0) :
mk_expr2(s_leftshift, type_(e0l), a21l, e3r)),
*a2 = mkintconst(type_(e0l), intval_(e1r) << nr, 0);
if (nl == nr) {
h0_(e) = s_and;
e0l = a1;
e0r = a2;
} else if (nl > nr) {
e0l = mk_expr2(s_and, type_(e0l), a1, a2);
e0r = mkintconst(type_(e0r), nl - nr, 0);
}
}
}
arg1_(e) = e0l;
arg2_(e) = e0r;
break;
}
case s_plusplus: case s_minusminus:
case s_displace:
*pure = NO;
arg1_(e) = optimise1(arg1_(e), YES, &purea1);
arg2_(e) = optimise1(arg2_(e), YES, &purea1);
break;
case s_andand:
{ Expr *newe = NULL,
*a1 = optimise1(arg1_(e), YES, &purea1),
*a2 = optimise1(arg2_(e), YES, &purea2);
*pure = purea1 & purea2;
if (purea1 && purea2) {
CompKDesc k1, k2;
bool comp1 = IsCompareK(a1, &k1),
comp2 = IsCompareK(a2, &k2);
if (comp1 && comp2 && is_same(k1.e, k2.e)) {
newe = OptimiseComparePair(&k1, &k2);
if (newe != NULL) {
e = newe;
break;
}
} else if (comp1 && h0_(a2) == s_andand) {
if (IsCompareK(arg1_(a2), &k2) && is_same(k1.e, k2.e)) {
newe = OptimiseComparePair(&k1, &k2);
if (newe != NULL) {
a1 = newe;
a2 = arg2_(a2);
}
} else if (IsCompareK(arg2_(a2), &k2) && is_same(k1.e, k2.e)) {
newe = OptimiseComparePair(&k1, &k2);
if (newe != NULL) {
a1 = newe;
a2 = arg1_(a2);
}
}
} else if (comp2 && h0_(a1) == s_andand) {
if (IsCompareK(arg1_(a1), &k1) && is_same(k1.e, k2.e)) {
newe = OptimiseComparePair(&k1, &k2);
if (newe != NULL) {
a1 = arg2_(a1);
a2 = newe;
}
} else if (IsCompareK(arg2_(a1), &k1) && is_same(k1.e, k2.e)) {
newe = OptimiseComparePair(&k1, &k2);
if (newe != NULL) {
a1 = arg1_(a1);
a2 = newe;
}
}
}
}
arg1_(e) = a1; arg2_(e) = a2;
break;
}
case s_bitnot:
case s_neg:
{ Expr *a1 = optimise1(arg1_(e), YES, pure);
if (*pure && HasIntegralType(e)) {
if (h0_(a1) == op) {
e = arg1_(a1);
break;
}
}
arg1_(e) = a1;
break;
}
case s_boolnot:
{ Expr *a1 = optimise1(arg1_(e), YES, pure);
if (isrelational_(h0_(a1)))
e = mk_expr2(NegateRelop(h0_(a1)), type_(e), arg1_(a1), arg2_(a1));
else
arg1_(e) = a1;
break;
}
default:
if (ismonad_(op))
arg1_(e) = optimise1(arg1_(e), YES, pure);
else if (isdiad_(op)) {
arg1_(e) = optimise1(arg1_(e), YES, &purea1);
arg2_(e) = optimise1(arg2_(e), YES, &purea2);
*pure = purea1 & purea2;
} else syserr(syserr_optimise1, (long)op);
break;
}
if (debugging(DEBUG_AETREE) && syserr_behaviour > 0) {
#ifndef NO_RETURN_EXPRESSIONS
if (op != s_return)
#endif
pr_exproftype("optimise1= ", e);
}
return e;
}
static SynBindList *optimiselist(ExprList *x)
{ SynBindList *letbindings = NULL;
bool dummy;
for (; x != 0; x = cdr_(x)) {
Expr *e = exprcar_(x);
if (h0_(e) == s_fnap) {
/* Avoid introduction of the temporary done by case s_fnap in */
/* optimise1 for structure-returning functions (produces an */
/* unnecessary and hard to remove structure copy). cg will cause the */
/* called function to return its results directly to the argument */
/* place */
e = optimisefnap(e);
} else if (h0_(e) == s_let && h0_(arg2_(e)) == s_fnap) {
arg2_(e) = optimisefnap(arg2_(e));
} else {
if ((mcrepofexpr(e) & MCR_SORT_MASK) == MCR_SORT_STRUCT &&
h0_(e) == s_let && h0_(arg2_(e)) == s_comma) {
SynBindList *bl = exprletbind_(e);
Expr *a2 = arg2_(e);
if (bl->bindlistcdr == NULL &&
(Expr *)bl->bindlistcar == arg2_(a2)) {
letbindings = mkSynBindList(letbindings, bl->bindlistcar);
e = a2;
}
}
in_args++;
e = optimise1(e, YES, &dummy);
in_args--;
}
exprcar_(x) = e;
}
return letbindings;
}
static Expr *optimisefnap(Expr *e) {
SynBindList *b;
bool dummy;
Expr *fn = arg1_(e) = optimise1(arg1_(e), YES, &dummy);
b = optimiselist(exprfnargs_(e));
/* Optimise away some casts for software floating point */
/* (cf optimisecast) */
if (h0_(fn) == s_addrof) {
Expr *fnb = arg1_(fn);
if (h0_(fnb) == s_binder && exprfnargs_(e) != NULL) {
ExprList *args = exprfnargs_(e);
Expr *arg = exprcar_(args);
if (cdr_(args) == NULL
&& h0_(arg) == s_fnap
&& exprfnargs_(arg) != NULL && cdr_(exprfnargs_(arg)) == NULL
&& h0_(arg1_(arg)) == s_addrof
&& h0_(arg1_(arg1_(arg))) == s_binder) {
Expr *fna = arg1_(arg1_(arg));
ExprList *argsa = exprfnargs_(arg);
if (fnb == sim.fnarrow) {
/* in (float)(double), the inner cast is redundant */
if (fna == sim.dwiden)
e = exprcar_(argsa);
else if (fna == sim.llstod)
e = mk1fnap(sim.llstof, argsa);
else if (fna == sim.llutod)
e = mk1fnap(sim.llutof, argsa);
else if (fna == sim.dfloat)
e = mk1fnap(sim.ffloat, argsa);
else if (fna == sim.dfloatu)
e = mk1fnap(sim.ffloatu, argsa);
} else if (fnb == sim.dwiden && h0_(exprcar_(argsa)) == s_cast) {
/* in (double)(float)(int), the cast to float is */
/* redundant if the thing cast to int is short or char */
int32 rep = mcrepofexpr(arg1_(exprcar_(argsa)));
if ((rep & MCR_SORT_MASK) < MCR_SORT_FLOATING
&& (rep & MCR_SIZE_MASK) <= 2) {
if (fna == sim.ffloat)
e = mk1fnap(sim.dfloat, argsa);
else if (fna == sim.ffloatu)
e = mk1fnap(sim.dfloatu, argsa);
}
}
}
}
}
return (b == NULL) ? e : mk_exprlet(s_let, type_(e), b, e);
}
#define U_Read 1
#define U_Write 2
typedef struct BindUseList BindUseList;
struct BindUseList {
BindUseList *cdr;
Binder *b;
int use;
};
/* Very nice, AM had wanted to do something like this for some time! */
static void warnifusage(BindUseList *bu, Binder *b, int flag) {
for (; bu != NULL; bu = cdr_(bu))
if (bu->b == b && (bu->use & flag)) {
if (bu->use & flag & U_Read)
cc_warn(warn_usage_rw, b);
else
cc_warn(warn_usage_ww, b);
return;
}
}
static BindUseList *mergeuselists(BindUseList *b1, BindUseList *b2, BindUseList *oldb) {
if (b1 == oldb)
return b2;
else if (b2 != oldb) {
BindUseList *p = b1, *next;
for (; (next = cdr_(p)) != oldb; p = next) /* nothing */;
cdr_(p) = b2;
}
return b1;
}
static BindUseList *checkvaruse(BindUseList *b, Expr *e)
{
if (debugging(DEBUG_AETREE) && syserr_behaviour > 1)
{ eprintf("checkvaruse "); pr_expr_nl(e);
}
switch (h0_(e)) {
default:
if (h0_(e) > s_binder)
cc_warn(simp_warn_checkvar, h0_(e));
break;
case s_addrof:
if (h0_(arg1_(e)) != s_binder)
b = checkvaruse(b, arg1_(e));
break;
/* Hmm, I'd rather do via isdiad_ ismonad_, possible? */
case s_binder:
warnifusage(b, exb_(e), U_Write);
b = (BindUseList *)syn_list3(b, e, U_Read);
break;
case s_andequal: case s_orequal: case s_xorequal:
case s_timesequal: case s_plusequal: case s_minusequal: case s_divequal:
case s_idivequal: case s_remequal:
case s_leftshiftequal: case s_rightshiftequal:
case s_assign: case s_init:
{ Expr *lhs = arg1_(e);
b = checkvaruse(b, arg2_(e));
if (h0_(lhs) != s_binder)
b = checkvaruse(b, lhs);
else {
warnifusage(b, exb_(lhs), U_Write);
b = (BindUseList *)syn_list3(b, lhs, U_Write);
}
break;
}
case s_plusplus: case s_minusminus:
case s_displace:
{ Expr *a1 = arg1_(e);
if (h0_(a1) != s_binder)
b = checkvaruse(b, a1);
else {
warnifusage(b, exb_(a1), U_Read+U_Write);
b = (BindUseList *)syn_list3(b, a1, U_Write);
}
break;
}
case s_subscript:
case s_equalequal: case s_notequal:
case s_greater: case s_greaterequal: case s_less: case s_lessequal:
case s_plus: case s_minus: case s_times: case s_div:
case s_ptrdiff:
case s_idiv: case s_rem: case s_power:
case s_and: case s_or: case s_xor: case s_leftshift: case s_rightshift:
case s_dotstar:
b = checkvaruse(b, arg2_(e));
/* drop though */
#ifndef NO_RETURN_EXPRESSIONS
case s_return:
#endif
case s_evalerror:
case s_cast:
case s_content4:
case s_content:
case s_monplus: case s_neg: case s_bitnot: case s_boolnot:
case s_dot: case s_qualdot:
case s_ctor: /* a monad protecting a s_comma */
b = checkvaruse(b, arg1_(e));
case_s_any_string
break;
case s_invisible:
b = checkvaruse(b, arg2_(e));
break;
case s_throw:
if (arg1_(e)) b = checkvaruse(b, arg1_(e));
break;
case s_qualified|s_let:
case s_let:
b = checkvaruse(b, arg2_(e));
break;
case s_andand: case s_comma: case s_oror:
{ BindUseList *b1 = checkvaruse(b, arg1_(e));
BindUseList *b2 = checkvaruse(b, arg2_(e));
b = mergeuselists(b1, b2, b);
break;
}
case s_fnap:
{ ExprList *args = exprfnargs_(e);
for (; args != NULL; args = cdr_(args))
b = checkvaruse(b, exprcar_(args));
b = checkvaruse(b, arg1_(e));
break;
}
case s_cond:
{ BindUseList *b1 = checkvaruse(b, arg2_(e));
BindUseList *b2 = checkvaruse(b, arg3_(e));
BindUseList *b3 = checkvaruse(b, arg1_(e));
b = mergeuselists(mergeuselists(b1, b2, b), b3, b);
break;
}
}
if (debugging(DEBUG_AETREE) && syserr_behaviour > 1) {
BindUseList *p;
cc_msg("=>");
for (p = b; p != NULL; p = cdr_(p))
cc_msg(" $b,%s", p->b, (p->use-1)*3+"R\0\0W\0\0RW");
cc_msg("\n");
}
return b;
}
Expr *optimise0(Expr *e)
/* exported - yields 0 if a 'serious' error message has already been
printed (we know this by the s_error at the top of the tree).
The semantic routines *SHOULD* all be strict in s_error.
*/
{ Expr *res;
bool dummy;
if (h0_(e) == s_error) return NULL;
checkvaruse(NULL, e);
new_binders = NULL;
if (setjmp(optimise0_jb) == 0)
res = optimise1(e, YES, &dummy);
else
{ res = NULL;
new_binders = NULL;
}
/*
* If there are any structure returning functions allocate temp binders
* here at the root of the expression tree.
*/
return (new_binders == 0) ? res :
mk_expr2(s_let, typeofexpr(res), (Expr*)new_binders, res);
}
/* The following routine detects when a struct/union has suitable members
that it can be considered an integer and thus be slavable in a register.
A first requirement is that all (union, total for struct) members are
size 4 or less. The total size of 4 has been checked by caller.
However, not all such structs are suitable - consider
struct { short a,b;}. Moreover since C requires that the address of
struct/union first element is the same as the address of the
aggregate this poses problems (and that this problem extends to
non-address-taken structs via assignment, this means that on some
machines we cannot put struct { char c; } in a register.
However, struct { int c:8;} is always OK.
The rule is that every sub-object only contains int/enum/pointer.
Return value is 1 if values of this type are allocatable to registers, 2
if functions returning a value of this type should do so in an integer
register (slightly looser conditions: this also requires that
all subfields be integral and have offset zero, but allows shorter types
than int).
*/
#define integerlikestruct(s) (slaveablestruct(s) == 1)
static int slaveablestruct(TagBinder *b)
{ ClassMember *l;
int okres = 1;
if (!integerlike_enabled) return 0;
for (l = tagbindmems_(b); l != 0; l = memcdr_(l))
{
if (!is_datamember_(l))
{ /* Reject non-static member functions (particularly ctors) */
/* since we can't just copy corresponding objects: consider */
/* e.g. class A { A *p; A() { p = this; }}; */
if (!(bindstg_(l) & (bitofstg_(s_static)|bitofstg_(s_typedef))))
/* need a macro for non-static member fn? */
return 0;
}
#if 0
else if (isbitfield_type(memtype_(l)))
{ /* bits are OK (sem.c turns to int) */
/* @@@ beware PCC mode/C++ char bitfields &c */
}
#endif
else
{ TypeExpr *t = princtype(memtype_(l));
SET_BITMAP m;
switch (h0_(t))
{ default: return 0; /* array not OK */
case t_content: break; /* pointers are OK */
case t_ref: break; /* and so are refs */
case t_fnap: break; /* so are mem fns */
case s_typespec: /* including bitfields */
if (memwoff_(l) != 0) return 0;
m = typespecmap_(t);
if (m & bitoftype_(s_enum))
m = typeofenumcontainer(typespectagbind_(t));
switch (m & -m)
{ default: return 0;
case bitoftype_(s_char):
okres = 2;
break;
case bitoftype_(s_int):
if (m & bitoftype_(s_short)) okres = 2;
break; /* 4 bit int ok */
case bitoftype_(s_double):
if ((m & bitoftype_(s_short))
&& software_floats_enabled)
break;
return 0;
case bitoftype_(s_struct):
case bitoftype_(s_class):
case bitoftype_(s_union):
if (!slaveablestruct(typespectagbind_(t)))
return 0;
break;
}
break;
}
}
}
return okres;
}
static int32 mcrepofexpr1(Expr *e, bool container)
/* keep in step with sizeoftype */
{ TypeExpr *x = prunetype(typeofexpr(e));
SET_BITMAP m;
switch (h0_(x))
{
case t_unknown:
/* treated as void, see below. */
return 0x0000000;
case s_typespec:
m = typespecmap_(x);
switch (m & -m) /* LSB - unsigned/long etc. are higher */
{
case bitoftype_(s_enum):
if (container)
m = typeofenumcontainer(typespectagbind_(x));
goto mcrepofint;
case bitoftype_(s_char):
if ((m & (bitoftype_(s_signed)|bitoftype_(s_unsigned))) == 0)
m |= (feature & FEATURE_SIGNED_CHAR) ?
bitoftype_(s_signed) : bitoftype_(s_unsigned);
/* drop through */
case bitoftype_(s_int):
case bitoftype_(s_bool):
mcrepofint:
{ int32 n = sizeoftype(x);
if (int_islonglong_(m))
return MCR_SORT_STRUCT + n;
return n +
(m & bitoftype_(s_unsigned) ?
m & bitoftype_(s_signed) ? MCR_SORT_PLAIN :
MCR_SORT_UNSIGNED :
MCR_SORT_SIGNED);
}
case bitoftype_(s_double):
{ int32 n = sizeoftype(x);
/* The tests here generate no code if alignof_double==alignof_int. */
return (alignof_double > alignof_int && n == sizeof_double) ?
MCR_SORT_FLOATING + MCR_ALIGN_DOUBLE + n :
MCR_SORT_FLOATING + n;
}
case bitoftype_(s_struct):
case bitoftype_(s_class):
case bitoftype_(s_union):
{ int32 n = sizeoftype(x);
if (n == 4 && integerlikestruct(typespectagbind_(x)))
return MCR_SORT_SIGNED + n;
else
return (alignof_double > alignof_int &&
alignoftype(x) == alignof_double) ?
MCR_SORT_STRUCT + MCR_ALIGN_DOUBLE + n :
MCR_SORT_STRUCT + n;
}
case bitoftype_(s_void):
/*
* BEWARE: Other parts of the compiler use mcrepoftype==0
* as a test for 'void' types.
*/
return 0x0000000;
default: break;
}
/* drop through */
default:
/* case t_fnap: */
syserr(syserr_mcrepofexpr, (long)h0_(x),(long)typespecmap_(x));
case t_ovld:
return MCR_SORT_SIGNED + sizeof_ptr;
case t_subscript:
/* The following checks that restriction that mcrepofexpr() spiritually */
/* should never be applied to array typed expressions. Two exceptions: */
/* s_binder's (for flowgraf.c sizing) and s_strings (optimise removes their */
/* implicit '&'). */
if (h0_(e)!=s_binder && !isstring_(h0_(e)))
syserr(syserr_mcreparray, (long)h0_(e));
if (h0_(e) == s_binder)
{ int32 n = sizeoftype(x);
if (n & ~MCR_SIZE_MASK)
cc_err(simplify_err_outsizearray, exb_(e)),
n = MCR_SIZE_MASK;
return (alignof_double > alignof_int &&
alignoftype(x) == alignof_double) ?
MCR_SORT_STRUCT + MCR_ALIGN_DOUBLE + n :
MCR_SORT_STRUCT + n;
}
/* s_string falls into pointer code */
case t_content:
case t_ref:
return TARGET_ADDRESSES_UNSIGNED ? MCR_SORT_UNSIGNED + sizeof_ptr :
MCR_SORT_SIGNED + sizeof_ptr;
}
}
static int32 mcrepofexpr2(Expr *e, bool container)
{ int32 r;
/* temp. nasty hack for optimise(s_dot/s_dotstar) and cppfe/vargen */
/* solution: make type of datasegment struct-of-size 0x00ffffff? */
r = (e == (Expr *)datasegment || e == (Expr *)constdatasegment)
? MCR_SORT_STRUCT+0 : mcrepofexpr1(e, container);
/* Fake floating point values so that they are thought of as structures. */
if (software_floats_enabled && r == MCR_SORT_FLOATING + 4)
return MCR_SORT_SIGNED + 4;
else if (software_doubles_enabled
&& (r == MCR_SORT_FLOATING + 8 ||
r == MCR_SORT_FLOATING + MCR_ALIGN_DOUBLE + 8))
return MCR_SORT_STRUCT + 8;
return r;
}
int32 mcrepofexpr(Expr *e)
{ return mcrepofexpr2(e, YES);
}
int32 mcrepoftype(TypeExpr *t)
{
/* This returns the machine representation of a type. Done by forgery of */
/* an expression and a call to mcrepofexpr(). */
return mcrepofexpr(mk_expr2(s_invisible, t, 0, 0));
}
bool returnsstructinregs_t(TypeExpr *t) {
/* t is known to be a function type, but not necessarily one returning a */
/* structure value. */
TypeExpr *restype;
t = prunetype(t);
if (h0_(t) != t_fnap)
syserr("non fnap in returnsstructinregs_t");
restype = prunetype(typearg_(t));
if (typefnaux_(t).flags & bitoffnaux_(s_structreg)) {
int32 resultwords = sizeoftype(restype) / MEMCPYQUANTUM;
return (resultwords >= 1 && resultwords <= NARGREGS);
} else {
#ifdef SOFTWARE_FLOATING_POINT_RETURNS_DOUBLES_IN_REGISTERS
if (software_doubles_enabled && isprimtype_(restype, s_double))
return YES;
#endif
if (h0_(restype) == s_typespec && int_islonglong_(typespecmap_(restype)))
return YES;
if (h0_(restype) == s_typespec && (typespecmap_(restype) & CLASSBITS) &&
sizeoftype(restype) <= 4 && slaveablestruct(typespectagbind_(restype)) == 2)
return YES;
return NO;
}
}
bool returnsstructinregs(Expr *fn) {
TypeExpr *t = prunetype(typeofexpr(fn));
if (h0_(t) != s_content) return NO; /* syserr will follow */
t = princtype(typearg_(t));
if (h0_(t) == t_coloncolon)
t = typearg_(t);
return returnsstructinregs_t(t);
}
/* end of simplify.c */
|
stardot/ncc | mip/optproto.h | /*
* mip/optproto.h -- compiler configuration options set at compile time.
* Copyright (C) Acorn Computers Ltd., 1988
* Copyright (C) Codemist Ltd., 1989
* SPDX-Licence-Identifier: Apache-2.0
* Version 1.
*/
/*
* This is a prototype file documenting (some of) the available
* things which might go in target.h or options.h.
* Insert all such flags in here.
*/
#error attempt to compiler optproto.h /* ensure still sane */
#ifndef _options_LOADED
#define _options_LOADED
/*
* Firstly set TARGET_MACHINE and TARGET_SYSTEM. Note that you should
* follow the general line below.
*/
#define TARGET_MACHINE "Wombat-500"
#define TARGET_IS_WOMBAT 1
/*
* Since host.h is #included previously we can simply make the TARGET
* OS depend on host, e.g.
*/
#ifdef COMPILING_ON_UNIX
# define TARGET_SYSTEM "Unix"
# define TARGET_IS_UNIX 1
#else
# define TARGET_SYSTEM "Wombat-OS"
# define TARGET_IS_WOMBAT_OS 1
#endif
/* Now here, or more likely in target.h you specify machine properties */
/* #define TARGET_IS_BIG_ENDIAN 1 -- if your target is big endian... */
/* #define TARGET_IS_LITTLE_ENDIAN 1 -- if your target is little endian */
/* #define TARGET_LACKS_HALFWORD_STORE 1 */
/* Now things defining the desired target representations. */
/* #define alignof_int 4 -- else accept the default set in defaults.h */
/* #define sizeof_int 4 -- else accept the default set in defaults.h */
/* #define alignof_struct 4 -- else accept the default set in defaults.h */
/* #define DRIVER_OPTIONS { "-zps1", NULL } -- e.g. no stack checks */
/*
* Now parameterisations as to facilities of the compiler you wish,
* note that you are unlikely to need to specify many of these.
*/
/* #define EXTENSION_VALOF 1 -- to build a compiler with ACN's extension */
/* #define NO_ASSEMBLER_OUTPUT 1 -- to build a compiler sans ... capability */
/* #define NO_OBJECT_OUTPUT 1 -- to build a compiler sans ... capability */
/* #define NO_LISTING_OUTPUT 1 -- to build a compiler sans ... capability */
/* #define NO_INSTORE_FILES 1 -- to build a compiler sans in-store hdrs */
/* #define NO_DEBUGGER 1 -- to build a compiler sans debugger suppt */
/* #define NO_SELF_CHECKS 1 -- to avoid building checks aimed at itself */
/* #define NO_VERSION_STRINGS 1 -- to avoid module version strings */
#define TARGET_HAS_DIVREM_FUNCTION 1 /* divide function also returns remainder.*/
/* would be in target.h, but is OS- */
/* dependent too. */
/* ARM only things -- specify target register convention variant. */
/* #define APCS_BINDING_A 'X' -- for the X binding of APCS (X = A,U,R,M) */
/* -- else accept the default set in mcdep.c */
/*
* The following rather lengthy set of tests and definitions allows
* various options debugging in the compiler to be selected. Selected
* options can be controlled at run-time from the comand line.
*/
#define ENABLE_ALL 1 /* -- to enable all debugging options */
/* #define ENABLE_LEX 1 -- trace lexer token stream */
/* #define ENABLE_SYN 1 -- hint at parser operation (mostly unused) */
/* #define ENABLE_CG 1 -- trace code generation */
/* #define ENABLE_BIND 1 -- trace generation of binders */
/* #define ENABLE_TYPE 1 -- trace manipulation of type expressions */
/* #define ENABLE_REGS 1 -- debug register allocation */
/* #define ENABLE_OBJ 1 -- debug object-code formatter */
/* #define ENABLE_FNAMES 1 -- to note start of parsing each top-level fn */
/* #define ENABLE_FILES 1 -- trace finding/inclusion of source files */
/* #define ENABLE_LOOP 1 -- debug loop optimisation */
/* #define ENABLE_Q 1 -- debug generation of debugger tables */
/* #define ENABLE_STORE 1 -- report on use of store by code generator */
/* #define ENABLE_2STORE 1 -- debug compiler's storage manager */
/* #define ENABLE_SPILL 1 -- help debug register spilling */
/* #define ENABLE_MAPSTORE 1 -- enable compiler profiling */
/* #define ENABLE_AETREE 1 -- allow abstract syntax tree to be printed */
/* #define ENABLE_PP 1 -- trace pre-processor operation */
/* #define ENABLE_DATA 1 -- trace generation of static/global data */
/* #define ENABLE_CSE 1 -- debug common subexprssion elimination */
/* #define ENABLE_LOCALCG 1 -- debug local code generation (xxxgen) */
/*
* ****** TEMPORARY HACKS ******
*/
/* #define ENABLE_X 1 -- to enable the desperate codetrace feture */
#endif /* _options_LOADED */
/* end of mip/optproto.h */
|
stardot/ncc | arm/mcdpriv.h | /*
* C compiler file mcdpriv.h
* (Private interfaces within machine-dependent back end).
* Copyright (C) Acorn Computers Ltd., 1988
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
#ifndef __mcdpriv_h
#define __mcdpriv_h 1
#include "mcdep.h"
#ifndef JOPCODEDEF_ONLY
#include "codebuf.h"
#endif
#define P_RET 1
#define P_CMPZ 2 /* update PSR flags NZC, not V */
#define P_PRE 4 /* Used for pre-auto-index */
#define P_POST 8 /* Used for post-auto-index */
#define P_LSL 0x10
#define P_ASR 0x20 /* Used to generate register-controlled shifts */
#define P_LSR 0x30
#define P_ROR 0x40
#define P_RSHIFT (P_LSL | P_ASR | P_LSR | P_ROR)
#define SCC_of_PEEP(peep) ((peep) & (P_CMPZ|P_SETCC) ? \
((peep) & P_SETPSR ? F_SCC | F_RD(15) : F_SCC):0) /* change bit no.? */
#define P_BASEALIGNED 0x800
#define P_MS 0x1000
#define P_ADJUSTSP 0x2000
/* These two are used internally to the peepholer to mark a change of */
/* condition for a comparison and its associated branch / condexec */
#define P_UNSIGNEDCOND 0x4000 /* signed changed to unsigned */
#define P_SWAPCOND 0x8000 /* operands swapped */
#define P_SWAPPEDOPS 0x10000
#define P_ZONLY 0x20000 /* Z-flag only needed (in conjunction with P_CMPZ) */
#define P_SETCC 0x40000 /* update PSR flags NZCV */
#define P_SETPSR 0x80000 /* update all PSR flags, including processor mode */
#define P_TRANS 0x100000 /* Translate user mode option - LDRT/STRT */
#define _a_read_r1 0x1
#define _a_read_r2 0x2
#define _a_read_r3 0x4
#define _a_read_r4 0x8
#define _a_set_r1 0x10
#define _a_set_r2 0x20
#define _a_modify_mem 0x40
#define _a_call 0x80
#define _a_regmask_r1 0x100
#define _a_regmask_r3 0x200
#define _a_gap_r1 0x400
#define _a_gap_r2 0x800
#define _a_read_mem 0x1000
#define _a_uses_stack 0x2000
extern struct JopTable a_joptable[];
#ifdef DEFINE_A_JOPTABLE
# if defined ENABLE_CG || defined ENABLE_REGS || defined ENABLE_CSE
# define a_with_bits(n, b) {n, b},
# else
# define a_with_bits(n, b) { b },
# endif
struct JopTable a_joptable[] = {
#else
# define a_with_bits(n, b)
#endif
#define a_attributes(op) (a_joptable[(op-J_LAST_JOPCODE-1) & J_TABLE_BITS].bits)
#define J_POPMB (J_LAST_JOPCODE+1L)
a_with_bits("POPMB", _a_gap_r1+_a_read_r2+_a_regmask_r3+_a_read_mem)
#define J_PUSHC (J_LAST_JOPCODE+2L)
a_with_bits("PUSHC", _a_read_r1+_a_read_r2+_a_set_r1+_a_modify_mem)
#define J_CALLI (J_LAST_JOPCODE+3L)
a_with_bits("CALLI", _a_read_r4+_a_set_r1+_a_call)
#define J_CALLIR (J_LAST_JOPCODE+4L)
a_with_bits("CALLIR", _a_read_r4+_a_read_r3+_a_set_r1+_a_call)
#define J_TAILCALLI (J_LAST_JOPCODE+5L)
a_with_bits("TAILCALLI", _a_read_r4+_a_set_r1+_a_call)
#define J_TAILCALLIR (J_LAST_JOPCODE+6L)
a_with_bits("TAILCALLIR", _a_read_r4+_a_read_r3+_a_set_r1+_a_call)
#define J_CALLX (J_LAST_JOPCODE+7L)
a_with_bits("CALLX", _a_read_r4+_a_set_r1+_a_call)
#define J_CALLXR (J_LAST_JOPCODE+8L)
a_with_bits("CALLXR", _a_read_r4+_a_read_r3+_a_set_r1+_a_call)
#define J_TAILCALLX (J_LAST_JOPCODE+9L)
a_with_bits("TAILCALLX", _a_read_r4+_a_set_r1+_a_call)
#define J_TAILCALLXR (J_LAST_JOPCODE+10L)
a_with_bits("TAILCALLXR", _a_read_r4+_a_read_r3+_a_set_r1+_a_call)
#define J_MOVDIM (J_LAST_JOPCODE+11L)
a_with_bits("MOVDIM", _a_regmask_r1+_a_gap_r2+_a_regmask_r3)
#define J_MOVIDM (J_LAST_JOPCODE+12L)
a_with_bits("MOVIDM", _a_regmask_r1+_a_gap_r2+_a_regmask_r3)
#define J_ADCK (J_LAST_JOPCODE+13L)
a_with_bits("ADCK", _a_read_r2+_a_set_r1)
#define J_ADCR (J_LAST_JOPCODE+14L)
a_with_bits("ADCR", _a_read_r2+_a_read_r3+_a_set_r1)
#define J_SBCK (J_LAST_JOPCODE+15L)
a_with_bits("SBCK", _a_read_r2+_a_set_r1)
#define J_SBCR (J_LAST_JOPCODE+16L)
a_with_bits("SBCR", _a_read_r2+_a_read_r3+_a_set_r1)
#define J_RSCK (J_LAST_JOPCODE+17L)
a_with_bits("RSCK", _a_read_r2+_a_set_r1)
#define J_RSCR (J_LAST_JOPCODE+18L)
a_with_bits("RSCR", _a_read_r2+_a_read_r3+_a_set_r1)
#define J_TSTK (J_LAST_JOPCODE+19L)
a_with_bits("TSTK", _a_read_r2)
#define J_TSTR (J_LAST_JOPCODE+20L)
a_with_bits("TSTR", _a_read_r2+_a_read_r3)
#define J_TEQK (J_LAST_JOPCODE+21L)
a_with_bits("TEQK", _a_read_r2)
#define J_TEQR (J_LAST_JOPCODE+22L)
a_with_bits("TEQR", _a_read_r2+_a_read_r3)
#define J_BICK (J_LAST_JOPCODE+23L)
a_with_bits("BICK", _a_read_r2+_a_set_r1)
#define J_BICR (J_LAST_JOPCODE+24L)
a_with_bits("BICR", _a_read_r2+_a_read_r3+_a_set_r1)
#define J_CMNK (J_LAST_JOPCODE+25L)
a_with_bits("CMNK", _a_read_r2)
#define J_CMNR (J_LAST_JOPCODE+26L)
a_with_bits("CMNR", _a_read_r2+_a_read_r3)
#define J_MVNK (J_LAST_JOPCODE+27L)
a_with_bits("MVNK", _a_read_r2)
#define J_MVNR (J_LAST_JOPCODE+28L)
a_with_bits("MVNR", _a_read_r2+_a_read_r3)
#define J_LAST_A_JOPCODE J_MVNR
#ifdef DEFINE_A_JOPTABLE
0
};
#endif
#ifndef JOPCODEDEF_ONLY
typedef struct { /* like struct Icode but with RealReg's and a peep field */
Icode ic;
int32 peep; /* opcode extension */
int32 dataflow;
int32 cond;
} PendingOp;
void a_pr_jopcode(PendingOp *p);
#define localcg_debug(n) (debugging(DEBUG_LOCALCG) && (localcg_debugcount & (n)))
extern char frameregnames[(16-9)*2];
/* register number -> name for sb (or v6), ip, fp, sl, sp
* (variable because dependent on calling standard
* in force). Also does lr and pc for simplicity.
*/
extern void setcallingstandard(char);
/* One of 'A', 'R', 'U', 'M', default set by compiler
* build, value alterable by configuration option.
*/
extern int32 pcs_flags;
/* Beware: these values are also written in the config tool */
#define PCS_CALLCHANGESPSR 1
#define PCS_FPE3 2
#define PCS_NOSTACKCHECK 4
#define PCS_REENTRANT 8
#define PCS_FPREGARGS 16 /* never in pcs_flags, only a pcs config value */
/* but mustn't overlap with pcs_flags bits */
#define PCS_NOFP 32
#define PCS_SOFTFP 64
#define PCS_INTERWORK 128
#define PCS_ACCESS_CONSTDATA_WITH_ADR 256
#define PCS_ZH_MASK 0x7f /* options passed from driver via -zh argument */
/* excludes access_constdata_with_adr */
#ifndef PCS_DEFAULTS
# define PCS_DEFAULTS 0
#endif
#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 MOVC_LOOP_THRESHOLD 24
extern int32 a_loads_r1(PendingOp const* const p);
extern int32 a_uses_r1(PendingOp const* const p);
extern int32 a_reads_r1(PendingOp const* const p);
extern int32 a_loads_r2(PendingOp const* const p);
extern int32 a_uses_r2(PendingOp const* const p);
extern int32 a_reads_r2(PendingOp const* const p);
extern int32 a_uses_r3(PendingOp const* const p);
extern int32 a_uses_r4(PendingOp const* const p);
extern int32 a_uses_mem(PendingOp const* const p);
extern int32 a_modifies_mem(PendingOp const* const p);
extern int32 a_uses_stack(PendingOp const* const p);
extern bool a_corrupts_r1(PendingOp const* p);
extern bool a_corrupts_r2(PendingOp const* p);
typedef struct
{
uint32 use, def, corrupt, dead;
} RegisterUsage;
#define regs_in(u) ((u)->use)
#define regs_out(u) ((u)->def)
#define regs_corrupt(u) ((u)->corrupt)
#define regs_dead(u) ((u)->dead)
#define regs_read(u) ((u)->use)
#define regs_written(u) ((u)->def | (u)->corrupt)
#define regs_free(u) ((u)->corrupt | (u)->dead)
#define regs_used(u) ((u)->use | (u)->def | (u)->corrupt)
/* returns the complete register usage of c */
extern GetRegisterUsage(const PendingOp *c, RegisterUsage *u);
extern char *CheckJopcodeP(const PendingOp *p, CheckJopcode_flags flags);
extern int32 power_of_two(int32 n);
extern int32 regofregbit(int32 m);
extern bool MultiplyNeedsWorkreg(int32 n);
extern uint32 movc_workregs(PendingOp const *p);
extern bool movc_preserving_r1r2(PendingOp const *p, bool dead_r2);
extern void show_inst_direct(PendingOp *p);
extern void peephole_op(PendingOp *p, bool flush);
extern void peephole_reinit(void);
extern void peephole_init(void);
extern void peephole_tidy(void);
#ifdef TARGET_HAS_AOF
#define aof_fpreg xr_objflg1 /* fn passes FP args in FP registers */
#define aof_usessb xr_objflg2 /* defined fn 'uses' sb */
#define aof_leaf xr_objflg3 /* defined fn is a leaf */
typedef struct CommonDef {
struct CommonDef *next;
DataDesc data;
Symstr *name;
int index;
int32 refsize;
int32 stringpos;
} CommonDef;
extern CommonDef *commondefs;
extern Symstr *data_sym, *bss_sym, *adcon_sym;
#else
#define aof_fpreg 0 /* fn passes FP args in FP registers */
#define aof_usessb 0 /* defined fn 'uses' sb */
#define aof_leaf 0 /* defined fn is a leaf */
#endif
extern DataDesc adconpool;
extern Symstr *adconpool_lab;
extern int adconpool_find(int32 w, int32 flavour, Symstr *sym);
extern void adconpool_flush(void);
extern void adconpool_init(void);
extern unsigned integer_load_max;
extern unsigned ldm_regs_max;
#define PROCESSOR_HAS_HALFWORDS 1
#define PROCESSOR_HAS_MULTIPLY 2 /* 32x32 => 64 */
#define PROCESSOR_HAS_26BIT_MODE 4
#define PROCESSOR_HAS_32BIT_MODE 8
#define PROCESSOR_HAS_THUMB 16
typedef struct
{ char name[16]; Uint flags; char arch[4];
char mulbits, multime, mlatime;
} Processor;
Processor const *LookupProcessor(char const *name);
Processor const *LookupArchitecture(char const *name);
typedef int ProcessorEnumProc(void *, Processor const *);
int EnumerateProcessors(ProcessorEnumProc *f, void *arg);
void target_lib_variant(char *b);
typedef enum { fpu_fpa, fpu_amp } FPU_Type;
extern FPU_Type fpu_type;
#endif /* JOPCODEDEF_ONLY */
#endif
/* end of arm/mcdpriv.h */
|
stardot/ncc | tests/2256.c | /*
* 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"
/********************* 2256 ***********************/
/* must be compiled with -zpq8 */
int t0_2256(int argc, char **argv)
{ return argc; }
int t1_2256(int argc, char **argv)
{
int count, retval;
if (argc < 3)
return argc;
for (count = 0; count > 0; count--)
retval = t0_2256 (argc, argv);
return retval;
}
/* no executable test */
/********************* ***********************/
int main(void)
{
BeginTest();
EQI(0,0);
EndTest();
return 0;
}
|
stardot/ncc | mip/globals.h | <gh_stars>0
/*
* mip/globals.h - ubiquitously required definitions
* Copyright (C) Acorn Computers Ltd., 1988.
* Copyright (C) Codemist Ltd., 1988.
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
#ifndef _globals_LOADED
#define _globals_LOADED
#ifdef __STDC__
# include <stdarg.h>
#else
# include <varargs.h>
#endif
#ifndef _host_LOADED
# include "host.h"
#endif
#ifdef COMPILING_ON_MVS
/*
* The following #included #define's ensure that external symbols are
* limited to 6 chars without gratuitous changes to every file.
*/
# include "sixchar.h"
#endif
#ifndef _options_LOADED
# include "options.h"
#endif
#ifndef _target_LOADED
# include "target.h"
#endif
#ifndef _defaults_LOADED
# include "defaults.h"
#endif
#ifndef _defs_LOADED
# include "defs.h"
#endif
#include "msg.h"
/*
* DUFF_ADDR is used to initialise pointers which may not be dereferenced.
* The address chosen traps on dereference on the machines we use.
* No use is made of its value, save that is assumed to compare equal to
* itself when used to initialise allocators. It could, functionally,
* equally well be NULL, or for the queasy, a pointer to one static byte.
*/
#define DUFF_ADDR (VoidStar)(~0x45245252L) /* 0xbadbadad */
/* the following lines ease bootstrapping problems: "\v\f\r" respectively */
/* (allowing different settings from the usual ones below in options.h */
#ifndef CHAR_NL
# define CHAR_NL 10
#endif
#ifndef CHAR_VT
# define CHAR_VT 11
#endif
#ifndef CHAR_FF
# define CHAR_FF 12
#endif
#ifndef CHAR_CR
# define CHAR_CR 13
#endif
#define CHAR_BEL ('A'==193 ? 0x2f : 7)
/* Beware the following, if n==32 then ANSI-undefined. */
#define lsbmask(n) (((unsigned32)1 << (n)) - 1)
#define memclr(a,n) memset(a,0,n)
extern int32 pp_pragmavec[];
/*
* We put xx!=0 for switches that default to ON, and xx>0 for default off.
*/
#define warn_implicit_fns (pp_pragmavec['a'-'a'] != 0) /* cc only */
#define memory_access_checks (pp_pragmavec['c'-'a'] > 0) /* mip */
#define warn_deprecated (pp_pragmavec['d'-'a'] != 0) /* cc */
/* beware that #pragma -e is temporarily used for #error behaviour */
#define fpregargs_disabled (pp_pragmavec['g'-'a'] > 0)
#define integerlike_enabled (pp_pragmavec['h'-'a'] != 0) /* cc */
#define crossjump_enabled (pp_pragmavec['j'-'a'] != 0) /* mip */
/* ECN - pragma to disable all gen optimisations */
#define gen_opt_disabled (pp_pragmavec['k'-'a'] > 0)
#define ldm_enabled (pp_pragmavec['m'-'a'] > 0) /* arm */
/* ECN - pragma to disable tailcalls 'n' for Notailcalls */
#define no_tail_calls (pp_pragmavec['n'-'a'] > 0)
#define multiple_aof_code_areas (pp_pragmavec['o'-'a'] > 0) /* arm, mip */
#define profile_option (pp_pragmavec['p'-'a'] > 0) /* mip, arm */
#define full_profile_option (pp_pragmavec['p'-'a'] > 1) /* mip */
#define no_stack_checks (pp_pragmavec['s'-'a'] > 0) /* arm */
#define force_top_level (pp_pragmavec['t'-'a'] != 0) /* cc */
#define special_variad pp_pragmavec['v'-'a'] /* cc */
#define pcrel_vtables (pp_pragmavec['u'-'a'] > 0)
#define no_side_effects (pp_pragmavec['y'-'a'] > 0) /* cc */
#define cse_enabled (pp_pragmavec['z'-'a'] > 0) /* mip */
#define resultinflags (pp_pragmavec['x'-'a'] > 0)
#define var_warn_implicit_fns pp_pragmavec['a'-'a']
#define var_memory_access_checks pp_pragmavec['c'-'a']
#define var_warn_deprecated pp_pragmavec['d'-'a']
#define global_floatreg_var pp_pragmavec['f'-'a']
#define var_include_once pp_pragmavec['i'-'a']
#define var_crossjump_enabled pp_pragmavec['j'-'a']
#define var_gen_opt_disabled pp_pragmavec['k'-'a']
#define var_ldm_enabled pp_pragmavec['m'-'a']
#define var_no_tail_calls pp_pragmavec['n'-'a']
#define var_aof_code_area pp_pragmavec['o'-'a']
#define var_profile_option pp_pragmavec['p'-'a']
/* The next pragma provides flags to use during DEVELOPMENT. Permanent */
/* flags should be subsumed into feature, config or a proper pragma. */
#define var_cc_private_flags pp_pragmavec['q'-'a']
#define global_intreg_var pp_pragmavec['r'-'a']
#define var_no_stack_checks pp_pragmavec['s'-'a']
#define var_force_top_level pp_pragmavec['t'-'a']
#define var_no_side_effects pp_pragmavec['y'-'a']
#define var_cse_enabled pp_pragmavec['z'-'a']
#define var_resultinflags pp_pragmavec['x'-'a']
/*
* Bits within var_cc_private_flags: PLEASE keep up to date.
* 0x40000000 COMMON, CODE attribute - used internally
* 0x20000000 currently generating code for a VTable - used internally
* 0x01000000 16777216 Enable Standard scoping
* 0x00800000 8388608 Suppress generation of fpdesc tables
* 0x00400000 4194304 Show final function overloads
* 0x00200000 2097152 Enable C++ generated fns debugging
* 0x00100000 1048576 Disable direct substituion of inline function arguments
* 0x00080000 524288 flowgraf: uh... tail recursion something?
* 0x00040000 262144 flowgraf: Disable BLK2EXIT stuff
* 0x00020000 131072 Disable struct binder splitting
* 0x00010000 65536 Enable exprtemps debugging
* 0x00008000 32768 Disable str compression (#ifdef STRING_COMPRESSION)
* 0x00004000 16384 Show overload match value calculations
* 0x00002000 8192 Disable function inlining (forces out-of-line)
* 0x00001000 4096 Disable regalloc allocation preference calculation
* 0x00000800 2048 Disable regalloc copy-avoidance preference
* 0x00000400 1024 Disable preservation of unused a1-a4 across fn call
* 0x00000200 512 J_OPSYSK sets the psr
* 0x00000100 256 Disable live range splitting
* 0x00000080 128 Enable generation of exception tables
* 0x00000040 64 CSE: Disable propagating local values
* 0x00000020 32 CSE: Disable heapptr dataflow
* 0x00000010 16 Disable the tail continuation optimisation
* 0x00000008 8 Disable peepholing
* 0x00000004 4 Disable regalloc spill 'cleaning'
* 0x00000002 2 Toggle allocate store for top-level non-addrof
simpletype consts (default: C/do, C++/don't)
* 0x00000001 1 Ignore 'register' attribute on binders
*/
/* static options for compiler */
#define NAMEMAX 256L /* max no of significant chars in a name */
#define BIND_HASHSIZE 521L /* no. of Symstr hash table buckets */
#define MAX_SAVED_LABELS 32L /* max no of label to save in a label chain */
#define SEGSIZE 31744L /* (bytes) - unit of alloc of hunks */
/* (32K - 1024) for benefit of 16 bit ints */
#define ICODESEGSIZE 512L /* Icode vector now allocated in 8k hunks */
#define CODEVECSEGBITS 10L /* 4Kbyte unit of allocation */
#define CODEVECSEGSIZE (1L<<CODEVECSEGBITS)
#define CODEVECSEGMAX 256L /* max segments (max 1024K bytes/proc) */
#define REGHEAPSEGBITS 9L /* index array for segment of 512 vregs */
#define REGHEAPSEGSIZE (1L<<REGHEAPSEGBITS)
#define REGHEAPSEGMAX 64L /* max segments (hence max 32K vregs/proc) */
/* An old comment claimed that LITPOOLSIZE was 1024 for 'max address range' */
/* I suspect that this is out of date now that litpool overflows gently. */
#define LITPOOLSEGBITS 5L /* index array for segment of 32 lits */
#define LITPOOLSEGSIZE (1L<<LITPOOLSEGBITS)
#define LITPOOLSEGMAX 32L /* max segments, so 1024 lits ovfl gently */
#ifdef FOR_ACORN
#ifndef PASCAL
#ifndef FORTRAN
/* support for CFront pre-processing (IDJ:6-Jun-94) */
extern int cplusplus_flag;
#endif
#endif
#endif
/*
* disable error/warnings...
*/
extern int32 suppress;
#define D_IMPLICITCTOR 1L
#define D_ASSIGNTEST 2L
#define D_SHORTWARN 4L /* no longer used apparently */
#define D_PPNOSYSINCLUDECHECK 8L
#define D_IMPLICITVOID 0x10L
#define D_VALOFBLOCKS 0x20L
#define D_IMPLICITNARROWING 0x40L
#define D_ACCESS 0x80L
#define D_LONGFLOAT 0x100L
#define D_IMPLICITVIRTUAL 0x200L
#define D_STRUCTPADDING 0x400L
#define D_LOWERINWIDER 0x800L
#define D_GUARDEDINCLUDE 0x1000L
/* These two are currently pragmas rather than bits in suppress. Why? */
#define D_DEPRECATED 0x2000L
#define D_IMPLICITFNS 0x4000L
#define D_STRUCTASSIGN 0x8000L
#ifdef PASCAL /*ECN*/
#undef D_ASSIGNTEST
#define D_ASSIGNTEST (~0)
#endif
/* The following are used in some implementations to suppress ERRORS. */
/* Note: they partly duplicate the -FC (FEATURE_LIMITED_PCC) option. */
/* Note: suppressing errors makes the implementation non-conforming. */
#define D_ZEROARRAY 0x10000L
#define D_PPALLOWJUNK 0x20000L
#define D_IMPLICITCAST 0x40000L
#define D_MPWCOMPATIBLE 0x80000L
#define D_CAST 0x100000L /* Suppress errors about implicit casting of
pointer to A to pointer to B (A != B)
*/
#define D_LINKAGE 0x200000L /* ECN - Suppress errors about static/extern
linkage disagreements
*/
#define D_UNUSEDTHIS 0x400000L
#define D_FUTURE 0x800000L /* suppress C++ keyword in C, etc. */
#define D_CFRONTCALLER 0x1000000L /* warn about virtual fn calls, ptr to mem fns */
#define D_MULTICHAR 0x2000000L /* warn about 'foo' */
#define D_LONGLONGCONST 0x4000000L /* warn about 3000000000 being 3000000000ll */
#define D_IMPLICITINT 0x8000000L /* no implicit int in C++ */
/* warnings which are disabled by default */
#ifndef D_SUPPRESSED
# define D_SUPPRESSED \
(D_SHORTWARN | D_STRUCTPADDING | D_GUARDEDINCLUDE | D_PPNOSYSINCLUDECHECK | \
D_IMPLICITCTOR | D_IMPLICITNARROWING | D_LOWERINWIDER | D_FUTURE | \
D_CFRONTCALLER | D_STRUCTASSIGN)
#endif
#ifdef PASCAL /*ECN*/
/*
* run time checks
*/
extern int32 rtcheck;
#define RTCHECK_ARRAY 1L /* pc */
#define RTCHECK_CASE 2L /* pc */
#define RTCHECK_NIL 4L /* pc */
#define RTCHECK_REFERENCE 8L /* pc */
#define RTCHECK_ASSERT 16L /* pc */
#define RTCHECK_DEADCODE 32L /* pc */
#endif
/*
* features
*/
extern int32 feature;
#define FEATURE_SAVENAME 1L /* arm(gen), mip */
#define FEATURE_NOUSE 2L /* mip(bind) */
#define FEATURE_PPNOUSE 4L /* cc */
#define FEATURE_PREDECLARE 8L /* mip(bind) */
#define FEATURE_ANOMALY 0x10L /* mip(regalloc) */
#define FEATURE_ANNOTATE 0x20L /* arm(asm), potentially mip */
#define FEATURE_WARNOLDFNS 0x40L /* cc */
#define FEATURE_TELL_PTRINT 0x80L /* cc */
#define FEATURE_UNEXPANDED_LISTING 0x100L /* cc */
#define FEATURE_USERINCLUDE_LISTING 0x200L /* cc */
#define FEATURE_SYSINCLUDE_LISTING 0x400L /* cc */
#define FEATURE_6CHARMONOCASE 0x800L /* cc */
#define FEATURE_ALLOWCOUNTEDSTRINGS 0x1000L
#define FEATURE_CPP 0x02000L /* ISO/ANSI C++ Standard */
#define FEATURE_CFRONT 0x04000L /* want this near to _PCC... */
#define FEATURE_PCC 0x08000L /* cc, mip(bind, misc) */
#define FEATURE_ANSI 0x10000L /* ISO/ANSI C Standard */
#define FEATURE_CFRONT_OR_PCC (FEATURE_CFRONT|FEATURE_PCC)
#define FEATURE_REVERSE_BITFIELDS 0x20000L /* cc */
#define FEATURE_PPCOMMENT 0x40000L /* cc */
#define FEATURE_WR_STR_LITS 0x80000L /* mip(flowgraf) */
#define FEATURE_SIGNED_CHAR 0x100000L /* cc */
#define FEATURE_FUSSY 0x200000L /* for pedants & paranoiacs */
#define FEATURE_UNIX_STYLE_LONGJMP 0x400000L /* mip */
#define FEATURE_LET_LONGJMP_CORRUPT_REGVARS \
0x800000L /* mip */
/* meaningful only if _UNIX_STYLE_LONGJMP */
#define FEATURE_AOF_AREA_PER_FN 0x1000000L /* arm(aaof) */
#define FEATURE_VERBOSE 0x2000000L /* mip */
#define FEATURE_DONTUSE_LINKREG 0x4000000L /* mip */
#define FEATURE_LIMITED_PCC 0x8000000L /* pp, sem */
#define FEATURE_KANDR_INCLUDE 0x10000000L /* mip */
#define FEATURE_INLINE_CALL_KILLS_LINKREG \
0x20000000L /* mip */
#ifdef PASCAL /*ECN*/
#define FEATURE_ISO 0x40000000L /* cc */
#else
#define FEATURE_ENUMS_ALWAYS_INT 0x40000000L
#endif
#define FEATURE_NOWARNINGS 0x80000000L /* mip(misc) */
#ifdef PASCAL /*ECN*/
#undef FEATURE_PREDECLARE
#undef FEATURE_WARNOLDFNS
#undef FEATURE_SYSINCLUDE_LISTING
#undef FEATURE_WR_STR_LITS
#undef FEATURE_PCC
#undef FEATURE_ANOMALY
#undef FEATURE_TELL_PTRINT
#undef FEATURE_6CHARMONOCASE
#define FEATURE_PREDECLARE 0
#define FEATURE_WARNOLDFNS 0
#define FEATURE_SYSINCLUDE_LISTING 0
#define FEATURE_WR_STR_LITS 0
#define FEATURE_PCC 0
#define FEATURE_ANOMALY 0
#define FEATURE_TELL_PTRINT 0
#define FEATURE_6CHARMONOCASE 0
#endif
#ifdef CPLUSPLUS
#define LanguageIsCPlusPlus (feature & FEATURE_CPP)
#else
#define LanguageIsCPlusPlus 0
#endif
/*
* Dynamic configuration flags.
*/
extern int32 config;
/* 1L CONFIG_HAS_MULTIPLY now defunct */
/* 2L CONFIG_SLOW_COND_FP_EXEC now defunct */
#define CONFIG_INDIRECT_SETJMP 4L /* a fn ptr may point to setjmp() */
#define CONFIG_CLIPPER30 8L /* Special for Intergraph Clipper */
#define CONFIG_ALT_REGUSE 0x10L /* to generalise normal_sp_sl */
#define CONFIG_FPREGARGS 0x20L
#define CONFIG_BIG_ENDIAN 0x40L
#define CONFIG_ENDIANNESS_SET 0x80L /* if this is set (by config_init()) */
/* default of target byte sex to host */
/* does not apply */
#define CONFIG_NO_UNALIGNED_LOADS 0x100L
#define CONFIG_REENTRANT_CODE 0x200L
#define CONFIG_OPTIMISE_SPACE 0x400L
#define CONFIG_OPTIMISE_TIME 0x800L
#define CONFIG_SOFTWARE_FLOATS 0x1000L
#define CONFIG_SOFTWARE_DOUBLES 0x2000L
#define CONFIG_SOFTWARE_FP (CONFIG_SOFTWARE_FLOATS+CONFIG_SOFTWARE_DOUBLES)
#define CONFIG_HALFWORD_SPT 0x4000L
#define CONFIG_STRUCT_PTR_ALIGN 0x8000L /* take advantage of alignment of ptrs to structs */
#define CONFIG_NO_HALFWORD_STORES 0x10000L
#define CONFIG_UNWIDENED_NARROW_ARGS 0x20000L
#define CONFIG_LONG_MULTIPLY 0x40000L /* target has long multiply */
#define CONFIG_32BIT 0x80000L /* target supports 32 bit mode */
#define CONFIG_26BIT 0x100000L /* target supports 26 bit mode */
#ifdef TARGET_IS_BIG_ENDIAN
#define target_lsbytefirst 0
#else
#ifdef TARGET_IS_LITTLE_ENDIAN
#define target_lsbytefirst 1
#else
#define target_lsbytefirst ((config & CONFIG_BIG_ENDIAN) == 0)
#endif
#endif
/* Note: 3 separate endianness variables: */
/* target_lsbytefirst - big/little-endian */
/* target_lsbitfirst - bitfields within machine word */
/* features & FEATURE_REVERSE_BITFIELDS - reverse bfs within container */
/* Currently force lsbitfirst to by lsbytefirst until there is a mechanism */
/* for changing it (IJR). */
#define target_lsbitfirst target_lsbytefirst
extern bool host_lsbytefirst;
extern FILE *asmstream, *objstream;
extern char const *sourcefile;
extern char const *objectfile;
extern int32 xwarncount, warncount, recovercount, errorcount;
extern bool list_this_file;
extern FILE *listingstream;
extern FILE *errors;
extern bool implicit_return_ok;
extern char *phasename;
typedef struct CurrentFnDetails {
Symstr *symstr;
int xrflags;
Binder *structresult;
VRegnum baseresultreg;
int nresultregs;
int32 flags, auxflags;
int32 maxstack;
int32 maxargsize;
int32 argwords;
int32 fltargwords;
BindList *argbindlist;
int32 fnname_offset; /* for xxx/gen.c */
FileLine fl;
} CurrentFnDetails;
extern CurrentFnDetails currentfunction;
#define procflags currentfunction.flags
#define procauxflags currentfunction.auxflags
#define greatest_stackdepth currentfunction.maxstack
#define argument_bindlist currentfunction.argbindlist
#define max_argsize currentfunction.maxargsize
#define cg_fnname_offset_in_codeseg currentfunction.fnname_offset
#ifdef TARGET_IS_ARM_OR_THUMB
extern int arthur_module;
#endif
extern int bss_threshold;
extern bool disallow_tentative_statics;
Int64Con *mkint64const(SET_BITMAP m, int64 const *i64);
extern FloatCon *real_of_string(const char *s, int32 flag);
extern FloatCon *real_to_real(FloatCon *fc, SET_BITMAP m);
extern FloatCon *int_to_real(int32 n, int32 u, SET_BITMAP m);
extern int32 length(List const *l);
extern List *dreverse(List *x);
extern Binder *dreverse_binder(Binder *x);
extern List *nconc(List *x, List *y);
extern bool generic_member(IPtr a, List const *l);
extern List *generic_ndelete(IPtr a, List *l);
/* Destructively modify the argument reglist by removing from it the */
/* first entry whose data field is 'a'. */
extern int32 max(int32 a, int32 b);
extern int32 bitcount(int32 n);
extern int32 logbase2(int32 n);
extern void errstate_perfileinit(void);
extern void errstate_initialise(void);
extern int32 aetree_debugcount;
extern int32 cse_debugcount;
extern int32 localcg_debugcount;
extern int32 syserr_behaviour;
extern int files_debugcount;
char const *compiler_name(void);
#ifdef __CC_NORCROFT
/*
* The next procedure takes a string as a format... check args.
* Note use of a cryptic pragma rather than a nice spelt out one,
* since the option is only intended for support of this compiler
*/
# pragma -v3
#endif
extern void cc_msg(char *s, ...); /* NB still an uncompressed string */
#ifdef __CC_NORCROFT
# pragma -v0
#endif
#ifdef NLS
extern void cc_msg_lookup(msg_t errcode, ...);
#else
# define cc_msg_lookup cc_msg
#endif
/* The following 4 functions are used by the Fortran front end. */
extern void cc_rerr_l(int32 line, msg_t errorcode, va_list a);
extern void cc_warn_l(int32 line, msg_t errorcode, va_list a);
extern void cc_err_l(int32 line, msg_t errorcode, va_list a);
extern void cc_fatalerr_l(int32 line, msg_t errorcode, va_list a);
extern void flt_report_error(int);
extern void compile_abort(int);
extern void summarise(void);
extern void listing_diagnostics(void);
#ifdef CALLABLE_COMPILER
#define reg_setallused(s) ((void)(s))
#else
#ifndef NON_CODEMIST_MIDDLE_END
extern void reg_setallused(RealRegSet *s); /* not as nasty as memcpy */
#endif
#endif
#define StrEq(a, b) (strcmp((a), (b)) == 0)
#define StrnEq(a, b, n) (strncmp((a), (b), (n)) == 0)
#endif
/* end of mip/globals.h */
|
stardot/ncc | util/genhdrs.c | <reponame>stardot/ncc
/*
* C compiler support file genhdrs.c
* Copyright (C) Codemist Limited, 1987, 1989.
* Copyright (C) Acorn Computers Limited., 1988
* Copyright (C) Advanced RISC Machines Limited 1992-93.
* SPDX-Licence-Identifier: Apache-2.0
* All rights reserved.
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
/*
* This file is a program that is run in order to create a file called
* headers.c which is part of the source of the compiler. It also creates
* errors.h. To do its work it needs prototype files miperrs.h, feerrs.h &
* mcerrs.h, and access to directories containing the standard headers,
* such as stdio.h etc. The object of having this utility is twofold -
* first it arranges for standard headers to be built into an in-store
* mini file system so that #including them can be fast, then it organises
* some data compression for both builtin headers and the text of error
* messages.
*
* Call this program with
*
* Genhdrs -o headers.c -i <dir> <files> or
* Genhdrs -e errors.h -q miperrs.h -q mcerrs.h -q mcerrs.h [-n] [-s]
*
* where the <files> at the end will be a list of names of files from the
* given directory that are to be included as built-in headers.
* If the list of files is too long to fit on the line it is possible to go
* -v <via-file>
* where the via-file contains a list. If -v is specified separate files
* may not be given as well.
*
* Flag -n causes error messages to get mapped to numbers
* Flag -s causes error messages to be compressed
*
* On an Acorn ARM a certain version of the compiler was 323304 bytes
* in size with no compression of error messages. The savings by selecting
* various of the above options were (where -t was a further option to
* compress error strings in with the built-in headers, which option has
* now been removed):
*
* -n 4476
* -s 4496
* -n -s 8972 (about 2.7%)
* -t 2276
* -n -t 6752
*
* It seems that -n -s will be useful for production code, -s reasonably
* painless for most system developers (not using -n because system
* developers may expect to see syserrs from time to time), and no
* compression being the mode of choice when doing cross-development
* for a new machine, especially one with a different character set.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <ctype.h>
#include <time.h>
#define SELF "genhdrs"
/*
* The following sets ArgvType for 64-bit pointers so that
* DEC Unix (OSF) cc can be used with the -xtaso-short compiler option
* to force pointers to be 32-bit.
*/
#if defined(__alpha) && defined(__osf__)
#pragma pointer_size (save)
#pragma pointer_size (long)
#endif
typedef char *ArgvType;
#if defined(__alpha) && defined(__osf__)
#pragma pointer_size (restore)
#endif
#define MAXPATHS 40
#define MAXFILENAMESZ 256
#define MAXSTRINGS 1000 /* How many strings can be stored here */
#define MAXCHARS 100000 /* Total length of strings to be processed */
static int number_msgs = 0;
static int emit_tagdirs = 0; /* whether to emit -TAGS- and -NOT TAGS- messages*/
static int squeeze_msgs = 0;
static int safe_compress= 1;
static int lastchar = 0;
static int npaths = 0;
static int nerrors = 0;
static char *paths[MAXPATHS];
static int nepaths = 0;
static char *epaths[MAXPATHS];
static char hdrname[40][MAXPATHS];
static char file_name[MAXFILENAMESZ];
static unsigned char *strings[MAXSTRINGS];
static int stringlength[MAXSTRINGS];
static unsigned short compression[256], compression_depth[256];
static unsigned char *chardata = NULL;
static int *digraph_counts = NULL;
static int stringcount = 0;
static int msgnumber = 0;
static int charpoint = 0;
/* 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
#define STREND 0x8
#define STRSTART 0x9
static FILE *path_open(char *name, char *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 outch(int ch)
{ if (charpoint >= MAXCHARS)
{ charpoint = 0;
fprintf(stderr, "%s: Too many chars (%u permitted)\n", SELF, MAXCHARS);
++nerrors;
}
else
chardata[charpoint++] = (ch);
}
static void copy_header(char *name)
{
FILE *fh1;
int ch, state = NORMAL;
char ansi_name[32];
fh1 = path_open(name, "r");
if (fh1==NULL)
{ fprintf(stderr, "Unable to read input file %s\n", name);
++nerrors;
return;
}
if ((name[0] == 'h' || name[0] == 'H') && name[1] == '.')
{ strcpy(ansi_name, name+2);
strcat(ansi_name, ".h");
}
else if(name[0] == ':') /* Macintosh filenames can start with : */
strcpy(ansi_name, name+1);
else
strcpy(ansi_name, name);
fprintf(stderr, "%s: Copying %s as %s\n", SELF, file_name, ansi_name);
strcpy(hdrname[stringcount], ansi_name);
if (stringcount >= MAXSTRINGS)
{ fprintf(stderr, "%s: Too many strings (%u allowed)\n", SELF, MAXSTRINGS);
stringcount = 0;
++nerrors;
return;
}
strings[stringcount++] = &chardata[charpoint];
lastchar = '\n';
ch = getc(fh1);
while (ch!=EOF)
{
switch (state)
{
case NORMAL:
switch (ch)
{
case '\t':
case ' ': ch = getc(fh1);
if (ch != ' ') outch(' ');
continue;
case '\'': outch(ch); state = CHAR; break;
case '\"': outch(ch); state = STRING; break;
case '/': state = SLASH; break;
default: outch(ch); break;
}
break;
case STRING:
switch (ch)
{
case '\"': outch(ch); state = NORMAL; break;
case '\\': outch(ch); state = STRBACK;break;
default: outch(ch); break;
}
break;
case CHAR:
switch (ch)
{
case '\'': outch(ch); state = NORMAL; break;
case '\\': outch(ch); state = CHARBACK;break;
default: outch(ch); break;
}
break;
case STRBACK:
outch(ch);
state = STRING;
break;
case CHARBACK:
outch(ch);
state = CHAR;
break;
case SLASH:
switch (ch)
{
case '*': state = COMMENT;break;
case '\'': outch('/');
outch(ch); state = CHAR; break;
case '\"': outch('/');
outch(ch); state = STRING; break;
default: outch('/');
outch(ch); 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);
++nerrors;
return;
}
ch = getc(fh1);
}
if (state!=NORMAL || lastchar!='\n')
{
fprintf(stderr, "\nUnexpected end of file in %s?\n", file_name);
++nerrors;
}
outch(0);
while (charpoint & 3) outch(0);
fclose(fh1);
}
static void decompress_char(int c)
{
int z = compression[c];
if (c == z)
{ if (c == '\n') c = 'n', putc('\\', stderr);
else if (c == 0) c = '0', putc('\\', stderr);
putc(c, stderr);
}
else
{ decompress_char((z >> 8) & 0xff);
decompress_char(z & 0xff);
}
}
static int compress_strings(int emsg, int *digraph_counts, char *force_used)
/*
* value returned is greatest stack depth needed during decompression.
* A nonzero arg => treat strings as error messages and try to preserve
* %? and $? escape sequences in them.
*/
{
int i, nsquashed = 0, stackdepth_needed = 0, worst_char = 0;
int total_bytes = 0;
for (i = 0; i < 256; i++) compression[i] = compression_depth[i] = 0;
/*
* Identify the characters that are in use in the given set of strings.
*/
if (safe_compress && force_used != 0)
for (i = force_used[0]; i != 0; i = *(++force_used))
compression[i & 0xff] = i;
for (i=0; i<stringcount; i++)
{ unsigned char *s = strings[i];
int l = stringlength[i] = 1 + strlen((char *)s);
int k;
total_bytes += l;
for (k=0; k<l; k++) compression[s[k] & 0xff] = s[k];
}
fprintf(stderr, "%d bytes of strings found\n", total_bytes);
for (i=1; i<256 && stackdepth_needed < 10; i++)
{ int z = compression[i];
int j, best, bestj;
if (z == i) continue; /* Char code already in use */
for (j=0; j<256*256; j++) digraph_counts[j] = 0;
for (j=0; j<stringcount; j++)
{ unsigned char *s = strings[j];
int l = stringlength[j];
int k, inesc = 0;
for (k=1; k<l; k++)
{ int a = s[k-1] & 0xff, b = s[k] & 0xff;
if (!emsg) digraph_counts[256*a+b]++;
else switch (inesc)
{
case 0: switch (a)
{
case '%': inesc = 1;
continue;
case '$': inesc = 2;
continue;
default: if (b != '%' && b != '$' && b != 0)
digraph_counts[256*a+b]++;
continue;
}
case 1: switch (tolower(a))
{
case '%': case 'c': case 'd': case 'e': case 'f': case 'g':
case 'i': case 'n': case 'o': case 'p': case 's': case 'u':
case 'x': inesc = 0; /* Drop through */
default: continue;
}
default: inesc = 0;
continue;
}
}
}
best = bestj = -1;
for (j=0; j<256*256; j++)
if (digraph_counts[j] > best) best = digraph_counts[j], bestj = j;
if (best <= 1) break; /* Compression finished! */
#ifdef VERBOSE_MODE
fprintf(stderr, "%.4x -> %.2x ", bestj, i);
#else
putc('.', stderr);
if (++nsquashed == 64) putc('\n', stderr), nsquashed = 0;
#endif
compression[i] = bestj;
{ int l1 = compression_depth[bestj & 0xff];
int l2 = compression_depth[bestj >> 8];
int l = 1 + l2;
if (l1 > l) l = l1;
compression_depth[i] = l;
if (l > stackdepth_needed)
{ stackdepth_needed = l;
worst_char = i;
}
}
for (j=0; j<=stringcount; j++)
{ unsigned char *s = strings[j];
int l = stringlength[j];
int ba = bestj>>8, bb = bestj & 0xff;
int k, inesc = 0;
for (k=1; k<l; k++)
{ int a = s[k-1] & 0xff, b = s[k] & 0xff;
/*
* I only combine characters if so doing would not disrupt an escape
* sequence.
*/
if (!emsg) goto combine;
else switch (inesc)
{
case 0: switch (a)
{
case '%': inesc = 1;
continue;
case '$': inesc = 2;
continue;
default: if (b != '%' && b != '$' && b != 0) goto combine;
}
case 1: switch (tolower(a))
{
case '%': case 'c': case 'd': case 'e': case 'f': case 'g':
case 'i': case 'n': case 'o': case 'p': case 's': case 'u':
case 'x': inesc = 0; /* Drop through */
default: continue;
}
default: inesc = 0;
continue;
}
combine:
if (a == ba && b == bb)
{ s[k-1] = i;
/* was: memmove(&s[k], &s[k+1], l-k-1); */
{
int n = l-k-1;
unsigned char *a = &s[k];
unsigned char *b = &s[k+1];
for (; n-- > 0;) *a++ = *b++;
}
stringlength[j] = l = l-1;
total_bytes--;
}
}
}
}
fprintf(stderr,
"\nNeed %d bytes of stack in decompression for char %.2x (",
stackdepth_needed, worst_char);
decompress_char(worst_char);
fprintf(stderr, ")\nsize = %d now\n", total_bytes);
return stackdepth_needed;
}
static int print_squashed_msg(unsigned char *s, int l, FILE *fe, int filecol)
{
int c, i;
putc('\"', fe); filecol++;
for(i=0; i<l; i++)
{ switch (c = s[i])
{
case '\n':
c = 'n'; /* Drop through */
case '\"': case '\\':
break;
case 0: if (i == l-1) continue;
default:
if (filecol > 70 && !isspace(c))
{ putc('\\', fe);
putc('\n', fe);
filecol = 0;
}
if (
#ifdef macintosh
/* some Mac compilers admit that some high-bit set chars are printable */
/* and some others don't define isprint above 0x7f (which is non-ANSI) */
(c & ~0x7f) == 0 &&
#endif
isprint(c)) putc(c, fe), filecol++;
/*
* If I need to print an (octal) escape I always show 3 digits to avoid
* confusion if the next character happens to be numeric.
*/
else fprintf(fe, "\\%.3o", c & 0xff), filecol+=4;
continue;
}
putc('\\', fe);
putc(c, fe), filecol+=2;
}
putc('\"', fe), filecol++;
return filecol;
}
#define MAP 0
#define NUMBER 1
#define LEAVE 2
static void scan_msg_file(FILE *fq)
{
/*
* This is only called if I am squeezing error strings.
* In MAP mode I will collect strings so that the
* compression scheme has some data to work on.
*/
int prevch = -1, ch, ch1, state = NORMAL;
int action = MAP;
while ((ch1 = ch = getc(fq)) != EOF)
{
if (state == NORMAL && prevch == '\n' && ch == '%')
{ ch1 = ch = getc(fq);
switch (tolower(ch))
{
case 'o':
action = MAP; break;
case 's':
case 'z': action = LEAVE; break;
default: fprintf(stderr, "\n%%%c unrecognised\n", ch);
break;
}
continue;
}
if (state == NORMAL && prevch == '/' && ch == '*')
state = COMMENT;
else if (state == COMMENT && prevch == '*' && ch == '/')
state = NORMAL;
else if (state == NORMAL && ch == '\"')
{ state = STRSTART;
switch (action)
{
case MAP:
if (stringcount >= MAXSTRINGS)
{ fprintf(stderr,
"%s: Too many strings (%u allowed)\n", SELF, MAXSTRINGS);
stringcount = 0;
++nerrors;
return;
}
strings[stringcount++] = &chardata[charpoint];
break;
default:
break;
}
}
else if (state == STRING)
{ for (;;)
{ if (ch == '\\')
{ switch (ch1 = ch = getc(fq))
{
case '\n':
ch1 = ch = getc(fq);
continue;
case 'n': case 'N':
ch1 = '\n';
break;
case 'a': case 'A':
case 'b': case 'B':
case 'f': case 'F':
case 'r': case 'R':
case 't': case 'T':
case 'v': case 'V':
case 'x': case 'X':
case '0': fprintf(stderr,
"Bad escape found in header prototype\n");
default:
break;
}
}
else if (ch == '\"') state = STREND;
break;
}
}
if (action == MAP && state == STRING) outch(ch1);
if (state == STREND)
{ state = NORMAL;
switch (action)
{
case MAP:
outch(0);
while (charpoint & 3) outch(0);
break;
default:
break;
}
}
if (state == STRSTART) state = STRING;
prevch = ch;
}
}
static void copy_msg_file(FILE *fe, FILE *fq, FILE *ft)
{
int prevch = -1, ch, state = NORMAL;
int action = squeeze_msgs ? MAP : LEAVE;
int efilecol = 0, tfilecol = 0;
/* NB: number_msgs <=> ft != NULL */
while ((ch = getc(fq)) != EOF)
{
if (state == NORMAL && prevch == '\n' && ch == '%')
{ ch = getc(fq);
switch (tolower(ch))
{
case 'o': if (emit_tagdirs) fprintf(fe, "/*-TAGS-*/\n");
action = squeeze_msgs ? MAP : LEAVE;
break;
case 's': if (emit_tagdirs) fprintf(fe, "/*-NOT TAGS-*/\n");
action = LEAVE;
break;
case 'z': if (emit_tagdirs) fprintf(fe, "/*-TAGS-*/\n");
action = LEAVE;
break;
default: fprintf(stderr, "\n%%%c unrecognised\n", ch);
break;
}
continue;
}
if (state == NORMAL && prevch == '/' && ch == '*')
state = COMMENT;
else if (state == COMMENT && prevch == '*' && ch == '/')
state = NORMAL;
else if (state == NORMAL && ch == '\"')
{ state = STRSTART;
if (number_msgs)
{ ++msgnumber;
efilecol += fprintf(fe, "%d /* ", msgnumber);
tfilecol += fprintf(ft, "/* %3d */ ", msgnumber);
}
if (action == MAP)
{ if (stringcount >= MAXSTRINGS) stringcount = 0;
if (number_msgs)
tfilecol = print_squashed_msg(strings[stringcount],
stringlength[stringcount], ft, tfilecol);
else
{ efilecol = print_squashed_msg(strings[stringcount],
stringlength[stringcount], fe, efilecol);
/*
* I wanted to put a newline here to improve the format of the converted
* error file - but that caused confusion in places where I had line
* continuation in the header prototype files. Hence I will end up
* with longer lines here than I like.
*/
efilecol+=fprintf(fe, " /* ");
}
stringcount++;
}
}
else if (state == STRING)
{ for (;;)
{ if (ch == '\\')
{ switch (ch = getc(fq))
{
case '\n':
putc('\\', fe), putc(ch, fe), efilecol = 0;
if (ft != NULL)
putc('\\', ft), putc(ch, ft), tfilecol = 0;
ch = getc(fq);
continue;
case 'n': case 'N':
putc('\\', fe), efilecol++;
if (ft != NULL) putc('\\', ft), tfilecol++;
break;
case 'a': case 'A':
case 'b': case 'B':
case 'f': case 'F':
case 'r': case 'R':
case 't': case 'T':
case 'v': case 'V':
case 'x': case 'X':
case '0': fprintf(stderr,
"%s: Bad escape found in header prototype\n", SELF);
default:
putc('\\', fe), efilecol++;
if (ft != NULL)
putc('\\', ft), tfilecol++;
break;
}
}
else if (ch == '\"') state = STREND;
break;
}
}
putc(ch, fe);
if (ft != NULL && action != MAP &&
(state == STRSTART || state == STRING || state == STREND))
putc(ch, ft), tfilecol++;
if (ch == '\n')
efilecol = tfilecol = 0;
else
efilecol++;
if (state == STREND)
{ state = NORMAL;
if (action==MAP || number_msgs)
{ efilecol += fprintf(fe, " */");
if (ft != NULL) putc('\n', ft);
}
}
if (state == STRSTART) state = STRING;
prevch = ch;
}
}
static int make_headers(char *headers, int argc, ArgvType *argv, char *viafile)
{ FILE *fh;
int j, n_files = 0;
fh = fopen(headers, "w");
if (fh == NULL)
{ fprintf(stderr, "%s: Unable to create output file %s\n", SELF, headers);
return 1;
}
fprintf(stderr, "%s: Creating %s...\n", SELF, headers);
{ time_t t0 = time(NULL);
struct tm *tm = localtime(&t0);
fprintf(fh, "/*\n");
fprintf(fh, " * Copyright (C) Advanced RISC Machines Limited and\n");
fprintf(fh, " * Codemist Limited, 19%d.\n",
tm->tm_year);
fprintf(fh, " * All rights reserved.\n *\n");
fprintf(fh, " * %s, created by %s on %s */\n\n",
headers, SELF, ctime(&t0));
}
if (viafile)
{ FILE *vv = fopen(viafile, "r");
if (vv == NULL)
fprintf(stderr, "File %s could not be opened\n", viafile);
else
{ char fname[64];
int rc;
/* fscanf is magic here - it strips away whitespace just the way I want */
while ((rc = fscanf(vv, "%s", fname)) == 1)
{ copy_header(fname);
++n_files;
}
fclose(vv);
}
}
else
{ char *arg;
for (j = 1; j < argc; ++j)
{ arg = argv[j];
if (arg[0] == '-')
{ int flag;
if (arg[2] == 0 &&
(flag = tolower(arg[1])) != 'n' && flag != 's') ++j;
continue;
}
copy_header(arg);
++n_files;
}
}
if (nerrors == 0)
{ int sk = compress_strings(0, digraph_counts, (char *)NULL);
int where, n;
if (n_files == 0)
{ fprintf(fh, "#ifndef NO_INSTORE_FILES\n");
fprintf(fh, "# define NO_INSTORE_FILES 1\n");
fprintf(fh, "#endif\n");
}
else
{ fprintf(fh, "static const unsigned short int compression_info[256] = {");
for (j=0; j<256; j++)
{ if ((j & 0x7) == 0) fprintf(fh, "\n ");
fprintf(fh, "0x%.4x", compression[j]);
if (j == 255) fprintf(fh, "};\n\n");
else fprintf(fh, ", ");
}
fprintf(fh, "typedef struct {\n");
fprintf(fh, " const char *name;\n");
fprintf(fh, " int content;\n");
fprintf(fh, "} header_files;\n");
fprintf(fh, "\nstatic const header_files builtin_headers[] = {\n");
where = 0;
for (j=0; j < stringcount; j++)
{ fprintf(fh, " {\"%s\", %d},\n", hdrname[j], where);
where += stringlength[j];
}
fprintf(fh," {0, 0}};\n\n");
fprintf(fh, "static const unsigned char string_data[] = {");
n = 0;
for (j = 0; j < stringcount; j++)
{ unsigned char *s = strings[j];
int l = stringlength[j], w;
for (w = 0; w < l; ++w)
{ if ((n & 0xf) == 0) fprintf(fh, "\n ");
fprintf(fh, "%3d", s[w]);
n++;
if (n < where)
{ putc(',', fh);
continue;
}
else
{ fprintf(fh, "};\n\n");
break;
}
}
}
}
sk += 1; /* Add 1 for safety */
fprintf(fh, "#define HDRSTACKDEPTH %d\n\n", sk);
fprintf(fh,"/* end of %s */\n", headers);
fprintf(stderr, "%s: %s created successfully.\n", SELF, headers);
}
else
{ fclose(fh);
fh = fopen(headers, "w"); /* to truncate it to zero length */
fprintf(fh, "#error \"%s is empty because of %s errors.\"\n",
headers, SELF);
fprintf(stderr, "\n%s: %s is junk because of errors.\n\n",
SELF, headers);
}
fclose(fh);
return nerrors != 0;
}
static int make_messages(char *messages, int squeeze_msgs, char *text)
{ FILE *fe, *ft;
int j, esk = 0;
fe = fopen(messages, "w");
if (fe == NULL)
{ fprintf(stderr, "%s: Unable to create output file %s\n",
SELF, messages);
return 1;
}
if (text != NULL)
{ ft = fopen(text, "w");
if (ft == NULL)
{ fprintf(stderr, "%s: Unable to create output file %s\n",
SELF, messages);
fclose(fe);
return 1;
}
}
else
ft = NULL;
fprintf(stderr, "%s: Creating %s...\n", SELF, messages);
if (squeeze_msgs)
{ /* Here a pass over the error files is needed to collect */
/* information for the compression process */
for (j = 0; j < nepaths; j++)
{ FILE *fq = fopen(epaths[j], "r");
if (fq == NULL)
{ fprintf(stderr,
"%s: Unable to open error prototype file %s\n",
SELF, epaths[j]);
++nerrors;
continue;
}
fprintf(stderr, "Scanning error file %s\n", epaths[j]);
scan_msg_file(fq);
fclose(fq);
}
/* Preclude any characters of the C character set being used */
/* to compress an error message in case of subsequent chaos. */
esk = compress_strings(1, digraph_counts,
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
0123456789 _!\"#$%&'()=-~^{[+;*:}]|\\<,>.?/");
charpoint = stringcount = 0;
}
{ time_t t0 = time(NULL);
struct tm *tm = localtime(&t0);
fprintf(fe, "/*\n");
fprintf(fe, " * Copyright (C) Advanced RISC Machines Limited and\n");
fprintf(fe, " * Codemist Limited, 19%d.\n",
tm->tm_year);
fprintf(fe, " * All rights reserved.\n *\n");
fprintf(fe, " * %s, created by %s on %s */\n\n",
messages, SELF, ctime(&t0));
#ifdef __CC_NORCROFT
fprintf(fe, "#ifdef __CC_NORCROFT\n# pragma force_top_level\n");
fprintf(fe, "# pragma include_only_once\n#endif\n\n");
#endif
fprintf(fe, "#ifndef _msgs_LOADED\n#define _msgs_LOADED 1\n\n");
}
if (number_msgs)
fprintf(fe, "typedef int syserr_message_type;\n\n");
else
fprintf(fe, "typedef char *syserr_message_type;\n");
#ifdef __CC_NORCROFT
/* We really need a magic name like __check_ncc_internal_formats for -v3. */
fprintf(fe, "#ifdef __CC_NORCROFT\n# pragma -v3\n#endif\n\n");
#endif
fprintf(fe, "extern void syserr(syserr_message_type errcode, ...);\n\n");
if (number_msgs) /* nothing yet */
{ msgnumber = 0;
}
else
#ifdef __CC_NORCROFT
/* We really need a magic name like __check_ncc_internal_formats for -v3. */
fprintf(fe, "#ifdef __CC_NORCROFT\n# pragma -v0\n#endif\n\n");
#endif
if (nerrors == 0) for (j = 0; j < nepaths; j++)
{ FILE *fq = fopen(epaths[j], "r");
if (fq == NULL)
{ fprintf(stderr, "%s: Unable to open error prototype file %s\n",
SELF, epaths[j]);
++nerrors;
continue;
}
fprintf(stderr, "Copying error file %s\n", epaths[j]);
copy_msg_file(fe, fq, ft);
fclose(fq);
}
charpoint = stringcount = 0;
if (nerrors != 0)
fprintf(fe, "\n#error \"%s failed to create %s\"\n", SELF, messages);
if (number_msgs)
fprintf(fe, "\n#define NUMBERED_MESSAGES 1\n");
if (squeeze_msgs)
{ fprintf(fe, "\n#define COMPRESSED_MESSAGES 1\n");
fprintf(fe, "\n#define MSGSTACKDEPTH %d\n", esk+1);
fprintf(fe, "\n#ifdef DEFINE_MSG_COMPRESSION_TABLE\n");
fprintf(fe, "\nstatic unsigned short int ecompression_info[256] = {");
for (j = 0; j < 256; j++)
{ if ((j & 0x7) == 0) fprintf(fe, "\n ");
fprintf(fe, "0x%.4x", compression[j]);
if (j == 255) fprintf(fe, "};\n\n");
else fprintf(fe, ", ");
}
fprintf(fe, "\n#endif\n");
}
fprintf(fe, "\n#endif /* _msgs_LOADED */\n");
fprintf(fe, "/* end of %s */\n", messages);
fclose(fe);
if (ft != NULL) fclose(ft);
return nerrors != 0;
}
int main(int argc, ArgvType *argv)
{
int j, filecount = 0, rc;
char *arg, *viafile, *headers = NULL, *messages = NULL, *text = NULL;
nerrors = npaths = filecount = 0;
viafile = NULL;
for (j = 1; j < argc; ++j)
{ arg = argv[j];
if (arg[0] == '-')
{ switch (arg[1])
{
/*
* -n get error messages mapped onto numeric codes
*/
case 'n':
case 'N': number_msgs = 1;
break;
/*
* -d Emit directives for the mktags program for syserr messages
*/
case 'd':
case 'D': emit_tagdirs = 1;
break;
/*
* -t get text of messages mapped onto numeric codes
*/
case 't':
case 'T': arg += 2;
if (*arg == 0) arg = argv[++j];
text = arg;
break;
/*
* -s squeeze error messages (as individual strings)
*/
case 's':
case 'S': squeeze_msgs = 1;
break;
/*
* -i specify a search path for finding ordinary files to be
* copied to create in-store headers. E.g. -i /usr/include/
* might make sense on a Unix system.
*/
case 'i':
case 'I': if (npaths >= MAXPATHS)
{
fprintf(stderr,
"%s: Too many paths - only %u allowed\n",
SELF, MAXPATHS);
exit(1);
}
else
{
arg += 2;
if (*arg == 0) arg = argv[++j];
paths[npaths++] = arg;
}
break;
/*
* -o File to put bulk of compressed text into. This file
* will be compiled (as "headers.c") to form part of the
* compiler.
*/
case 'o':
case 'O': arg += 2;
if (*arg == 0) arg = argv[++j];
headers = arg;
break;
/*
* -e Error header output file ("errors.h") gets created by
* scanning error prototype file and assigning numeric error
* codes to messages, inserting compressed text for the
* messages into headers.c
*/
case 'e':
case 'E': arg += 2;
if (*arg == 0) arg = argv[++j];
messages = arg;
break;
/*
* -q prototype for "errors.h" contains raw form of error messages
* with various marker strings (%Z, %O and %S) to show what
* form of transformation is needed.
* %O define a numeric error code & arrange decoding tables,
* %S define numeric code but do not provide for decoding,
* %Z leave error text as a literal string (not numeric).
*
* There will normally be (at least) two error prototype files,
* one the generic one (mip/errproto.h) and one that is target
* specific (xxx/mcerrs.h). It may also prove necessary to
* have language (i.e. front-end) specific error files and
* even host-system specific ones - hence this utility allows
* for MAXPATHS inclusions here.
*/
case 'q':
case 'Q': if (npaths >= MAXPATHS)
{
fprintf(stderr,
"%s: Too many paths - only %u allowed\n",
SELF, MAXPATHS);
exit(1);
}
else
{
arg += 2;
if (*arg == 0) arg = argv[++j];
epaths[nepaths++] = arg;
}
break;
/*
* -v Provide the list of files for scanning through an indirection.
*/
case 'v':
case 'V': arg += 2;
if (*arg == 0) arg = argv[++j];
viafile = arg;
break;
case 'u':
case 'U': safe_compress = 0;
break;
default:
fprintf(stderr, "%s: Unknown option %s\n", SELF, arg);
++nerrors;
break;
}
}
else
++filecount;
}
if (number_msgs && text == NULL)
{ fprintf(stderr, "%s: Use of -n requires use of -t<textfile>\n", SELF);
return 1;
}
if (!number_msgs && text != NULL)
{ fprintf(stderr, "%s: Assuming -n (implied by -t<textfile>)\n", SELF);
number_msgs = 1;
}
if (nerrors != 0) return 1;
chardata = (unsigned char *)malloc(MAXCHARS);
digraph_counts = (int *)malloc(256*256*sizeof(int));
if (chardata == NULL || digraph_counts == NULL)
{ fprintf(stderr, "%s: Not enough free memory\n", SELF);
return 1;
}
rc = 0;
if (headers != NULL)
{ charpoint = stringcount = 0;
rc |= make_headers(headers, argc, argv, viafile);
}
nerrors = 0;
if (messages != NULL)
{ charpoint = stringcount = 0;
rc |= make_messages(messages, squeeze_msgs, text);
}
free(chardata);
free(digraph_counts);
return rc;
}
/* End of genhdrs.c */
|
stardot/ncc | cfe/lex.h | /*
* C compiler file cfe/lex.h:
* 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$
* Checkin $Date$
* Revising $Author$
*/
#ifndef _lex_h
#define _lex_h
#ifndef _defs_LOADED
# include "defs.h"
#endif
typedef struct SymInfo {
AEop sym;
union { char *s; int32 i; Symstr *sv; FloatCon *fc; Int64Con *i64; } a1;
union { int32 len, flag; } a2;
FileLine fl;
} SymInfo;
extern SymInfo curlex; /* Current token and aux. info. */
#ifdef EXTENSION_VALOF
extern bool inside_valof_block;
#endif
#ifdef TARGET_HAS_INLINE_ASSEMBLER
extern int asm_mode;
#endif
extern AEop nextsym(void);
extern void ungetsym(void); /* right inverse of nextsym */
extern int errs_on_this_sym;
extern AEop nextsym_for_hashif(void);
extern void lex_init(void);
extern void lex_beware_reinit(void);
extern void lex_reinit(void);
#ifdef CPLUSPLUS
/* for C++ or ANSI C; harmless here */
extern int lex_bodybegin(void); /* start save template def */
extern int lex_bodyend(void); /* end save template def */
extern int lex_savebody(void); /* save member fn def */
extern int lex_saveexpr(void);
extern void lex_openbody(int h, bool dup, bool record,
Symstr *old_sv, Symstr *new_sv);
/* re-read saved text */
extern void lex_closebody(void); /* end read + lose text */
/* for C++ ONLY; not used in ANSI C */
extern AEop lex_buffersym(void);
extern void lex_endbuffering(void);
extern Symstr *lex_replaceable_template_sym(Symstr *s);
#else
#define lex_bodybegin() 0
#define lex_bodyend() 0
#define lex_savebody() 0
#define lex_saveexpr() 0
#define lex_openbody(h,dup,rec,o,n) ((void)0)
#define lex_closebody() ((void)0)
#endif
#endif
/* end of cfe/lex.h */
|
stardot/ncc | armthumb/tooledit.c | /* ARM and Thumb C compilers: file tooledit.c
* Copyright (C) 1996 Advanced RISC Machines Limited. All rights reserved.
* Common tooledit code for arm and thumb.
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
#include <string.h>
#include <ctype.h>
#include "globals.h"
#include "cgdefs.h"
#include "jopcode.h"
#include "compiler.h"
#include "mcdpriv.h"
#include "toolenv.h"
#include "tooledit.h"
static bool IsReadOnly(ToolEnv *t, char const *name) {
#ifdef TARGET_IS_THUMB
if (StrEq(name, "-arch")
|| StrEq(name, "-cpu"))
return YES;
if (StrEq(name, "-apcs.32bit")
|| StrEq(name, "-apcs.softfp") || StrEq(name, "-apcs.fpis")
|| StrEq(name, "-apcs.fp") || StrEq(name, "-apcs.fpr"))
return YES;
#else
if (StrEq(name, "-arch"))
return !TE_HasValue(t, "-cpu", "#generic");
#endif
if (StrEq(name, "-gt"))
return TE_HasValue(t, ".debugtable", "=-dwarf");
return FALSE;
}
typedef struct { char const *name; char const *val; } EnvInit;
static EnvInit const pcc_implies[] = {
{".Wf", "=-Wf"}, {".Wd", "=-Wd"}, {".Wa", "=-Wa"}, {".Wn", "=-Wn"},
{".Wv", "=-Wv"}, {".Ep", "=-Ep"}, {".schar", "=-zc"},
{"-D__STDC__", "="},
{"-D__STDC_VERSION__", "="},
{0, 0}
};
static EnvInit const ansi_implies[] = {
{".Wf", "=-W+f"}, {".Wd", "=-W+d"}, {".Wa", "=-W+a"}, {".Wn", "=-W+n"},
{".Wv", "=-W+v"}, {".Ep", "=-E+p"}, {".schar", "=-z+c"},
{"-D__STDC__", "==1"},
{"-D__STDC_VERSION__", "==199409L"},
{0, 0}
};
static EnvInit const noswst_implies[] = { { "-D__APCS_NOSWST", "?"}, {0, 0} };
static EnvInit const swst_implies[] = { { "-D__APCS_NOSWST", "="}, {0, 0} };
static EnvInit const reent_implies[] = { { "-D__APCS_REENT", "?"}, {0, 0} };
static EnvInit const noreent_implies[] = { { "-D__APCS_REENT", "="}, {0, 0} };
static EnvInit const inter_implies[] = { { "-D__APCS_INTERWORK", "?"}, {0, 0} };
static EnvInit const nointer_implies[] = { { "-D__APCS_INTERWORK", "="}, {0, 0} };
static EnvInit const bi_implies[] = { { "-D__BIG_ENDIAN", "?"}, {0, 0} };
static EnvInit const li_implies[] = { { "-D__BIG_ENDIAN", "="}, {0, 0} };
static EnvInit const ft_implies[] = { { "-D__REVERSE_BF_PACKING", "?"}, {0, 0} };
static EnvInit const noft_implies[] = { { "-D__REVERSE_BF_PACKING", "="}, {0, 0} };
static EnvInit const dwarf_implies[] = { { "-gt", "#p" }, {0, 0} };
static EnvInit const b32_implies[] = { { "-D__APCS_32", "?"}, {0, 0} };
static EnvInit const nofp_implies[] = { { "-D__APCS_NOFP", "?"}, {0, 0} };
static EnvInit const softfp_implies[] = { { "-D__SOFTFP__", "?"}, { "-D__SOFT_DOUBLES__", "?"}, {0, 0} };
static EnvInit const softd_implies[] = { { "-D__SOFTFP__", "="}, { "-D__SOFT_DOUBLES__", "?"}, {0, 0} };
static EnvInit const nofpr_implies[] = { { "-D__PCS_FPREGARGS", "="}, {0, 0} };
#ifndef TARGET_IS_THUMB
static EnvInit const b26_implies[] = { { "-D__APCS_32", "="}, {0, 0} };
static EnvInit const fp_implies[] = { { "-D__APCS_NOFP", "="}, {0, 0} };
static EnvInit const hardfp_implies[] = { { "-D__SOFTFP__", "="}, { "-D__SOFT_DOUBLES__", "="}, {0, 0} };
static EnvInit const fpr_implies[] = { { "-D__PCS_FPREGARGS", "?"}, {0, 0} };
static EnvInit const amp_implies[] = { { "-apcs.softfp", "#/softdoubles"}, { "-apcs.fpr", "#/fpregargs"},
{ "-apcs.wide", "#/narrow"}, {0, 0} };
#endif
typedef struct { char const *val; EnvInit const *implies; } EnvValImplies;
static EnvValImplies const swst_vals[] = { {"#/swst", swst_implies}, {"#/noswst", noswst_implies}, {NULL, NULL} };
static EnvValImplies const reent_vals[] = { {"#/reent", reent_implies}, {"#/noreent", noreent_implies}, {NULL, NULL} };
static EnvValImplies const inter_vals[] = { {"#/interwork", inter_implies}, {"#/nointerwork", nointer_implies}, {NULL, NULL} };
static EnvValImplies const sex_vals[] = { {"=-bi", bi_implies}, {"=-li", li_implies}, {NULL, NULL} };
#ifndef TARGET_IS_THUMB
static EnvValImplies const softfp_vals[] = { {"#/softfp", softfp_implies}, {"#/hardfp", hardfp_implies},
{"#/softdoubles", softd_implies}, {NULL, NULL} };
static EnvValImplies const fpr_vals[] = { {"#/fpregargs", fpr_implies}, {"#/nofpregargs", nofpr_implies}, {NULL, NULL} };
static EnvValImplies const fp_vals[] = { {"#/fp", fp_implies}, {"#/nofp", nofp_implies}, {NULL, NULL} };
static EnvValImplies const b32_vals[] = { {"#/32", b32_implies}, {"#/26", b26_implies}, {NULL, NULL} };
static EnvValImplies const fpis_vals[] = { {"#/fpe3", NULL}, {"#/fpe2", NULL}, {NULL, NULL} };
static EnvValImplies const fpu_vals[] = { {"#fpa", NULL}, {"#amp", amp_implies}, {NULL, NULL} };
#endif
static EnvValImplies const ec_vals[] = { {"=-Ec", NULL}, {"=-E+c", NULL}, {NULL, NULL} };
static EnvValImplies const ef_vals[] = { {"=-Ef", NULL}, {"=-E+f", NULL}, {NULL, NULL} };
static EnvValImplies const el_vals[] = { {"=-El", NULL}, {"=-E+l", NULL}, {NULL, NULL} };
static EnvValImplies const ep_vals[] = { {"=-Ep", NULL}, {"=-E+p", NULL}, {NULL, NULL} };
static EnvValImplies const ez_vals[] = { {"=-Ez", NULL}, {"=-E+z", NULL}, {NULL, NULL} };
static EnvValImplies const wa_vals[] = { {"=-Wa", NULL}, {"=-W+a", NULL}, {NULL, NULL} };
static EnvValImplies const wd_vals[] = { {"=-Wd", NULL}, {"=-W+d", NULL}, {NULL, NULL} };
static EnvValImplies const wf_vals[] = { {"=-Wf", NULL}, {"=-W+f", NULL}, {NULL, NULL} };
static EnvValImplies const wg_vals[] = { {"=-Wg", NULL}, {"=-W+g", NULL}, {NULL, NULL} };
static EnvValImplies const wl_vals[] = { {"=-Wl", NULL}, {"=-W+l", NULL}, {NULL, NULL} };
static EnvValImplies const wm_vals[] = { {"=-Wm", NULL}, {"=-W+m", NULL}, {NULL, NULL} };
static EnvValImplies const wn_vals[] = { {"=-Wn", NULL}, {"=-W+n", NULL}, {NULL, NULL} };
static EnvValImplies const wp_vals[] = { {"=-Wp", NULL}, {"=-W+p", NULL}, {NULL, NULL} };
static EnvValImplies const ws_vals[] = { {"=-Ws", NULL}, {"=-W+s", NULL}, {NULL, NULL} };
static EnvValImplies const wu_vals[] = { {"=-Wu", NULL}, {"=-W+u", NULL}, {NULL, NULL} };
static EnvValImplies const wv_vals[] = { {"=-Wv", NULL}, {"=-W+v", NULL}, {NULL, NULL} };
static EnvValImplies const ff_vals[] = { {"=-ff", NULL}, {"=-f+f", NULL}, {NULL, NULL} };
static EnvValImplies const fa_vals[] = { {"=-fa", NULL}, {"=-f+a", NULL}, {NULL, NULL} };
static EnvValImplies const fv_vals[] = { {"=-fv", NULL}, {"=-f+v", NULL}, {NULL, NULL} };
static EnvValImplies const ft_vals[] = { {"=-ft", ft_implies}, {"=-f+t", noft_implies}, {NULL, NULL} };
static EnvValImplies const fk_vals[] = { {"=-fk", NULL}, {"=-f+k", NULL}, {NULL, NULL} };
static EnvValImplies const fw_vals[] = { {"=-fw", NULL}, {"=-f+w", NULL}, {NULL, NULL} };
static EnvValImplies const fy_vals[] = { {"=-fy", NULL}, {"=-f+y", NULL}, {NULL, NULL} };
static EnvValImplies const zc_vals[] = { {"=-zc", NULL}, {"=-z+c", NULL}, {NULL, NULL} };
static EnvValImplies const fz_vals[] = { {"=-fz", NULL}, {"=-f+z", NULL}, {NULL, NULL} };
static EnvValImplies const g_vals[] = { {"=-", NULL}, {"=+", NULL}, {NULL, NULL} };
static EnvValImplies const za_vals[] = { {"=0", NULL}, {"=1", NULL}, {NULL, NULL} };
static EnvValImplies const zap_vals[] = { {"=0", NULL}, {"=1", NULL}, {NULL, NULL} };
static EnvValImplies const zd_vals[] = { {"=0", NULL}, {"=1", NULL}, {NULL, NULL} };
static EnvValImplies const zo_vals[] = { {"=-z+o", NULL}, {"=-zo", NULL}, {NULL, NULL} };
typedef struct {
char const *name;
EnvValImplies const *val;
} KnownVals;
static KnownVals const known[] = {
{"-apcs.swst", swst_vals },
{"-apcs.reent", reent_vals },
{"-apcs.inter", inter_vals },
{".bytesex", sex_vals },
#ifndef TARGET_IS_THUMB
{"-apcs.softfp", softfp_vals },
{"-apcs.fpr", fpr_vals },
{"-apcs.fp", fp_vals },
{"-apcs.32bit", b32_vals },
{"-apcs.fpis", fpis_vals },
{ "-fpu", fpu_vals},
#endif
{".Ec", ec_vals },
{".Ef", ef_vals },
{".El", el_vals },
{".Ep", ep_vals },
{".Ez", ez_vals },
{".Wa", wa_vals },
{".Wd", wd_vals },
{".Wf", wf_vals },
{".Wg", wg_vals },
{".Wl", wl_vals },
{".Wm", wm_vals },
{".Wn", wn_vals },
{".Wp", wp_vals },
{".Ws", ws_vals },
{".Wu", wu_vals },
{".Wv", wv_vals },
{".ff", ff_vals },
{".fa", fa_vals },
{".fv", fv_vals },
{".ft", ft_vals },
{".-Isearch",fk_vals },
{".rolits", fw_vals },
{".enums", fy_vals },
{".schar", zc_vals },
{".swilr", fz_vals },
{"-g", g_vals },
{ "-za", za_vals },
{ "-zap", zap_vals },
{ "-zd", zd_vals },
{ ".areaperfn", zo_vals },
{NULL}
};
typedef struct {
char const *name;
struct { char const *val; EnvInit const *implies; } val;
} FixedVals;
static FixedVals const fixedvals[] = {
#ifdef TARGET_IS_THUMB
{"-cpu", {"#ARM7TM", NULL} },
{"-arch", {"#4T", NULL} },
{"-apcs.softfp", {"#/softfp", softfp_implies} },
{"-apcs.fpr", {"#/nofpregargs", nofpr_implies} },
{"-apcs.fp", {"#/nofp", nofp_implies} },
{"-apcs.32bit", {"#/32", b32_implies} },
{"-apcs.fpis", {"#/fpe3", NULL} },
#endif
{NULL, {NULL, NULL} }
};
static bool CheckInsert(ToolEnv *t, char const *name, char const *val) {
/* Insert <'name', 'val'> into 't', returning TRUE if the value
* associated with 'name' is changed thereby.
*/
char const *oldval = toolenv_lookup(t, name);
if (oldval == NULL) {
if (StrEq(val, "=") || StrEq(val, "#"))
return FALSE;
/* Attempting to delete something already absent from the env. */
} else if (StrEq(oldval, val))
return FALSE;
tooledit_insert(t, name, val);
return TRUE;
}
static bool SetDefaults(ToolEnv *t, EnvInit const *p) {
bool changed = NO;
for (; p->name != NULL; p++)
changed = changed | CheckInsert(t, p->name, p->val);
return changed;
}
static bool CheckRange(char const *val, Uint low, Uint high) {
if (isdigit(val[0])) {
char *endp;
uint32 n = (uint32)strtol(val, &endp, 0);
if (endp[0] == 0 && low <= n && n <= high) return YES;
}
return NO;
}
static bool CheckAlignValue(char const *val) {
if (isdigit(val[0])) {
char *endp;
uint32 n = (uint32)strtol(val, &endp, 0);
if (endp[0] == 0 && n > 0 && n <= 8 && (n & (0-n)) == n) return YES;
}
return NO;
}
static void TE_ReconstructEtc(ToolEnv *t);
static void TargetDefine(ToolEnv *t, char const *s1, char const *s2, bool define) {
if (s2[0] != 0) {
char b[64];
sprintf(b, "-D__TARGET_%s_%s", s1, s2);
toolenv_insert(t, b, define ? "?" : "=");
}
}
ToolEdit_InsertStatus tooledit_insertwithjoin(
ToolEnv *t, char const *name, int join, char const *value) {
EnvInit const *implies = NULL;
ToolEdit_InsertStatus status = TE_OK;
if (IsReadOnly(t, name)) {
/* If a toolenv entry is read-only, we still allow it to be written
* provided the value is the correct one (to avoid a problem with
* setting the default values, which go through here so that
* consequential changes are done in just one place).
*/
FixedVals const *p;
for (p = fixedvals;; p++)
if (p->name == NULL)
return TE_Failed;
else if (StrEq(name, p->name)) {
if (join != p->val.val[0] || !StrEq(value, &p->val.val[1]))
return TE_Failed;
implies = p->val.implies;
break;
}
}
if (join != '=' && join != '#') {
if (join != '?' || value[0] != 0) return TE_Failed;
}
#ifndef TARGET_IS_THUMB
if (StrEq(name, "-cpu") || StrEq(name, "-arch")) {
char a[32], c[32];
Processor const *cpu;
char const *newcpu;
{ char const *oldarch = toolenv_lookup(t, "-arch");
char const *oldcpu = toolenv_lookup(t, "-cpu");
if (oldarch == NULL)
a[0] = 0;
else
strcpy(a, oldarch+1);
if (oldcpu == NULL)
c[0] = 0;
else
strcpy(c, oldcpu+1);
}
if (StrEq(name, "-cpu")) {
if (join == '#' && StrEq(value, "generic")) {
/* Setting cpu to #generic does not actually alter anything
* else in the environment, but it does change -arch from
* read-only to writable.
*/
cpu = LookupArchitecture(a);
toolenv_insert(t, name, "#generic");
status = TE_OKBut;
newcpu = value;
} else {
cpu = LookupProcessor(value);
if (cpu == NULL) return TE_Failed;
/* Changing the cpu from generic may not change anything else
* in the environment, but it does change -arch from writable
* to read-only.
*/
if (StrEq(c, "#generic")) status = TE_OKBut;
if (toolenv_insertwithjoin(t, name, join, value) != 0) return TE_Failed;
if (StrEq(value, "SA1500")) {
tooledit_insert(t, "-fpu", "#amp");
status = TE_OKBut;
}
newcpu = value;
}
} else /*(StrEq(name, "-arch"))*/ {
if (!TE_HasValue(t, "-cpu", "#generic")) return TE_Failed;
cpu = LookupArchitecture(value);
newcpu = c;
}
if (cpu != NULL && !StrEq(a, cpu->arch+1)) {
TargetDefine(t, "ARCH", a, NO);
TargetDefine(t, "ARCH", cpu->arch+1, YES);
TargetDefine(t, "FEATURE", "HALFWORD", cpu->flags & PROCESSOR_HAS_HALFWORDS);
TargetDefine(t, "FEATURE", "THUMB", cpu->flags & PROCESSOR_HAS_THUMB);
TargetDefine(t, "FEATURE", "MULTIPLY", cpu->flags & PROCESSOR_HAS_MULTIPLY);
status = TE_OKBut;
}
if (!StrEq(c, newcpu)) {
TargetDefine(t, "CPU", c, NO);
TargetDefine(t, "CPU", newcpu, YES);
status = TE_OKBut;
}
toolenv_insert(t, "-arch", cpu->arch);
status = TE_OKBut;
return status;
} else if (StrEq(name, "-fpu")) {
char const *oldfpu = toolenv_lookup(t, "-fpu");
if (oldfpu != NULL) {
if (StrEq(oldfpu+1, value)) return TE_OK;
TargetDefine(t, "FPU", oldfpu+1, NO);
}
status = TE_OKBut;
TargetDefine(t, "FPU", value, YES);
/* And drop through to insert (with implications) through generic code */
} else
#endif
if (StrEq(name, ".lang")) {
if (join == '=' && StrnEq(value, "-pcc", 4))
implies = pcc_implies;
else
implies = ansi_implies;
} else if (StrEq(name, ".debugtable")) {
if (join == '=' && StrEq(value, "-dwarf"))
implies = dwarf_implies;
/* Read-only status of -gt may have changed */
status = TE_OKBut;
} else if (StrEq(name, "-zi")) {
if (join != '=' || !CheckRange(value, 1, 4)) return TE_Failed;
} else if (StrEq(name, "-zr")) {
if (join != '=' || !CheckRange(value, LDM_REGCOUNT_MIN_DEFAULT, LDM_REGCOUNT_MAX_DEFAULT))
return TE_Failed;
} else if (StrEq(name, "-zas") || StrEq(name, "-zat")) {
if (join != '=' || !CheckAlignValue(value))
return TE_Failed;
}
if (implies == NULL) {
KnownVals const *kv = known;
for (; kv->name != NULL; kv++)
if (StrEq(name, kv->name)) {
EnvValImplies const *valp = kv->val;
for (; ; valp++)
if (valp->val == NULL)
return TE_Failed;
else if (join == valp->val[0] && StrEq(value, &valp->val[1])) {
implies = valp->implies;
break;
}
break;
}
}
if (toolenv_insertwithjoin(t, name, join, value) != 0) return TE_Failed;
if (StrEq(name, ".etc")) {
TE_DecodeArgumentLine(t, value, YES);
TE_ReconstructEtc(t);
return TE_OKBut;
}
if (implies != NULL && SetDefaults(t, implies)) return TE_OKBut;
return status;
}
ToolEdit_InsertStatus tooledit_insert(
ToolEnv *t, char const *name, char const *value) {
return tooledit_insertwithjoin(t, name, value[0], &value[1]);
}
char const *tooledit_lookup(
ToolEnv *t, char const *name, bool *readonly) {
/* lookup is simply toolenv_lookup, with a thin veneer to return */
/* a readonly value. */
char const *val = toolenv_lookup(t, name);
if (val != NULL) {
*readonly = IsReadOnly(t, name);
}
return val;
}
static char const * const langname[] = {
"=-pcc -strict",
"=-pcc",
"=-ansi",
"=-ansi -fc",
"=-ansi -strict",
#ifdef CPLUSPLUS
"=-cpp",
"=-cpp -fc",
"=-cfront",
"=-cfront -fc",
#endif
NULL
};
#ifdef TARGET_IS_THUMB
static int valuecount_docpu(void) {
return 1;
}
static int enumvalues_docpu(ToolEnvItemFn *f, void *arg) {
return f(arg, "-cpu", "#ARM7TM");
}
static int valuecount_doarch(void) {
return 1;
}
static int enumvalues_doarch(ToolEnvItemFn *f, void *arg) {
return f(arg, "-arch", "#4T");
}
#else
static int countvalues_cpus(void *arg, Processor const *cpu) {
(*(int *)arg)++;
IGNORE(cpu);
return 0;
}
static int valuecount_docpu(void) {
int n = 1; /* #generic handled specially */
EnumerateProcessors(countvalues_cpus, &n);
return n;
}
typedef struct { ToolEnvItemFn *f; void *arg; } EnumValues_Cpu_Rec;
static int enumvalues_cpus(void *arg, Processor const *cpu) {
EnumValues_Cpu_Rec *ep = (EnumValues_Cpu_Rec *)arg;
return ep->f(ep->arg, "-cpu", cpu->name);
}
static int enumvalues_docpu(ToolEnvItemFn *f, void *arg) {
EnumValues_Cpu_Rec er;
er.arg = arg; er.f = f;
f(arg, "-cpu", "#generic");
return EnumerateProcessors(enumvalues_cpus, &er);
}
typedef struct { int n; char const *name[16]; } Enum_Arch_Rec;
static int enum_arch(void *arg, Processor const *cpu) {
Enum_Arch_Rec *ep = (Enum_Arch_Rec *)arg;
int i;
for (i = 0; i < ep->n; i++) {
if (StrEq(ep->name[i], cpu->arch))
return 0;
}
ep->name[i] = cpu->arch;
ep->n = i+1;
return 0;
}
static int valuecount_doarch(void) {
Enum_Arch_Rec er;
er.n = 0;
EnumerateProcessors(enum_arch, &er);
return er.n;
}
static int enumvalues_doarch(ToolEnvItemFn *f, void *arg) {
Enum_Arch_Rec er;
int i;
er.n = 0;
EnumerateProcessors(enum_arch, &er);
for (i = 0; i < er.n; i++) {
int rc = f(arg, "-arch", er.name[i]);
if (rc != 0) return rc;
}
return 0;
}
#endif
int tooledit_valuecount(ToolEnv *t, char const *name) {
IGNORE(t);
if (StrEq(name, "-cpu"))
return valuecount_docpu();
if (StrEq(name, "-cpu")) {
return valuecount_doarch();
} else if (StrEq(name, ".lang")) {
int i = 0;
for (; langname[i] != NULL; i++) continue;
return i;
}
return -1;
}
int tooledit_enumeratevalues(
ToolEnv *t, char const *name, ToolEnvItemFn *f, void *arg) {
IGNORE(t);
if (StrEq(name, "-cpu"))
return enumvalues_docpu(f, arg);
else if (StrEq(name, "-arch"))
return enumvalues_doarch(f, arg);
else if (StrEq(name, ".lang")) {
int i = 0;
for (; langname[i] != NULL; i++) {
int rc = f(arg, name, langname[i]);
if (rc != 0) return rc;
}
return 0;
}
return -1;
}
typedef struct {
ToolEnv *t;
ToolEdit_EnumFn *f;
void *arg;
char const *prefix;
size_t prefix_len;
} TE_EnumRec;
static int TE_EnumFn(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))
return 0;
return tp->f(tp->arg, name, val, IsReadOnly(tp->t, name));
}
int tooledit_enumerate(
ToolEnv *t, char const *prefix, ToolEdit_EnumFn *f, void *arg) {
if (StrEq(prefix, "-I.") || StrEq(prefix, "-J.")) {
return Tool_OrderedEnvEnumerate(t, prefix, f, arg);
} else {
TE_EnumRec tr;
tr.t = t; tr.f = f; tr.arg = arg;
tr.prefix = prefix; tr.prefix_len = strlen(prefix);
return toolenv_enumerate(t, TE_EnumFn, &tr);
}
}
typedef struct {
char *buf;
int len, maxlen;
} BufDesc;
typedef struct {
BufDesc b;
char const *etc;
char const *cpu;
char const *arch;
uint32 fmap[2], Wmap[2], Emap[2];
Uint napcs;
char const *apcsqual[16];
} TE_GCLRec;
static void AddArgument(
BufDesc *bd, char const *name, const char *val, bool protectspaces) {
char const *dot = strchr(name, '.');
size_t keylen = (dot == NULL
|| (!isalnum(dot[1])
&& dot[1] != '-')) ? strlen(name)
: dot - name;
int newlen = bd->len;
int jointype = val[0];
int spacecount = 0;
size_t vallen = strlen(val);
if (newlen != 0) newlen++; /* a separating space */
newlen += keylen;
if (jointype != '?') {
if (protectspaces) {
char const *p = &val[1];
for (; *p != 0; p++)
if (isspace(*p)) {
spacecount++;
break;
}
if (name[0] == '.' && spacecount == 1)
spacecount = 0;
}
newlen += vallen;
if (jointype == '=') newlen--; /* name and value concatenated */
if (spacecount > 0) newlen += 2;
}
if (newlen + 1 <= bd->maxlen) { /* allow for zero termination */
int len = bd->len;
char *b = bd->buf;
if (len != 0) b[len++] = ' ';
if (jointype == '=' && spacecount > 0) b[len++] = '"';
memcpy(&b[len], name, keylen); len += keylen;
if (jointype == '#') {
b[len++] = ' ';
if (spacecount > 0) b[len++] = '"';
}
if (jointype != '?') {
memcpy(&b[len], &val[1], vallen-1);
len += vallen-1;
if (spacecount > 0) b[len++] = '"';
}
}
bd->len = newlen;
}
static Uint MapChars(char *b, uint32 w, Uint ix) {
int ch = 'a';
for (; w != 0; w = w >> 1, ch++)
if (w & 1) b[ix++] = ch;
return ix;
}
static void AddMaps(TE_GCLRec *tp, int type, uint32 *map) {
char b[64];
Uint i = 0;
if (map[0] == 0 && map[1] == 0) return;
b[0] = '='; b[1] = '-'; b[2] = type;
i = MapChars(b, map[0], 3);
if (map[1] != 0) {
b[i] = '+';
i = MapChars(b, map[1], i+1);
}
b[i] = 0;
AddArgument(&tp->b, ".dummy", b, FALSE);
}
static void SwitchFlag(TE_GCLRec *tp, int ix, Uint type, int ch) {
uint32 bit = 1 << (ch - 'a');
if (type == 'f') tp->fmap[ix] |= bit;
else if (type == 'E') tp->Emap[ix] |= bit;
else tp->Wmap[ix] |= bit;
}
static int Te_GCLFn(void *arg, const char *name, const char *val) {
TE_GCLRec *tp = (TE_GCLRec *)arg;
char const *defaultval = toolenv_lookup(cc_default_env, name);
if (defaultval != NULL && StrEq(val, defaultval))
return 0;
if (StrEq(name, ".etc")) {
tp->etc = val;
} else if (StrEq(name, "-cpu")) {
tp->cpu = val;
} else if (StrEq(name, "-arch")) {
tp->arch = val;
} else if (StrnEq(name, "-apcs.", 6)) {
tp->apcsqual[tp->napcs++] = &val[1];
} else if (!StrnEq(name, "-I.", 3) &&
!StrnEq(name, "-J.", 3) &&
!StrnEq(name, "-D", 2)) {
if (name[0] == '.' && val[0] == '=' && val[1] == '-') {
int type = val[2];
if (type == 'f' || type == 'E' || (type == 'W' && val[3] != 0)) {
if (val[4] == 0) {
SwitchFlag(tp, 0, type, val[3]);
return 0;
} else if (val[3] == '+' && val[5] == 0) {
SwitchFlag(tp, 1, type, val[4]);
return 0;
}
}
}
AddArgument(&tp->b, name, val, TRUE);
}
return 0;
}
static int Te_GCLFnI(void *arg, char const *name, char const *val, bool readonly) {
TE_GCLRec *tp = (TE_GCLRec *)arg;
char const *defaultval = toolenv_lookup(cc_default_env, name);
IGNORE(readonly);
if (defaultval == NULL || !StrEq(val, defaultval))
AddArgument(&tp->b, name, val, TRUE);
return 0;
}
int tooledit_getcommandline(ToolEnv *t, char *buf, int maxlen) {
TE_GCLRec tr;
tr.etc = tr.cpu = NULL; tr.arch = NULL;
tr.b.buf = buf; tr.b.len = 0; tr.b.maxlen = maxlen;
tr.fmap[0] = tr.fmap[1] = 0;
tr.Emap[0] = tr.Emap[1] = 0;
tr.Wmap[0] = tr.Wmap[1] = 0;
tr.napcs = 0;
toolenv_enumerate(t, Te_GCLFn, &tr);
if (tr.napcs != 0) {
char b[256];
Uint i = 0;
b[0] = '#'; b[1] = 0;
for (; i < tr.napcs; i++) strcat(b, tr.apcsqual[i]);
AddArgument(&tr.b, "-apcs", b, TRUE);
}
if (tr.cpu != NULL && !StrEq(tr.cpu, "#generic"))
AddArgument(&tr.b, "-cpu", tr.cpu, TRUE);
else if (tr.arch != NULL)
AddArgument(&tr.b, "-arch", tr.arch, TRUE);
AddMaps(&tr, 'f', tr.fmap);
AddMaps(&tr, 'W', tr.Wmap);
AddMaps(&tr, 'E', tr.Emap);
tooledit_enumerate(t, "-D", Te_GCLFnI, &tr);
tooledit_enumerate(t, "-I.", Te_GCLFnI, &tr);
tooledit_enumerate(t, "-J.", Te_GCLFnI, &tr);
if (tr.etc != NULL)
AddArgument(&tr.b, "", tr.etc, FALSE);
if (tr.b.len < maxlen) buf[tr.b.len] = 0;
return tr.b.len+1;
}
typedef struct {
ToolEnv *t;
size_t n, size;
EnvInit *p;
} MakeEtcRec;
static int MakeEtc(void *arg, char const *name, char const *val) {
MakeEtcRec *mp = (MakeEtcRec *)arg;
if (!StrEq(name, ".etc") && !StrEq(name, ".defaulttime")
&& !Tool_Configurable(mp->t, name)
&& cc_default_env != NULL) {
char const *defaultval = toolenv_lookup(cc_default_env, name);
if (defaultval == NULL || !StrEq(val, defaultval)) {
if (mp->n == mp->size) {
mp->size += 10;
mp->p = (EnvInit *)realloc(mp->p, mp->size * sizeof(EnvInit));
}
mp->p[mp->n].name = name;
mp->p[mp->n].val = val;
mp->n++;
}
}
return 0;
}
static void TE_ReconstructEtc(ToolEnv *t) {
MakeEtcRec mr;
mr.t = t; mr.n = 0; mr.size = 10;
mr.p = (EnvInit *)malloc(10 * sizeof(EnvInit));
toolenv_enumerate(t, MakeEtc, &mr);
if (mr.n == 0) {
toolenv_insert(t, ".etc", "=");
} else {
BufDesc bd;
size_t i;
bd.buf = NULL; bd.len = 0; bd.maxlen = 0;
for (i = 0; i < mr.n; i++)
AddArgument(&bd, mr.p[i].name, mr.p[i].val, TRUE);
bd.buf = (char *)malloc(bd.len+1);
bd.maxlen = bd.len+1; bd.len = 0;
for (i = 0; i < mr.n; i++)
AddArgument(&bd, mr.p[i].name, mr.p[i].val, TRUE);
bd.buf[bd.len] = 0;
toolenv_insertwithjoin(t, ".etc", '=', bd.buf);
for (i = 0; i < mr.n; i++)
toolenv_insert(t, mr.p[i].name, "=");
free(bd.buf);
}
free(mr.p);
}
void TE_NormaliseEtc(ToolEnv *t) {
char const *etc = toolenv_lookup(t, ".etc");
if (etc != NULL) TE_DecodeArgumentLine(t, &etc[1], YES);
TE_ReconstructEtc(t);
}
/* end of tooledit.c */
|
stardot/ncc | mip/defaults.h | <gh_stars>0
/*
* mip/defaults.h - default sizes of things, debugging options etc...
* Copyright (C) Codemist Ltd., 1989-1992.
* Copyright (C) Advanced RISC Machines Limited, 1992.
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$ Codemist 9
* Checkin $Date$
* Revising $Author$
*/
/* This file is included after host.h, options.h and target.h and */
/* defaults any TARGET/LANGUAGE details left undefined by these files. */
/* Hence DO NOT MODIFY THIS FILE, but modify (e.g.) target.h instead. */
/* Possibilities currently supported are in comments. */
/* Not all possibilities are supported on all targets. */
#ifndef _defaults_LOADED
#define _defaults_LOADED 1
#ifndef TARGET_MACHINE
#error target.h did not specify TARGET_MACHINE
#endif
#ifndef TARGET_SYSTEM
#error options.h and target.h did not specify TARGET_SYSTEM (Unix assumed)
#define TARGET_SYSTEM "Unix"
#define TARGET_IS_UNIX 1
#endif
#ifndef TOOL
# ifdef CPLUSPLUS
# ifdef TARGET_IS_THUMB
# define TOOL tcpp
# else
# ifdef TARGET_IS_ARM
# define TOOL armcpp
# else
# define TOOL cpp
# endif
# endif
# else
# ifdef TARGET_IS_THUMB
# define TOOL tcc
# else
# ifdef TARGET_IS_ARM
# define TOOL armcc
# else
# define TOOL cc
# endif
# endif
# endif /* CPLUSPLUS */
#endif
#ifndef SIMPLIFY_OPTIMISE_CHAR_AND_SHORT_ARITHMETIC
# ifndef REGALLOC_CHAR_OPTIMISER
# define REGALLOC_CHAR_OPTIMISER 1
/* the currently preferred tool for the job (lacking the obscure */
/* bugs in the code in simplify.c) */
# endif
#endif
/* The following number determines the size (in bytes) threshold above */
/* which tentative (top level) definitions are provisionally allocated */
/* to BSS. This is only used if TARGET_HAS_BSS is set. Note that it */
/* may be set to 0, but this produces worse code for: */
/* int a,b; f() { return a+b; } */
/* which then requires two address constants for (since just one */
/* may LATER find its way to the data segment by (e.g.) "int a=1;" */
/* Allocating both a,b to datasegment initially allows one address */
/* constant to suffice. */
#ifndef BSS_THRESHOLD
/* ECN: Changed from 100 to 8 (Apr 95) */
# define BSS_THRESHOLD_DEFAULT 8
# define BSS_THRESHOLD bss_threshold
#endif
#ifndef NTEMPREGS /* gentle upwards compatibility */
# define NTEMPREGS 0
# define R_T1 R_A1 /* not used if NTEMPREGS=0. */
#endif
#ifndef TARGET_SHARES_INTEGER_AND_FP_REGISTERS
#ifndef NFLTTEMPREGS /* gentle upwards compatibility */
# define NFLTTEMPREGS 0
# define R_FT1 R_FA1 /* not used if NFLTTEMPREGS=0. */
#endif
#ifndef NFLTREGS /* gentle upwards compatibility */
# define NFLTREGS (NFLTARGREGS+NFLTVARREGS+NFLTTEMPREGS)
#endif
#endif
/* R_P1 is the first argument register seen from the callee side. */
/* Unless on a register-windows machine R_P1 = R_A1. */
#ifndef R_P1
# define R_P1 R_A1
#endif
#ifndef R_FA1
# define R_FA1 R_F0
#endif
#ifndef R_FP1
# define R_FP1 R_FA1
#endif
/* R_A1result and R_P1result similarly give names for the result reg. */
#ifndef R_A1result
# define R_A1result R_A1
#endif
#ifndef R_P1result
# define R_P1result R_A1result
#endif
#ifndef R_FA1result
# define R_FA1result R_FA1
#endif
#ifndef R_FP1result
# define R_FP1result R_FA1result
#endif
#ifdef TARGET_R0_ALWAYS_ZERO /* obsolete parameterisation */
# define R_ZERO 0
# define TARGET_HAS_CONST_R_ZERO
#endif
#ifndef TARGET_SPECIAL_ARG_REG
# ifdef TARGET_STRUCT_RESULT_REGISTER
# define TARGET_SPECIAL_ARG_REG TARGET_STRUCT_RESULT_REGISTER
# endif
#endif
#ifndef sizeof_short
# define sizeof_short 2 /* 2, 4 */
#endif
#ifndef sizeof_int
# define sizeof_int 4 /* 2, 4 */
#endif
#ifndef sizeof_long
# define sizeof_long 4 /* 4 */
#endif
#ifndef sizeof_longlong
# define sizeof_longlong 8 /* 4, 8 */
#endif
#ifndef sizeof_ptr
# define sizeof_ptr sizeof_int /* sizeof_int, 4 */
#endif
#ifndef sizeof_float
# define sizeof_float 4 /* 4 */
#endif
#ifndef sizeof_double
# define sizeof_double 8 /* 8 */
#endif
#ifndef sizeof_ldble
# define sizeof_ldble sizeof_double /* 8 */
#endif
#ifdef MIN_ALIGNMENT_CONFIGURABLE
extern int32 alignof_struct_val;
# define alignof_struct alignof_struct_val
# ifndef alignof_struct_default
# define alignof_struct_default 4
# endif
extern int32 alignof_toplevel_static_var;
# define alignof_toplevel_static alignof_toplevel_static_var
# ifndef alignof_toplevel_static_default
# ifdef TARGET_HAS_NATURALLY_ALIGNED_STATICS
# define alignof_toplevel_static_default 1
# else
# define alignof_toplevel_static_default 4
# endif
# endif
#endif
#ifndef alignof_short
# define alignof_short sizeof_short /* 2, 4 */
#endif
#ifndef alignof_int
# define alignof_int sizeof_int /* 2, 4 */
#endif
#ifndef alignof_long
# define alignof_long sizeof_long /* 4 */
#endif
#ifndef alignof_longlong
# define alignof_longlong 4 /* 4, 8 */
#endif
#ifndef alignof_ptr
# define alignof_ptr sizeof_ptr /* 4, 8 */
#endif
#ifndef alignof_float
# define alignof_float sizeof_float /* 4 */
#endif
#ifndef alignof_double
# define alignof_double 4 /* 2, 4, 8 */
#endif
#ifndef alignof_ldble
# define alignof_ldble alignof_double /* 8 */
#endif
#ifndef alignof_struct
# define alignof_struct 4 /* 4, but stricter member alignment wins */
#endif
#ifndef alignof_toplevel_auto /* somewhat a hack. */
# define alignof_toplevel_auto 4 /* min alignment for named things */
#endif
#ifndef alignof_toplevel_static
# define alignof_toplevel_static 4
#endif
#ifndef alignof_literal
# define alignof_literal 4
#endif
#ifndef alignof_member /* must be <= alignof_struct */
# define alignof_member 1 /* min alignment for members */
#endif
#ifndef alignof_max /* somewhat a hack. */
# define alignof_max alignof_double /* a form of quantum_max */
#endif
#define MAXBITSIZE (8*sizeof_int) /* (was 32) sizeof_long too maybe one day! */
#ifndef TARGET_VTAB_ELTSIZE
# define TARGET_VTAB_ELTSIZE 12
#endif
#ifndef TARGET_ADDRESSES_UNSIGNED
# define TARGET_ADDRESSES_UNSIGNED 0 /* 0, 1 */
#endif
#ifndef TARGET_RIGHTSHIFT
# define TARGET_RIGHTSHIFT(a,b) ((a)>>(b)) /* i.e. same as host. */
#endif
#ifndef signed_rightshift_
# define signed_rightshift_(a,b) \
((int32)((int32)(a)>=0 ? (a)>>(b) : ~((~(unsigned32)(a)) >> (b))))
#endif
#ifndef TARGET_NULL_BITPATTERN
# define TARGET_NULL_BITPATTERN 0 /* bit pattern for (void *)0. */
#endif
#ifndef TARGET_LACKS_MULDIV_LITERALS
#if defined(TARGET_LACKS_MULTIPLY_LITERALS) && defined(TARGET_LACKS_DIVIDE_LITERALS)
#define TARGET_LACKS_MULDIV_LITERALS 1
#endif
#endif
#ifdef TARGET_LACKS_MULDIV_LITERALS
#undef TARGET_LACKS_MULTIPLY_LITERALS
#define TARGET_LACKS_MULTIPLY_LITERALS 1
#undef TARGET_LACKS_DIVIDE_LITERALS
#define TARGET_LACKS_DIVIDE_LITERALS 1
#endif
#ifdef TARGET_LDRK_MAX
# ifndef TARGET_LDRBK_MAX
# define TARGET_LDRBK_MAX TARGET_LDRK_MAX
# define TARGET_LDRBK_MIN TARGET_LDRK_MIN
# endif
# ifndef TARGET_LDRWK_MAX
# define TARGET_LDRWK_MAX TARGET_LDRK_MAX
# define TARGET_LDRWK_MIN TARGET_LDRK_MIN
# endif
# ifndef TARGET_LDRLK_MAX
# define TARGET_LDRLK_MAX TARGET_LDRK_MAX
# define TARGET_LDRLK_MIN TARGET_LDRK_MIN
# endif
# ifndef TARGET_LDRFK_MAX
# define TARGET_LDRFK_MAX TARGET_LDRK_MAX
# define TARGET_LDRFK_MIN TARGET_LDRK_MIN
# endif
# ifndef TARGET_LDRDK_MAX
# define TARGET_LDRDK_MAX TARGET_LDRFK_MAX
# define TARGET_LDRDK_MIN TARGET_LDRFK_MIN
# endif
#endif
#ifdef TARGET_SP_LDRK_MAX
# ifndef TARGET_SP_LDRBK_MAX
# define TARGET_SP_LDRBK_MAX TARGET_SP_LDRK_MAX
# define TARGET_SP_LDRBK_MIN TARGET_SP_LDRK_MIN
# endif
# ifndef TARGET_SP_LDRWK_MAX
# define TARGET_SP_LDRWK_MAX TARGET_SP_LDRK_MAX
# define TARGET_SP_LDRWK_MIN TARGET_SP_LDRK_MIN
# endif
# ifndef TARGET_SP_LDRLK_MAX
# define TARGET_SP_LDRLK_MAX TARGET_SP_LDRK_MAX
# define TARGET_SP_LDRLK_MIN TARGET_SP_LDRK_MIN
# endif
# ifndef TARGET_SP_LDRFK_MAX
# define TARGET_SP_LDRFK_MAX TARGET_SP_LDRK_MAX
# define TARGET_SP_LDRFK_MIN TARGET_SP_LDRK_MIN
# endif
# ifndef TARGET_SP_LDRDK_MAX
# define TARGET_SP_LDRDK_MAX TARGET_SP_LDRFK_MAX
# define TARGET_SP_LDRDK_MIN TARGET_SP_LDRFK_MIN
# endif
#endif
#ifndef TARGET_MAX_FRAMESIZE
#define TARGET_MAX_FRAMESIZE 256
#endif
#ifndef MEMCPYQUANTUM
/* These might look like things that properly belong in cgdefs.h or */
/* jopcode.h, but unfortunately they're wanted by the front end to */
/* determine whether functions return structure results in registers */
/* (and so receive a result pointer as an extra first argument). This */
/* is needed because of C++ treatment of return struct-returning-fn() */
/* The following lines highlight the dependency on alignof_struct==4 of */
/* code for struct-return in registers. */
# ifdef TARGET_IS_ADENART
# define MEMCPYREG DBLREG
# define MEMCPYQUANTUM 8
# else
# define MEMCPYREG INTREG
# define MEMCPYQUANTUM 4
# endif
#endif
#ifndef sizeof_wchar /* wide string element type. */
/* The following lines serve to make the compiler use wchar_t == int. */
/* This happens works with both 16 and 32 bit target ints. */
# define sizeof_wchar sizeof_int
# define wchar_typespec bitoftype_(s_int)
# define NUM_WCHAR NUM_INT /* for lex.c */
#endif
#ifndef LANGUAGE
# ifdef PASCAL
# define LANGUAGE "Pascal"
# define NO_INSTORE_FILES 1
# define PASCAL_OR_FORTRAN 1
# endif
# ifdef CPLUSPLUS
# define LANGUAGE "C++"
# endif
# ifdef FORTRAN
# define LANGUAGE "Fortran"
# define NO_INSTORE_FILES 1
# define PASCAL_OR_FORTRAN 1
# endif
#endif
#ifndef LANGUAGE
# define LANGUAGE "C"
#endif
#ifndef DRIVER_OPTIONS
#error options.h did not specify DRIVER_OPTIONS ('none' assumed)
/* possible example setting: { "__unix", "__manufacturer" } */
# define DRIVER_OPTIONS { NULL }
#endif
/*
* Note that ENABLE_ALL does not imply ENABLE_MAPSTORE any more, since
* the mapstore option is but rarely implemented, and not very useful
* at that! If needed it must be explicitly set in options.h
*/
#ifdef ENABLE_ALL
# ifndef ENABLE_LEX
# define ENABLE_LEX 1
# endif
# ifndef ENABLE_SYN
# define ENABLE_SYN 1
# endif
# ifndef ENABLE_BIND
# define ENABLE_BIND 1
# endif
# ifndef ENABLE_PP
# define ENABLE_PP 1
# endif
# ifndef ENABLE_AETREE
# define ENABLE_AETREE 1
# endif
# ifndef CALLABLE_COMPILER
# ifndef ENABLE_CG
# define ENABLE_CG 1
# endif
# ifndef ENABLE_TYPE
# define ENABLE_TYPE 1
# endif
# ifndef ENABLE_REGS
# define ENABLE_REGS 1
# endif
# ifndef ENABLE_OBJ
# define ENABLE_OBJ 1
# endif
# ifndef ENABLE_FNAMES
# define ENABLE_FNAMES 1
# endif
# ifndef ENABLE_FILES
# define ENABLE_FILES 1
# endif
# ifndef ENABLE_LOOP
# define ENABLE_LOOP 1
# endif
# ifndef ENABLE_Q
# define ENABLE_Q 1
# endif
# ifndef ENABLE_STORE
# define ENABLE_STORE 1
# endif
# ifndef ENABLE_2STORE
# define ENABLE_2STORE 1
# endif
# ifndef ENABLE_SPILL
# define ENABLE_SPILL 1
# endif
# ifndef ENABLE_DATA
# define ENABLE_DATA 1
# endif
# ifndef ENABLE_CSE
# define ENABLE_CSE 1
# endif
# ifndef ENABLE_LOCALCG
# define ENABLE_LOCALCG 1
# endif
# ifndef ENABLE_TEMPLATE
# define ENABLE_TEMPLATE 1
# endif
# ifndef ENABLE_SR
# define ENABLE_SR 1
# endif
# endif
#endif
#ifdef ENABLE_LEX
# define DEBUG_LEX 0x1L
#else
# define DEBUG_LEX 0
#endif
#ifdef ENABLE_SYN
# define DEBUG_SYN 0x2L
#else
# define DEBUG_SYN 0
#endif
#ifdef ENABLE_CG
# define DEBUG_CG 0x4L
#else
# define DEBUG_CG 0
#endif
#ifdef ENABLE_BIND
# define DEBUG_BIND 0x8L
#else
# define DEBUG_BIND 0
#endif
#ifdef ENABLE_TYPE
# define DEBUG_TYPE 0x10L
#else
# define DEBUG_TYPE 0
#endif
#ifdef ENABLE_REGS
# define DEBUG_REGS 0x20L
#else
# define DEBUG_REGS 0
#endif
#ifdef ENABLE_OBJ
# define DEBUG_OBJ 0x40L
#else
# define DEBUG_OBJ 0
#endif
#ifdef ENABLE_FNAMES
# define DEBUG_FNAMES 0x100L
#else
# define DEBUG_FNAMES 0
#endif
#ifdef ENABLE_FILES
# define DEBUG_FILES 0x200L
#else
# define DEBUG_FILES 0
#endif
#ifdef ENABLE_LOOP
# define DEBUG_LOOP 0x400L
#else
# define DEBUG_LOOP 0
#endif
#ifdef ENABLE_Q
# define DEBUG_Q 0x800L
#else
# define DEBUG_Q 0
#endif
#ifdef ENABLE_STORE
# define DEBUG_STORE 0x1000L
#else
# define DEBUG_STORE 0
#endif
#ifdef ENABLE_2STORE
# define DEBUG_2STORE 0x2000L
#else
# define DEBUG_2STORE 0
#endif
#ifdef ENABLE_SPILL
# define DEBUG_SPILL 0x4000L
#else
# define DEBUG_SPILL 0
#endif
#ifdef ENABLE_MAPSTORE
# define DEBUG_MAPSTORE 0x8000L
#else
# define DEBUG_MAPSTORE 0
#endif
#ifdef ENABLE_AETREE
# define DEBUG_AETREE 0x10000L
#else
# define DEBUG_AETREE 0
#endif
#ifdef ENABLE_PP
# define DEBUG_PP 0x20000L
#else
# define DEBUG_PP 0
#endif
#ifdef ENABLE_DATA
# define DEBUG_DATA 0x40000L
#else
# define DEBUG_DATA 0
#endif
#ifdef ENABLE_CSE
# define DEBUG_CSE 0x80000L
#else
# define DEBUG_CSE 0
#endif
#ifdef ENABLE_LOCALCG
# define DEBUG_LOCALCG 0x100000L
#else
# define DEBUG_LOCALCG 0
#endif
#ifdef ENABLE_TEMPLATE
# define DEBUG_TEMPLATE 0x200000L
#else
# define DEBUG_TEMPLATE 0
#endif
#ifdef ENABLE_SR
# define DEBUG_SR 0x400000L
#else
# define DEBUG_SR 0
#endif
/* The following generates no code in if (debugging(n)) if 'n' is 0 */
extern long sysdebugmask;
#define debugging(n) ((n) && sysdebugmask & (n))
/*
* ****** TEMPORARY HACKS ******
*/
#ifdef ENABLE_X
# define DEBUG_X 0x80L
#else
# define DEBUG_X 0
#endif
#ifndef TARGET_IS_LITTLE_ENDIAN
# ifndef TARGET_IS_BIG_ENDIAN
# ifndef TARGET_ENDIANNESS_CONFIGURABLE
#error Target byte ordering within word not specified - assume little endian
# define TARGET_IS_LITTLE_ENDIAN
# endif
# endif
#endif
/*
* The following is intended as a general cross compilation pattern.
* The actual translation tables are really a host dependency in the case
* we are cross-character-set compiling, but who in the ascii world cares?
*/
#ifdef TARGET_HAS_EBCDIC
# define char_translation(x) ('A' == 193 ? (x) : _atoe[x])
# define char_untranslation(x) ('A' == 193 ? (x) : _etoa[x])
extern char _atoe[], _etoa[];
#else
# define char_translation(x) (x)
# define char_untranslation(x) (x)
#endif
/*
* The following is for use while the compiler is being developed,
* and causes warnings to appear if names are not sufficiently distinct.
*/
#ifdef POLICE_THE_SIX_CHAR_NAME_LIMIT
#define TARGET_HAS_LINKER_NAME_LIMIT 1
# define LINKER_NAME_MAX 6 /* needed if TARGET_HAS_LINKER_NAME_LIMIT */
# define LINKER_NAME_MONOCASE 1 /* needed if TARGET_HAS_LINKER_NAME_LIMIT */
#include "sixchar.h"
#endif /* POLICE_THE_SIX_CHAR_NAME_LIMIT */
#ifndef SOFTWARE_FLOATING_POINT
# define software_floating_point_enabled 0
# define software_floats_enabled 0
# define software_doubles_enabled 0
#endif
#ifndef software_floating_point_enabled
# define software_floating_point_enabled 1
# define software_floats_enabled 1
# define software_doubles_enabled 1
#endif
#ifndef just32bits_
# define just32bits_(x) (x)
# define widen32bitint_(x) (((x) & 0x80000000) ? (x) | ~0x7fffffff : (x) & 0x7fffffff)
#endif
#ifndef target_stack_moves_once
# ifdef TARGET_STACK_MOVES_ONCE
# define target_stack_moves_once 1
# else
# define target_stack_moves_once 0
# endif
#endif
#ifndef two_address_code
# define two_address_code(op) 1
#endif
/* TARGET_PREFIX is a prefix to be attached to all builtin functions
* Eg. __rt_sdiv & co. This is required where there may be more than
* one version of the builtin function depending on compiler & options
* used, and it is a requirement that these interwork.
*/
#ifndef TARGET_PREFIX
# define TARGET_PREFIX(fname) fname
#endif
#ifndef TARGET_IS_ARM_OR_THUMB
#ifdef TARGET_IS_ARM
#define TARGET_IS_ARM_OR_THUMB 1
#else
#ifdef TARGET_IS_THUMB
#define TARGET_IS_ARM_OR_THUMB 1
#endif
#endif
#endif
#endif
/* end of mip/defaults.h */
|
stardot/ncc | cfe/lex.c | <filename>cfe/lex.c
/*
* C compiler file lex.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 61
* Checkin $Date$
* Revising $Author$
*/
/*
* AM Feb 92: add some C++-isms when CPLUSPLUS is #defined.
* When not defined only effect is a warning for C++ keywords.
* AM Nov 89: treat ANSI pp-number conversion errors properly.
* AM Jun 89: add 16 bit int support
* 13.x.88 Pascal split off
* AM 23-10-86: Fix bug in string wrap round segments, add cc_rerr() calls.
* AM 28-7-86: Recognise += in lexer without whitespace, glue (nextsym)
* '+ =' with space/tab white space. Problematic here
* to recognise '+\n='. A #if would clobber things.
*/
#ifndef _LEX_H
#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_getbodysym() ((void) 0)
#define lex_putbodysym() ((void) 0)
#define save_names(a) ((void) 0)
#endif
/* 2 worlds stuff */
typedef struct SymBuf {
struct SymBuf *prev; SymInfo prevsym; /* for save/restore */
SymInfo *buf;
int size, pos, count;
bool dup_hack; /* template and d-or-e uses have diverged (sigh!) */
int old_put_handle; /* used to stop recording while playing (or while recording d-or-e */
} SymBuf;
static SymBuf *lexbuf_vec, *nextsym_lookaside;
static int nextsym_put_handle; /* only one template can be active */
static int lexbuf_max;
static int buffersym_bufidx;
/* */
static FileLine endofsym_fl;
/* exports: nextsym(), curlex, nextsym_for_hashif(),
lex_init(), and some more! */
/* utilities */
static int intofxdigit(int c)
/* convert hex digit to integer */
{ return(isdigit(c) ? (c) - '0' :
islower(c) ? (c) - 'a' + 10 :
isupper(c) ? (c) - 'A' + 10 :
-1);
}
#define NOTACHAR 0
#define LEX_STRBUFSIZE 256 /* (multiple of 4) initial size lex_strbuf */
static char *lex_strptr; /* next free char in lex_strbuf */
static char *lex_strend; /* one beyond end of lex_strbuf */
static SymInfo prevlex, prevlex_hif, nextlex = {s_nothing};
static int curchar; /* The look-ahead character */
/* The next 3 variables are notionally a single tuple. Export to misc. */
SymInfo curlex; /* Current token and aux. info. */
#ifdef EXTENSION_VALOF
bool inside_valof_block;
static Symstr *resultisword;
#endif
#ifdef TARGET_HAS_INLINE_ASSEMBLER
int asm_mode = ASM_NONE;
static bool in_asm_string = NO;
#endif
int errs_on_this_sym; /* To help error recovery */
/* the +4 in the next line is slop so we do not check on dec. pt. etc. */
static char namebuf[NAMEMAX+4]; /* Buffer for reading identifiers */
static unsigned32 lexclass[1+255];
/* Character table, yielding:
glue-ishness (low 8 bits),
corresponding symbol (next 8 bits),
doubled symbol (next 8 bits)
relop equal symbol (top 8 bits) */
#define lexclass_(ch) lexclass[ch & 0xff]
/* or [(unsigned char)ch], but there are compilers which have difficulty
with that
*/
/* 'curlex.a2.flag' values - only exported for make_integer (q.v.) */
/* the values are chosen for easy punning into sem.c types */
#define NUM_FLOAT bitoftype_(s_double)
#define NUM_INT bitoftype_(s_int)
#define NUM_LONG bitoftype_(s_long)
#define NUM_SHORT bitoftype_(s_short)
#define NUM_UNSIGN bitoftype_(s_unsigned)
#define NUM_LONGLONG bitoftype_(s_longlong)
#define NUM_CHAR (LanguageIsCPlusPlus ? bitoftype_(s_char) : NUM_INT)
/* Type of 'a' is int in C, char in C++. */
/* Note that NUM_WCHAR is defined in defaults.h. */
/* lexical classes - local to this file */
#define l_illegal 0L
#define l_noglue 1L
#define l_selfglue 2L
#define l_idstart 3L
#define l_digit0 4L
#define l_digit1 5L
#define l_quote1 6L
#define l_quote2 7L
#define l_dot 8L
#define l_shifter 9L
#define l_eqglue 10L
#define l_minus 11L
#define l_lpar 12L
#define l_less 13L
#define l_hash 14L
#define l_colon 15L
#define l_coloncpp 16L
#define l_percent 17L
#define LEX_CHTYPE 31L /* mask */
#define l_idcont 32L /* orable */
#define mklc(l,t1,t2,t3) (((unsigned32)(l)) | ((unsigned32)(t1) << 8) | \
((unsigned32)(t2) << 16) | ((unsigned32)(t3) << 24))
/* lex 'semantic' routines... */
/* make_floating uses GLOBAL store for its value. Is this reasonable? */
static AEop make_floating(char *s, int32 flag)
{ FloatCon *x = real_of_string(s,flag);
curlex.a1.fc = x;
return x->h0;
}
/* make_integer does not use GLOBAL or LOCAL store. It could use
the former (but this could be wasteful), or LOCAL, but beware placement
of alloc_reinit() in driver.c and lookahead tokens.
Currently it just assumes that syn.c will look at curlex.a2.flag.
*/
static AEop make_integer(int32 radix, int32 flag)
/* Numbers that overflow 2**32-1 lead to a diagnostic. */
/* Otherwise their type suffix (in flag) is modified to yield a type. */
/* Note that octal and hex numbers sometimes have different types. */
/* I have allowed the digits '8' and '9' to build up even in */
/* octal numbers - this is checked for here. */
/* BEWARE: possible two's complement dependency. */
{
bool overflow = NO, badoct = NO, overflow_warned = NO;
uint64 val64, t64, radix64;
uint32 value;
char c, *cp = namebuf;
I64_IToU(&radix64, radix);
I64_IToU(&val64, 0);
while ((c = *cp++) != 0) {
int32 n = 0;
switch (radix) {
case 8:
if (c>='8') badoct = YES;
n = intofdigit(c);
break;
case 10:
n = intofdigit(c);
break;
case 16:
n = intofxdigit(c);
break;
}
overflow = overflow | (I64_UMul(&val64, &val64, &radix64) != i64_ok);
I64_IToU(&t64, n);
overflow = overflow | (I64_UAdd(&val64, &val64, &t64) != i64_ok);
}
if (badoct) cc_rerr(lex_rerr_8_or_9);
if (overflow) {
cc_err(lex_err_ioverflow_64, namebuf);
overflow_warned = YES;
}
/* Now modify 'flag' (if necessary) to get a type for the constant. */
/* ANSI rules (bracketted cases cannot happen if int==long):
* (10) int, [long], unsigned long.
* (8,16) int, unsigned, [long], [unsigned long].
* (u) unsigned, [unsigned long].
* (l) long, unsigned long.
* (ul) unsigned long.
*/
overflow = I64_UToI(&value, &val64) != i64_ok;
if (feature & FEATURE_FUSSY) {
if (!overflow_warned && overflow) {
cc_err(lex_err_ioverflow, namebuf);
overflow_warned = YES;
}
} else if (overflow
|| (radix == 10 && (value & 0x80000000) && !(flag & NUM_UNSIGN))
|| (flag & NUM_LONGLONG)) {
bool warned = false;
if (!(flag & NUM_LONGLONG) && !(suppress & D_LONGLONGCONST))
{ if (val64.hi & 0x80000000)
cc_warn(lex_warn_force_ulonglong, namebuf, namebuf);
else
cc_warn(lex_warn_force_longlong, namebuf, namebuf);
warned = true;
}
if (val64.hi & 0x80000000)
{ flag |= NUM_UNSIGN;
if (!warned)
cc_warn(lex_warn_force_ulonglong, namebuf, namebuf);
}
curlex.a1.i64 = mkint64const(flag ^ (NUM_LONGLONG|NUM_SHORT|NUM_LONG), (int64 *)&val64);
return s_int64con;
}
if (sizeof_int == 2) /* TARGET_HAS_16_BIT_INT */
{ if (value & 0xffff0000 || flag & NUM_LONG)
{ flag |= NUM_LONG;
if (value & 0x80000000 && !(flag & NUM_UNSIGN))
{ if (radix == 10)
if (!overflow) /* only 1 error message */
cc_ansi_warn(lex_warn_force_unsigned, namebuf, namebuf);
flag |= NUM_UNSIGN;
}
}
else
{ if (value & 0x8000 && !(flag & NUM_UNSIGN))
{ /* warnings here? */
flag |= (radix == 10) ? NUM_LONG : NUM_UNSIGN;
}
}
}
else /* TARGET_HAS_32_BIT_INT */
{ /* (As above) the rules simplify if sizeof_int == sizeof_long == 4. */
/* Since if value is +ve or unsigned then 'flag' is OK, else */
/* we need to convert to 'ul' (decimal) else 'flag+u' otherwise. */
if ((value & 0x80000000) && !(flag & NUM_UNSIGN))
{ flag |= NUM_UNSIGN; /* add 'U' - see ANSI spec */
if (radix == 10) /* but for base 10 add 'L' too */
{ flag |= NUM_LONG;
if (!overflow_warned) /* only 1 error message */
cc_ansi_warn(lex_warn_force_unsigned, namebuf, namebuf);
}
}
}
curlex.a1.i = value;
curlex.a2.flag = flag;
return s_integer;
}
/* The following routine does checks for 'constraint violation' when */
/* coverting a pp_number to a token, caller has already checked for */
/* illegal uses of 'e+' in fp or hex numbers. */
static void lex_check_pp_number(void)
{ if (curchar == '.' ||
curchar != PP_EOF && (lexclass_(curchar) & l_idcont))
cc_ansi_rerr(lex_rerr_pp_number);
}
/* reading routines */
static int nextchar(void)
/* I may also want to buffer some recently read characters so that I */
/* can display them when I notice an error. */
{
if (curchar==PP_EOF) return curchar;
curchar = pp_nextchar();
return curchar;
}
#define is_e(c) /* e or E (exponent marker) */ \
(((c) == 'e') || ((c) == 'E'))
#define is_x(c) /* x or X (hex num marker) */ \
(((c) == 'x') || ((c) == 'X'))
static int32 read_floating(int32 k)
{ int32 flag = NUM_FLOAT;
while (isdigit(curchar))
{ if (k < NAMEMAX)
{ namebuf[k++] = curchar;
nextchar();
}
else
{ cc_err(lex_err_overlong_fp);
while (isdigit(curchar)) nextchar();
}
}
if (is_e(curchar))
{
namebuf[k++] = 'e'; /* normalize case of the exponent mark */
nextchar();
if ((curchar == '+') | (curchar=='-'))
{ namebuf[k++] = curchar;
nextchar();
}
if (!isdigit(curchar))
{ cc_err(lex_err_fp_syntax1);
/* Assume exponent of zero */
namebuf[k++] = '0';
}
else
{ while (isdigit(curchar))
{ if (k < NAMEMAX)
{ namebuf[k++] = curchar;
nextchar();
}
else
{ cc_err(lex_err_overlong_fp);
while (isdigit(curchar)) nextchar();
}
}
}
}
/* note that calls ensure that k > 0 here. */
namebuf[k] = '\0';
switch (curchar)
{ case 'l': case 'L': flag |= NUM_LONG; nextchar(); break;
case 'f': case 'F': flag |= NUM_SHORT; nextchar(); break;
}
/* Note that a fp number ending in 'E' above has already been diagnosed */
lex_check_pp_number();
return flag;
}
static AEop read_number(int radix)
{ int32 flag = NUM_INT, k = 0; /* namebuf useful to collect chars */
if (radix == 16)
{ while (isxdigit(curchar))
{ if (k < NAMEMAX)
{ namebuf[k++] = curchar;
nextchar();
}
else
{ cc_err(lex_err_overlong_hex);
while (isxdigit(curchar)) nextchar();
}
}
if (k==0)
{ cc_err(lex_err_need_hex_dig);
namebuf[k++] = '0'; /* treat as 0x0 */
}
namebuf[k] = '\0';
/* ANSI (Dec 88 draft) require a diagnostic for 0xee+1 or 0xee+spqr. */
if (is_e(namebuf[k-1]) && (curchar == '+' || curchar == '-'))
cc_ansi_rerr(lex_rerr_hex_exponent);
}
else
{ while (isdigit(curchar))
{ if (k < NAMEMAX)
{ namebuf[k++] = curchar;
nextchar();
}
else
{ cc_err(lex_err_overlong_int);
while (isdigit(curchar)) nextchar();
}
}
if (curchar=='.')
{ nextchar();
if (k == 0) namebuf[k++] = '0'; /* consider '0.' */
namebuf[k++] = '.';
flag = read_floating(k);
}
else if (is_e(curchar))
{ if (k == 0) namebuf[k++] = '0'; /* consider '0e5' */
flag = read_floating(k);
}
else
{ if (k == 0) namebuf[k++] = '0'; /* consider '0' */
namebuf[k] = '\0';
}
}
if (flag & NUM_FLOAT) return make_floating(namebuf,flag);
for (;;)
{
if (curchar == 'l' || curchar == 'L') {
if (!(feature & FEATURE_FUSSY) && (flag & NUM_LONG)) {
flag ^= NUM_LONG|NUM_LONGLONG; nextchar(); continue;
} else if (!(flag & (NUM_LONGLONG|NUM_LONG))) {
flag |= NUM_LONG; nextchar(); continue;
}
}
if ((curchar == 'u' || curchar == 'U') && !(flag & NUM_UNSIGN))
{ flag |= NUM_UNSIGN; nextchar(); continue;
}
lex_check_pp_number();
return make_integer(radix, flag);
}
}
/* string and char reading (unified reading & semantic routines) ... */
/* The wide character support below supports wchar_t == target int. */
/* You can change this via mip/defaults.h. */
static unsigned32 lex_string_insert(char *where, int size, unsigned32 what)
{ switch (size)
{ case 4: { uint32 val = what;
if (target_lsbytefirst != host_lsbytefirst) {
val = ((what & 0xff) << 24)
| ((what & 0xff00) << 8)
| ((what & 0xff0000) >> 8)
| (what >> 24);
}
*(uint32 *)where = val;
return what;
}
case 2: { uint16 val = (uint16)what;
if (target_lsbytefirst != host_lsbytefirst) {
val = ((what & 0xff) << 8)
| (what >> 8);
}
*(uint16 *)where = val;
return (uint16)what;
}
case 1: return *(uint8 *)where = (uint8)what;
default: syserr(syserr_lex_string); return what;
}
}
static bool lex_string_char(char *where, int size, bool escaped)
/* read a possibly escaped (with backslash (\)) character for a */
/* character or string literal (possibly wide). If read succeeds */
/* result is placed in where (if char) and (<size> *)where (if wide char).*/
/* Caller aligns if wide. Result is 1 if succeeds, 0 if null escape read */
{
int ch = curchar;
if (escaped) switch (ch) /* (next character has already been read) */
{
case 'a': ch = BELL; break; /* attn (otherwise known as bell) */
case 'b': ch = '\b'; break; /* backspace */
case 'f': ch = CHAR_FF; break; /* form feed */
case 'n': ch = CHAR_NL; break; /* newline */
case 'r': ch = CHAR_CR; break; /* carriage return */
case 't': ch = '\t'; break; /* (horizontal) tab */
case 'v': ch = CHAR_VT; break; /* vertical tab */
case '\\': ch = '\\'; break; /* backslash */
case '\'': ch = '\''; break; /* single quote mark */
case '\"': ch = '\"'; break; /* double quote mark */
case '?': ch = '?'; break; /* '?' in case \?\?\? is needed */
case 'x':
{ bool ovfl = 0;
unsigned32 escch, resultch;
if (!isxdigit(ch = nextchar()))
{ cc_err(lex_err_need_hex_dig1);
ch = 'x';
goto return_ch; /* "\xg" -> "xg": any better ideas? */
}
escch = intofxdigit(ch);
/* ANSI (3rd review draft) say any any number of digits. */
while (isxdigit(nextchar()))
{ if (((escch << 4) >> 4) != escch) ovfl = 1;
escch = (escch<<4) + intofxdigit(curchar);
}
/* Never translate \x escapes. */
resultch = lex_string_insert(where, size, escch);
if (ovfl || escch != resultch) /* constraint violation */
cc_rerr(lex_rerr_esc16_truncated, ovfl ? "...": "",
(long)escch, (long)resultch);
return 1;
}
case '0': case '1':
case '2': case '3': /* octal escapes */
case '4': case '5':
case '6': case '7':
/* This code is simpler than that for \x since 3 digits make overflow hard */
{ unsigned32 resultch;
unsigned escch = intofdigit(ch);
if (isodigit(nextchar())) /* second & third digits */
{ escch = (escch<<3) + intofdigit(curchar);
if (isodigit(nextchar())) {
escch = (escch<<3) + intofdigit(curchar);
nextchar();
}
}
/* Never translate \ooo escapes. */
resultch = lex_string_insert(where, size, escch);
if (escch != resultch) /* constraint violation */
cc_rerr(lex_rerr_esc8_truncated, escch, (int)resultch);
return 1;
}
/* note that the sequence \<nl> (but not \<space><nl>) is now removed at
all possible occasions by the preprocessor. However, code for handling
such situations is left here so that \<space><nl> is removed with just a
warning message.
Moreover we have to take care that (e.g.) \\<nl><nl> gives an error.
*/
case ' ': /* In pcc mode, allow '\ ' to appease XOpen test suite */
if (feature & FEATURE_PCC) break;
case '\t':
cc_err(lex_err_backslash_blank);
/* If I see \<space> I generate a warning message. I then skip over any
* following whitespace, up to one newline. Thus the effect is that
* \(space|tab)*(nl|) are ignored just as \nl.
*/
do nextchar(); while ((curchar==' ') || (curchar=='\t'));
if (curchar=='\n') nextchar();
case '\n': /* drop through. note no nextchar() here so read_string()
will give an error message. */
return 0;
default: /* pp.c removes control chars if !FEATURE_PCC */
cc_ansi_rerr(lex_rerr_illegal_esc, (int)ch, (int)ch);
break; /* i.e. treat unknown escape "\Q" as "Q" */
}
nextchar();
/* note the next line translates all chars except \ooo and \xooo */
return_ch:
(void)lex_string_insert(where, size, char_translation(ch));
return 1;
}
static void read_string(int quote, AEop type, bool lengthwanted)
{ char *symstrp = lex_strptr, *val = lex_strptr;
#ifdef EXTENSION_COUNTED_STRINGS
bool isCountedString = NO;
if (lengthwanted) {
curchar = 0;
isCountedString = YES;
} else
#else
IGNORE(lengthwanted);
#endif
nextchar();
while (curchar!=quote)
{ bool escaped = curchar == '\\';
if ((curchar=='\n') || (curchar==PP_EOF))
{ cc_err(lex_err_unterminated_string);
break; /* slightly untidy about nextchar() below, but OK */
}
/* If I run off the end of this segment of lex_strbuf I allocate another */
/* and copy the part-string into it, doubling the size if necessary. */
if (symstrp >= lex_strend)
{ size_t n = symstrp - val, allocsize = LEX_STRBUFSIZE;
while (n*2 > allocsize) allocsize *= 2;
{ char *oval = val;
val = (char *)BindAlloc(allocsize);
if (n != 0) memcpy(val, oval, n);
lex_strptr = symstrp = val + n;
lex_strend = val + allocsize;
}
}
if (escaped) nextchar();
#ifdef EXTENSION_COUNTED_STRINGS
if (val == symstrp && escaped && curchar == 'p' &&
(feature & FEATURE_ALLOWCOUNTEDSTRINGS))
{ /* "\p" at start of string */
isCountedString = YES;
#ifdef EXTENSION_UNSIGNED_STRINGS
if (type == s_string) type = s_ustring;
#endif
escaped = NO; /* discard the '\' : 'p' will be planted in the */
/* string and overwritten at the end */
}
#endif
if (lex_string_char(symstrp, (type == s_wstring ? sizeof_wchar : 1),
escaped))
symstrp += (type == s_wstring ? sizeof_wchar : 1);
}
nextchar();
if (quote == '"')
{ curlex.a2.len = symstrp - val;
#ifdef EXTENSION_COUNTED_STRINGS
if (isCountedString) /* treat wide strings rationally */
lex_string_insert(val, (type == s_wstring ? sizeof_wchar : 1),
curlex.a2.len-1);
#endif
lex_strptr = &val[pad_to_word(curlex.a2.len)]; /* commit usage */
curlex.a1.s = val;
curlex.sym = type;
}
else
{ int32 k = 0, n = symstrp - val;
/* note that for char constants we do not commit symstrp to lex_strptr */
/* The following line deals host-independently with single char */
/* constants, at least if host char is 8 bits. */
if (type == s_wstring)
{ if (n != sizeof_wchar) cc_rerr(lex_rerr_not1wchar);
if (n != 0)
{ if (sizeof_wchar == 4)
{ k = *(uint32 *)val;
if (target_lsbytefirst != host_lsbytefirst) {
k = ((k & 0xff) << 24)
| ((k & 0xff00) << 8)
| ((k & 0xff0000) >> 8)
| (k >> 24);
}
} else {
k = *(uint16 *)val;
if (target_lsbytefirst != host_lsbytefirst) {
k = ((k & 0xff) << 8)
| (k >> 8);
}
}
}
}
else if (n == 1)
k = (feature & FEATURE_SIGNED_CHAR) ? *(int8 *)val
: *(unsigned8 *)val;
else
{ /* The effect of n>1 is implementation-defined */
int32 i;
if (n == 0)
cc_rerr(lex_rerr_empty_char);
else if (n > sizeof_int)
cc_rerr(lex_rerr_overlong_char), n = sizeof_int;
else if (!(suppress & D_MULTICHAR))
cc_warn(lex_warn_multi_char);
/* The following code follows pcc, and is host independent */
/* but assembles bytes 'backwards' on 68000-sex machines. */
/* (It agrees with previous code on intel-sex hosts.) */
/* It is arguable that we should sign-extend the last char */
/* (only!) if FEATURE_SIGNED_CHAR (merges in n==1 case). */
for (i=0; i<n; i++)
k = (unsigned32)k << 8 | ((unsigned8 *)val)[i];
if (sizeof_int == 2) k = (int16)k; /* normalise, eg for cmp. */
}
curlex.a1.i = k;
curlex.a2.flag = (type == s_wstring) ? NUM_WCHAR : NUM_CHAR;
/* perhaps NUM_INT|NUM_LONG if n=4? */
curlex.sym = s_integer; /* chars give produce int consts. */
/* returning s_character/s_wcharacter would improve messages for int'a'; */
}
}
#define CPP_word 256 /* identifier (but warned) for C, keyword for C++ */
#define CPP_word2 512 /* keyword for C++, but currently warned+ident. */
#define CPP_word3 1024 /* keyword for C++, but currently warn that */
/* feature is not fully implemented. */
static AEop next_basic_sym(void)
/* all of nextsym() except debug info */
{ unsigned32 charinfo;
int32 savechar;
FileLine startofsym_fl;
if (endofsym_fl.filepos != -1 && !pp_inhashif)
curlex.fl = endofsym_fl;
if (curchar == NOTACHAR) nextchar();
startofsym_fl = curlex.fl;
for (;;)
{ if (curchar == PP_EOF) return (curlex.sym = s_eof);
if (!isspace(curchar)) break;
if (curchar == '\n')
{
if (pp_inhashif) return (curlex.sym = s_eol);
#ifdef TARGET_HAS_INLINE_ASSEMBLER
if (asm_mode == ASM_BLOCK)
{
endofsym_fl = curlex.fl; /* save for next call */
curlex.fl.l--; /* move back to current line */
curchar = NOTACHAR;
return (curlex.sym = s_eol);
}
#endif
}
nextchar();
}
/* Not just startofsym_fl = curlex.fl below, because we want the column
to be that of the first whitespace character preceding the symbol on
the same line, not that of the first character of the symbol (so that
a debugger may see the whitespace preceding a statement as part of it).
*/
if (startofsym_fl.l != curlex.fl.l)
{ startofsym_fl = curlex.fl;
startofsym_fl.column = 1;
}
switch ((charinfo = lexclass_(curchar)) & LEX_CHTYPE)
{
default: if (curchar == '#' || curchar == '\\')
cc_err(lex_err_bad_hash, (int)curchar);
else if (isprint(curchar)) /* can only happen if FEATURE_PCC */
cc_err(lex_err_bad_char, (long)curchar, (int)curchar);
else cc_err(lex_err_bad_noprint_char, (int)curchar);
nextchar();
next_basic_sym();
break;
case l_idstart:
{ int k = 0; /* number of characters read */
do
{ if (k < NAMEMAX)
{
namebuf[k++] = curchar;
}
nextchar();
} while (lexclass_(curchar) & l_idcont);
namebuf[k] = 0;
/* Check if ANSI wide string/char -- illegal syntax in olde-C. */
if (k == 1 && namebuf[0] == 'L'
&& (curchar == '"' || curchar == '\''))
read_string(curchar, s_wstring, NO);
#ifdef EXTENSION_UNSIGNED_STRINGS
else if (k == 1 && namebuf[0] == 'U' && curchar == '"')
read_string(curchar, s_ustring, NO);
else if (k == 1 && namebuf[0] == 'B' && curchar == '"')
read_string(curchar, s_ustring, YES);
#endif
else
{ int32 type;
curlex.a1.sv = sym_lookup(namebuf, SYM_GLOBAL);
type = symtype_(curlex.a1.sv);
/* To prepare for C++, give a warning ONCE per file in ANSI mode when a */
/* C++ keyword is used as a C identifier. */
if (type & (CPP_word|CPP_word2|CPP_word3)) {
if (LanguageIsCPlusPlus)
{ if (type & CPP_word2)
{ symtype_(curlex.a1.sv) = type = s_identifier;
cc_ansi_warn(lex_warn_cplusplusid, curlex.a1.sv);
} else if (type & CPP_word3) {
/* Temporary check for C++ features that are known */
/* to not be fully implemented. Will go away when */
/* C++ implementation has progressed. AC */
symtype_(curlex.a1.sv) = s_identifier;
cc_ansi_warn(lex_warn_cplusplusimpl, curlex.a1.sv);
symtype_(curlex.a1.sv) = type = type^CPP_word3;
}
}
else {
int32 tflag = type & (CPP_word|CPP_word2);
symtype_(curlex.a1.sv) = type = s_identifier;
#ifndef FOR_ACORN
if (tflag != (CPP_word|CPP_word2))
/* don't warn for wchar_t which appears */
/* stdlib.h and stddef.h in C mode. */
cc_ansi_warn(lex_warn_cplusplusid, curlex.a1.sv);
#endif
}
}
/* There are no keywords during pp (including #if), following ANSI/Reiser. */
/* Consider adding a new s_ppidentifier which could aid lex.c. */
#ifdef ALLOW_KEYWORDS_IN_HASHIF
curlex.sym = type;
#else
curlex.sym = pp_inhashif ? s_identifier : type;
#endif
curlex.a2.flag = 0;
#ifdef EXTENSION_VALOF
/* The following represents a rather nasty piece of context-sensitive */
/* hackery - inside a valof block the word 'resultis' is recognized as a */
/* keyword, but otherwise (as required in regular ANSI C) it is just */
/* another ordinary symbol. I wonder if there is a better solution to this */
/* issue........... ?? */
if (inside_valof_block && curlex.sym == s_identifier &&
curlex.a1.sv == resultisword) curlex.sym = s_resultis;
#endif
}
break;
}
case l_digit0: /* octal or hex or floating */
nextchar(); /* N.B. initial 0 not buffered */
if (is_x(curchar))
{ nextchar();
curlex.sym = read_number(16); /* hex */
}
else
curlex.sym = read_number(8); /* octal or float */
break;
case l_digit1: /* decimal int or floating */
curlex.sym = read_number(10);
break;
case l_dot: nextchar();
if (curchar == '*')
curlex.sym = s_dotstar,
curchar = NOTACHAR;
else
if (isdigit(curchar))
{ int32 flag, k = 0;
namebuf[k++] = '.';
namebuf[k++] = curchar;
nextchar();
flag = read_floating(k); /* change to use read_number()? */
curlex.sym = make_floating(namebuf, flag);
}
else
{ int32 n = 1;
while (curchar=='.') n++, nextchar();
switch (n)
{ case 1: curlex.sym = s_dot; break;
default: cc_err(lex_err_ellipsis);
/* drop through */
case 3: curlex.sym = s_ellipsis; break;
}
}
break;
case l_noglue:
curlex.sym = charinfo >> 8 & 255;
curchar = NOTACHAR;
break;
case l_eqglue: nextchar();
if (curchar == '=')
curlex.sym = charinfo >> 16,
curchar = NOTACHAR;
else curlex.sym = charinfo >> 8 & 255;
break;
case l_selfglue:
savechar = curchar;
nextchar();
if (curchar == savechar)
curlex.sym = charinfo >> 16 & 255,
curchar = NOTACHAR;
/* all selfgluer's '+' have a '+=' form except C++ ':=' */
else if (curchar == '=' && (charinfo >> 24) != 0)
curlex.sym = charinfo >> 24,
curchar = NOTACHAR;
else curlex.sym = charinfo >> 8 & 255;
break;
case l_less: nextchar();
if (curchar == ':')
{ curlex.sym = s_lbracket;
curchar = NOTACHAR;
} else if (curchar == '%')
{ curlex.sym = s_lbrace;
curchar = NOTACHAR;
} else
{ savechar = '<';
goto handleshift;
}
break;
case l_shifter: savechar = curchar; /* very much like l_selfglue */
nextchar(); /* (32 bits is too few) */
handleshift:
if (curchar == '=')
curlex.sym = charinfo >> 24,
curchar = NOTACHAR;
else if (curchar == savechar)
{ curlex.sym = charinfo >> 16 & 255;
nextchar();
if (curchar == '=')
curlex.sym = assignop_(curlex.sym), /* >> to >>= etc */
curchar = NOTACHAR;
}
else curlex.sym = charinfo >> 8 & 255;
break;
case l_minus: nextchar(); /* l_selfglue but for "->", (C++)"->*". */
if (curchar=='-')
curlex.sym = s_minusminus,
curchar = NOTACHAR;
else if (curchar=='>')
{ nextchar();
if (curchar=='*')
curlex.sym = s_arrowstar,
curchar = NOTACHAR;
else
curlex.sym = s_arrow;
}
else
{
if (curchar=='=')
curlex.sym = s_minusequal,
curchar = NOTACHAR;
else curlex.sym = s_minus;
}
break;
case l_colon: nextchar();
if (curchar == '>')
curlex.sym = s_rbracket,
curchar = NOTACHAR;
else
curlex.sym = s_colon;
break;
case l_coloncpp: nextchar();
if (curchar == '>')
curlex.sym = s_rbracket,
curchar = NOTACHAR;
else if (curchar == ':')
curlex.sym = s_coloncolon,
curchar = NOTACHAR;
else
curlex.sym = s_colon;
break;
case l_percent: nextchar();
if (curchar == '>')
curlex.sym = s_rbrace,
curchar = NOTACHAR;
else if (curchar == '=')
curlex.sym = s_remequal,
curchar = NOTACHAR;
else
curlex.sym = s_rem;
break;
case l_quote1: read_string(curchar, s_string, NO);
break;
case l_quote2:
#ifndef TARGET_HAS_INLINE_ASSEMBLER
read_string(curchar, s_string, NO);
break;
#else
if (asm_mode != ASM_STRING)
{ in_asm_string = NO;
read_string(curchar, s_string, NO);
}
else
{ in_asm_string = !in_asm_string;
curchar = NOTACHAR;
curlex.sym = s_quote;
}
break;
case l_hash: if (asm_mode == ASM_STRING || asm_mode == ASM_BLOCK)
{ curlex.sym = s_hash;
curchar = NOTACHAR;
}
else
{ cc_err(lex_err_bad_hash, (int)curchar);
nextchar();
next_basic_sym();
}
break;
#endif /* TARGET_HAS_INLINE_ASSEMBLER */
}
if (can_have_becomes(curlex.sym) && (feature & FEATURE_PCC))
{ /* recognise whitespace (but NOT newlines) in += etc */
/* as a sop to olde-style (K&R) C. */
/* BEWARE & = and * = in C++ default argument lists. */
/* So, this may only be done in cc -pcc mode... */
if (curchar == NOTACHAR) nextchar();
while (curchar == ' ' || curchar == '\t') nextchar();
if (curchar == '=')
{ curlex.sym = and_becomes(curlex.sym);
curchar = NOTACHAR;
}
}
endofsym_fl = curlex.fl; /* save for next call */
if (!pp_inhashif)
curlex.fl = startofsym_fl; /* reset to start of symbol */
return curlex.sym;
}
void ungetsym(void)
{ if (nextlex.sym != s_nothing) syserr("too many ungetsyms");
if (debugging(DEBUG_LEX))
cc_msg("<ungetsym: $l>\n");
nextlex = curlex; /* Surprisingly, this copying is as efficient */
/* as pointer juggling - perhaps more so. */
if (pp_inhashif) curlex = prevlex_hif; else curlex = prevlex;
}
AEop nextsym(void)
/* sets curlex.sym to next symbol */
{
errs_on_this_sym = 0;
if (pp_inhashif) prevlex_hif = curlex; else prevlex = curlex;
if (nextlex.sym != s_nothing)
{ curlex = nextlex;
nextlex.sym = s_nothing;
}
else
{ if (LanguageIsCPlusPlus && !pp_inhashif && nextsym_lookaside != NULL)
lex_getbodysym();
else
next_basic_sym();
if (LanguageIsCPlusPlus && !pp_inhashif && nextsym_put_handle >= 0)
lex_putbodysym();
}
if (debugging(DEBUG_LEX))
{ cc_msg("<nextsym: $l");
if (LanguageIsCPlusPlus && !pp_inhashif)
{ if (nextsym_lookaside != NULL)
cc_msg(" from [%d]", (int)(nextsym_lookaside - lexbuf_vec));
}
cc_msg(">\n");
}
return curlex.sym;
}
AEop nextsym_for_hashif(void)
{ curchar = NOTACHAR; /* could only have been '\n' or NOTACHAR */
return nextsym();
}
/* exported initialiser lex_init() is language dependent ... */
static void setuplexclass1(char *s, unsigned32 l)
{ unsigned char ch;
while ((ch = *s++) != 0) lexclass_(ch) = l | l_idcont;
}
static void init_sym_name_table(void)
{ /* add entries for error messages for non-reserved words, e.g. block */
/* (currently) non-table driven... */
sym_name_table[s_error] = msg_lookup(errname_error); /* <previous error> */
sym_name_table[s_invisible] = msg_lookup(errname_invisible); /* <invisible> */
sym_name_table[s_let] = msg_lookup(errname_let); /* <let> */
sym_name_table[s_character] = msg_lookup(errname_character); /* <character constant> */
sym_name_table[s_wcharacter] = msg_lookup(errname_wcharacter); /* <wide character constant> */
sym_name_table[s_boolean] = msg_lookup(errname_boolean); /* <boolean constant> */
sym_name_table[s_integer] = msg_lookup(errname_integer); /* <integer constant> */
sym_name_table[s_int64con] = msg_lookup(errname_int64con); /* <integer constant> */
sym_name_table[s_floatcon] = msg_lookup(errname_floatcon); /* <floating constant> */
sym_name_table[s_string] = msg_lookup(errname_string); /* <string constant> */
sym_name_table[s_wstring] = msg_lookup(errname_wstring); /* <wide string constant> */
sym_name_table[s_identifier] = msg_lookup(errname_identifier); /* <identifier> */
sym_name_table[s_pseudoid] = msg_lookup(errname_identifier); /* <identifier> */
sym_name_table[s_binder] = msg_lookup(errname_binder); /* <variable> */
sym_name_table[s_tagbind] = msg_lookup(errname_tagbind); /* <struct/union tag> */
sym_name_table[s_cond] = msg_lookup(errname_cond); /* _?_:_ */
sym_name_table[s_displace] = msg_lookup(errname_displace); /* ++ or -- */
sym_name_table[s_postinc] = msg_lookup(errname_postinc); /* ++ */
sym_name_table[s_postdec] = msg_lookup(errname_postdec); /* -- */
sym_name_table[s_arrow] = msg_lookup(errname_arrow); /* -> */
sym_name_table[s_arrowstar] = msg_lookup(errname_arrowstar); /* ->* */
sym_name_table[s_dotstar] = msg_lookup(errname_dotstar); /* .* */
sym_name_table[s_ctor] = msg_lookup(errname_constructor); /* <constructor> */
sym_name_table[s_dtor] = msg_lookup(errname_destructor); /* <destructor> */
sym_name_table[s_addrof] = msg_lookup(errname_addrof); /* unary & */
sym_name_table[s_content] = msg_lookup(errname_content); /* unary * */
sym_name_table[s_monplus] = msg_lookup(errname_monplus); /* unary + */
sym_name_table[s_neg] = msg_lookup(errname_neg); /* unary - */
sym_name_table[s_fnap] = msg_lookup(errname_fnap); /* <function argument> */
sym_name_table[s_subscript] = msg_lookup(errname_subscript); /* <subscript> */
sym_name_table[s_cast] = msg_lookup(errname_cast); /* <cast> */
sym_name_table[s_sizeoftype] = msg_lookup(errname_sizeoftype); /* sizeof */
sym_name_table[s_sizeofexpr] = msg_lookup(errname_sizeofexpr); /* sizeof */
sym_name_table[s_ptrdiff] = msg_lookup(errname_ptrdiff); /* - */ /* for (a-b)=c msg */
sym_name_table[s_endcase] = msg_lookup(errname_endcase); /* break */
sym_name_table[s_block] = msg_lookup(errname_block); /* <block> */
sym_name_table[s_decl] = msg_lookup(errname_decl); /* decl */
sym_name_table[s_fndef] = msg_lookup(errname_fndef); /* fndef */
sym_name_table[s_typespec] = msg_lookup(errname_typespec); /* typespec */
sym_name_table[s_typedefname] = msg_lookup(errname_typedefname); /* typedefname */
#ifdef EXTENSION_VALOF
sym_name_table[s_valof] = msg_lookup(errname_valof); /* valof */
#endif
sym_name_table[s_ellipsis] = msg_lookup(errname_ellipsis); /* ... */
sym_name_table[s_eol] = msg_lookup(errname_eol); /* \\n */
sym_name_table[s_eof] = msg_lookup(errname_eof); /* <eof> */
#ifdef RANGECHECK_SUPPORTED
sym_name_table[s_rangecheck] = msg_lookup(errname_rangecheck); /* <rangecheck> */
sym_name_table[s_checknot] = msg_lookup(errname_checknot); /* <check> */
#endif
sym_name_table[s_init] = msg_lookup(errname_init); /* = */
}
void lex_init() /* C version */
{
int32 i;
static const struct { unsigned32 lc; char name[2], name1[3], name2[3]; }
sp[] = {
{ mklc(l_noglue, s_lpar, 0, 0), "(" },
{ mklc(l_noglue, s_rpar, 0, 0), ")" },
{ mklc(l_noglue, s_lbracket, 0, 0), "[" },
{ mklc(l_noglue, s_rbracket, 0, 0), "]" },
{ mklc(l_noglue, s_lbrace, 0, 0), "{" },
{ mklc(l_noglue, s_rbrace, 0, 0), "}" },
{ mklc(l_noglue, s_semicolon, 0, 0), ";" },
{ mklc(l_noglue, s_comma, 0, 0), "," },
{ mklc(l_noglue, s_bitnot, 0, 0), "~" },
{ mklc(l_noglue, s_cond, 0, 0), "?" },
/* now the assignable nongluers */
{ mklc(l_eqglue, s_times, s_timesequal, 0), "*", "*=" },
{ mklc(l_eqglue, s_div, s_divequal, 0), "/", "/=" },
{ mklc(l_percent,s_rem, s_remequal, 0), "%", "%=" }, /* charinfo not really used */
{ mklc(l_eqglue, s_xor, s_xorequal, 0), "^", "^=" },
{ mklc(l_eqglue, s_boolnot, s_notequal, 0), "!", "!=" },
/* now the self-gluers (only the single form is assignable) */
{ mklc(l_selfglue, s_assign, s_equalequal, s_equalequal),
"=", "==", "==" },
{ mklc(l_selfglue, s_and, s_andand, s_andequal),
"&", "&&", "&=" },
{ mklc(l_selfglue, s_or, s_oror, s_orequal),
"|", "||", "|=" },
{ mklc(l_selfglue, s_plus, s_plusplus, s_plusequal),
"+", "++", "+=" },
/* shifts/relops - both the single and double form is assignable */
{ mklc(l_less, s_less, s_leftshift, s_lessequal),
"<", "<<", "<=" },
{ mklc(l_shifter, s_greater, s_rightshift, s_greaterequal),
">", ">>", ">=" },
/* magic chars - 1 per class */
{ mklc(l_quote1, 0, 0, 0), "'" },
{ mklc(l_quote2, s_quote, 0, 0), "\"" },
{ mklc(l_minus, s_minus, s_minusminus, s_minusequal),
"-", "--", "-=" },
{ mklc(l_dot, s_dot, 0, 0), "." },
{ mklc(l_colon, s_colon, 0, 0), ":" }, /* charinfo not really used */
{ mklc(l_hash, s_hash, 0, 0), "#" }
};
static const struct keyword { const char *name; AEop sym; } ns[] = {
/* ANSI keywords which also were in PCC. */
{ "auto", s_auto },
{ "break", s_break },
{ "case", s_case },
{ "char", s_char },
{ "continue", s_continue },
{ "default", s_default },
{ "do", s_do },
{ "double", s_double },
{ "else", s_else },
{ "enum", s_enum },
{ "extern", s_extern },
{ "float", s_float },
{ "for", s_for },
{ "goto", s_goto },
{ "if", s_if },
{ "int", s_int },
{ "long", s_long },
{ "register", s_register },
{ "return", s_return },
{ "short" , s_short },
{ "sizeof", s_sizeof },
{ "static", s_static },
{ "struct", s_struct },
{ "switch", s_switch },
{ "typedef", s_typedef },
{ "union", s_union },
{ "unsigned", s_unsigned },
{ "void", s_void },
{ "while", s_while },
/* C extension: */
{ "__int64", s_longlong},
/* specials to help the compiler/library. */
{ "___toplevel",s_toplevel },
{ "___type", s_typestartsym },
{ "___typeof",s_typeof },
{ "___weak", s_weak },
{ "__pure", s_pure },
{ "__value_in_regs", s_structreg },
{ "__packed", s_unaligned},
{ "__opaque", s_opaque },
#ifdef TARGET_HAS_INLINE_ASSEMBLER
{ "__asm", s_asm },
#endif
#ifdef TARGET_IS_ARM_OR_THUMB
{ "__swi", s_swi },
{ "__swi_indirect", s_swi_i },
#else
/* give traps reasonable names on Unix... */
{ "__systrap",s_swi },
{ "__systrap_indirect", s_swi_i },
#endif
{ "__irq", s_irq },
{ "__global_reg", s_globalreg },
{ "__global_freg", s_globalfreg },
{ "__inline", s_inline }
#ifdef EXTENSION_VALOF
, { "resultis", s_resultis }
#endif
};
static const struct keyword ns2[] = {
/* The following are ANSI C keywords, but old PCC (unix) sources */
/* (compile with -pcc -fussy) may treat them as identifiers! */
{ "const", s_const },
{ "signed", s_signed },
{ "volatile", s_volatile }
};
static const struct keyword ns3[] = {
/* C++ only keywords (redeclared as s_identifier on use in C mode) */
{ "asm", CPP_word|s_asm },
{ "bool", CPP_word|s_bool },
{ "catch", CPP_word|s_catch },
{ "class", CPP_word|s_class },
{ "delete", CPP_word|s_delete },
{ "false", CPP_word|s_false },
{ "friend", CPP_word|s_friend },
{ "inline", CPP_word|s_inline },
{ "new", CPP_word|s_new },
{ "operator", CPP_word|s_operator },
{ "private", CPP_word|s_private },
{ "protected",CPP_word|s_protected },
{ "public", CPP_word|s_public },
{ "template", CPP_word|s_template },
{ "this", CPP_word|s_this },
{ "throw", CPP_word3|s_throw },
{ "true", CPP_word|s_true },
{ "try", CPP_word|s_try },
{ "virtual", CPP_word|s_virtual },
{ "typename", CPP_word|s_typename },
{ "export", CPP_word|s_export },
/* ANSI C++ draft 950428 adds operator alternative representations... */
/* minor nit: these will appear tranformed in error messages */
{ "bitand", CPP_word|s_and },
{ "and", CPP_word|s_andand },
{ "bitor", CPP_word|s_or },
{ "or", CPP_word|s_oror },
{ "xor", CPP_word|s_xor },
{ "compl", CPP_word|s_bitnot },
{ "and_eq", CPP_word|s_andequal },
{ "or_eq", CPP_word|s_orequal },
{ "xor_eq", CPP_word|s_xorequal },
{ "not", CPP_word|s_boolnot },
{ "not_eq", CPP_word|s_notequal },
/* ANSI C++ draft 950428 adds the following keywords (just warn for now). */
/* CPP_word3 indicates partial implementation. */
{ "const_cast", CPP_word3|s_const_cast },
{ "dynamic_cast", CPP_word3|s_dynamic_cast },
{ "mutable", CPP_word2|s_error },
{ "namespace", CPP_word2|s_error },
{ "reinterpret_cast", CPP_word3|s_reinterpret_cast },
{ "static_cast", CPP_word3|s_static_cast },
{ "typeid", CPP_word3|s_typeid },
{ "explicit", CPP_word2|s_error },
{ "using", CPP_word3|s_using },
{ "wchar_t", CPP_word|CPP_word2|s_error }
};
{
char *unset=msg_lookup(errname_unset); /* for speed */
for (i = 0; i < s_NUMSYMS; i++) sym_name_table[i] = unset;
}
init_sym_name_table(); /* language independent inits... */
/* although lexclass[] is notionally constant, C's initialisation
facilities do not conveniently enable us to initialise it... */
for (i = 0; i <= 255; i++) lexclass[i] = l_illegal;
setuplexclass1("ABCDEFGHIJKLMNOPQRSTUVWXYZ_", l_idstart);
setuplexclass1("abcdefghijklmnopqrstuvwxyz", l_idstart);
setuplexclass1("123456789", l_digit1);
setuplexclass1("0", l_digit0);
/*
* The following line is for the sake of SUN NeWS !
* This is because SUN NeWS allows the use of '$'
* in variable names (yuk !)
*/
if (feature & (FEATURE_PCC|FEATURE_LIMITED_PCC))
setuplexclass1("$", l_idstart);
{ unsigned int u;
for (u = 0; u < sizeof(ns)/sizeof(ns[0]); ++u)
{ const char *name = ns[u].name; int32 sym = ns[u].sym;
sym_insert(name, sym);
sym_name_table[sym] = name;
}
if ((feature & (FEATURE_PCC|FEATURE_FUSSY)) !=
(FEATURE_PCC|FEATURE_FUSSY))
{ for (u = 0; u < sizeof(ns2)/sizeof(ns2[0]); ++u)
{ const char *name = ns2[u].name; int32 sym = ns2[u].sym;
sym_insert(name, sym);
sym_name_table[sym] = name;
}
if (LanguageIsCPlusPlus || !(suppress & D_FUTURE))
{ for (u = 0; u < sizeof(ns3)/sizeof(ns3[0]); ++u)
{ const char *name = ns3[u].name; int32 sym = ns3[u].sym;
if (LanguageIsCPlusPlus)
sym &= ~CPP_word;
sym_insert(name, sym);
sym_name_table[sym & ~(CPP_word|CPP_word2|CPP_word3)] = name;
}
}
}
if (!(feature & FEATURE_FUSSY))
sym_name_table[s_longlong] = "long long";
}
{ unsigned int u;
for (u = 0; u < sizeof(sp)/sizeof(sp[0]); u++)
{ const char *name = sp[u].name; unsigned32 lc = sp[u].lc;
AEop s;
lexclass_(*name) = lc;
if ((s = (lc >> 8) & 255) != 0) sym_name_table[s] = name;
if ((s = (lc >> 16) & 255) != 0) sym_name_table[s] = sp[u].name1;
if ((s = (lc >> 24) & 255) != 0) sym_name_table[s] = sp[u].name2;
}
if (LanguageIsCPlusPlus)
{ lexclass[':'] = mklc(l_coloncpp, s_colon, s_coloncolon, 0); /* charinfo not really used */
sym_name_table[s_coloncolon] = "::";
}
}
#ifdef EXTENSION_VALOF
/* 'resultis' is a funny (experimental) syntax extension */
resultisword = sym_insert_id("resultis");
#endif
curchar = NOTACHAR; /* Kill lookahead */
curlex.sym = s_nothing;
errs_on_this_sym = 0;
lex_strend = lex_strptr = (char *)DUFF_ADDR;
endofsym_fl.filepos = -1; /* mark as invalid */
lexbuf_max = 0; lexbuf_vec = (SymBuf *)DUFF_ADDR; nextsym_lookaside = 0;
buffersym_bufidx = -1;
nextsym_put_handle = -1;
#ifdef CPLUSPLUS
{ restorable_names_list = NULL;
template_old_sv = template_new_sv = NULL;
save_names(YES);
}
#endif
}
void lex_beware_reinit()
{ /* this routine patches the fact that an (illegal) C program of the */
/* form 'int a = 1 "abc"' or 'f(){} "abc"' needs to be able to */
/* print out "abc" in an error message even though Local store will */
/* have been clobbered by alloc_reinit(). Move it to Global store! */
if (isstring_(curlex.sym))
{ char *oval = curlex.a1.s;
curlex.a1.s = (char *)GlobAlloc(SU_Other, pad_to_word(curlex.a2.len));
memcpy(curlex.a1.s, oval, (size_t)curlex.a2.len);
}
}
void lex_reinit()
{
lex_strend = lex_strptr = (char *)DUFF_ADDR; /* better to use ""? */
nextlex.sym = s_nothing;
#ifdef CALLABLE_COMPILER
curchar = NOTACHAR;
#endif
}
/* End of lex.c */
|
stardot/ncc | tests/795.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"
/********************* 795 ***********************/
void t_795() {
/* Actually, if the fault in thread 795 is present, compiling
this will cause the compiler to crash.
*/
char b[4];
strcpy(b, "");
EQI(b[0], 0);
}
/********************* ***********************/
int main(void)
{
BeginTest();
t_795();
EndTest();
return 0;
}
|
stardot/ncc | ccapple/options.h | <reponame>stardot/ncc<filename>ccapple/options.h
/*
* 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$
*/
/*
* This is a prototype file documenting (some of) the available
* things which might go in target.h or options.h.
* Insert all such flags in here.
*/
#ifndef _options_LOADED
#define _options_LOADED
/* Include the following line to make an Apple APG compiler;
* Exclude it to make a standard toolkit compiler.
*/
/*#define TARGET_IS_APPLEAPGMACHINE 1*/
/*
* Firstly set TARGET_MACHINE and TARGET_SYSTEM. Note that you should
* follow the general line below.
*/
#ifdef TARGET_IS_APPLEAPGMACHINE
# define TARGET_MACHINE "Apple APG Machine"
/*
* Since host.h is #included previously we can simply make the TARGET
* OS depend on host, e.g.
*/
# define TARGET_SYSTEM "Apple Newton"
# define TARGET_IS_APPLEAPG 1
# define HOST_OBJECT_INCLUDES_SOURCE_EXTN 1 /* .c -> .c.o */
#else
# define TARGET_SYSTEM ""
# define TARGET_IS_RISC_OS 1
#endif
#define TARGET_ENDIANNESS_CONFIGURABLE 1
#define TARGET_DEFAULT_BIGENDIAN 1 /* 1 => bigendian default */
/* Now here, or more likely in target.h you specify machine properties */
/* #define TARGET_IS_BIG_ENDIAN 1 /* -- if your target is big endian... */
/* #define TARGET_IS_LITTLE_ENDIAN 1 -- if your target is little endian */
#define DO_NOT_EXPLOIT_REGISTERS_PRESERVED_BY_CALLEE 1
/* #define TARGET_STACK_MOVES_ONCE 1 / * Experimental option */
#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. */
/*
* Now parameterisations as to facilities of the compiler you wish,
* note that you are unlikely to need to specify many of these.
*/
/* #define EXTENSION_VALOF 1 -- to build a compiler with ACN's extension */
/* #define NO_ASSEMBLER_OUTPUT 1 -- to build a compiler sans ... capability */
/* #define NO_OBJECT_OUTPUT 1 -- to build a compiler sans ... capability */
/* #define NO_LISTING_OUTPUT 1 -- to build a compiler sans ... capability */
/* #define NO_INSTORE_FILES 1 -- to build a compiler sans in-store hdrs */
/* #define NO_DEBUGGER 1 -- to build a compiler sans debugger suppt */
/* #define NO_SELF_CHECKS 1 -- to avoid building checks aimed at itself */
/* #define NO_VERSION_STRINGS 1 -- to avoid module version strings */
#ifndef RELEASE_VSN
# define ENABLE_ALL 1 /* -- to enable all debugging options */
#endif
#ifdef TARGET_IS_APPLEAPGMACHINE
# define EXTENSION_COUNTED_STRINGS 1 /* to enable Pascal-style strings */
# 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 C_ENV_VAR "ARMCInclude"
# define PCS_DEFAULTS (PCS_CALLCHANGESPSR + PCS_NOSTACKCHECK)
# ifndef DRIVER_OPTIONS
# define DRIVER_OPTIONS { "-zps1", NULL } /* -- e.g. no stack checks */
# endif
#else /* toolkit compiler */
# define C_ENV_VAR "ARMLIB"
# define PCS_DEFAULTS PCS_CALLCHANGESPSR /* 32 bit */
/* + PCS_FPE3 */
/* + PCS_NOSTACKCHECK */
/* + PCS_REENTRANT */
/* + PCS_FPREGARGS */
# ifndef DRIVER_OPTIONS
# define DRIVER_OPTIONS { NULL }
# endif
#endif
# define NO_STATIC_BANNER 1
pascal void SpinCursor(short increment); /* copied from CursorCtl.h */
#define ExecuteOnSourceBufferFill() SpinCursor(1)
#define CHAR_CR '\r' /* like MPW C, '\r' == 10 and '\n' == 13 */
/* #define CORRECT_IS_BETTER_THAN_FAST 1 /* fix bug in pp.c */
#endif
/* end of ccapple/options.h */
|
stardot/ncc | mip/cseguts.h | /*
* mip/cseguts.h: CSE: internal interfaces
* Copyright (C) Acorn Computers Ltd., 1988.
* Copyright 1991-1997 Advanced Risc Machines Limited. All rights reserved
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
#ifndef _cseguts_h
#define _cseguts_h 1
#include "regsets.h"
#define CSEDebugLevel(n) (cse_debugcount > (n))
#define E_UNARYK 0 /* unaryop const */
#define E_UNARY 1 /* unaryop Exprn */
#define E_BINARYK 2 /* Exprn binaryop const */
#define E_BINARY 3 /* Exprn binaryop Exprn */
#define E_TERNARY 4 /* Exprn ? Exprn : Exprn */
#define E_LOAD 5 /* load value of vreg/binder/[Exprn, #offset] */
#define E_MISC 6 /* nasties. should be none? */
#define E_LOADR 7
#define E_CALL 8
typedef struct ExprnUse ExprnUse;
struct ExprnUse {
ExprnUse *cdr;
BlockHead *block;
int32 val_flags_icoden;
/* was (but can't make that 16-bit int safe)
struct {
int valbase: 2,
valn : 2,
flags: 5,
icoden: 23;
} ix;
*/
};
#define U_COMMUTATIVEFN 0x40 /* Just arg to find_exprn: not in an ExprnUse */
#define U_NOTDEF2 0x20 /* ... (U_PEEK, too) */
#define U_NOTREF 0x10
#define U_NOTDEF 0x08
#define U_PEEK 0x04
#define U_STORE 0x02
#define U_LOCALCSE 0x01
#define u_block_(x) ((x)->block)
#define flags_(x) ((((x)->val_flags_icoden) >> 4) & 0x1f)
#define icoden_(x) ((ptrdiff_t)(((x)->val_flags_icoden) >> 9))
#define IsRealIcode(x) (icoden_(x) != -1)
#define valno_(x) (((x)->val_flags_icoden) & 0x3)
#define nvals_(x) ((((x)->val_flags_icoden)>>2) & 0x3)
#define vfi_(v, f, i) ((((int32)(i)) << 9) | ((int32)(f) << 4) | (v))
#define setflag_(x, f) ((x)->val_flags_icoden |= (f) << 4)
#define setvalno_(x, v) ((x)->val_flags_icoden = ((x)->val_flags_icoden & ~3L) | (v))
#define setnvals_(x, v) ((x)->val_flags_icoden = ((x)->val_flags_icoden & ~(3L<<2)) | ((v)<<2))
#define useicode_(a) (blkcode_(u_block_(a))[icoden_(a)])
typedef struct LocList LocList;
typedef struct Exprn Exprn;
typedef struct Location Location;
struct Exprn {
Exprn *cdr; /* hash bucket chain */
J_OPCODE op;
int32 nodeid; /* nodeno<<5 | alias | type, see mknodeid_(). */
ExprnUse *uses;
VRegSetP leaves; /* set of Locations on which this Exprn depends */
union {
struct {
bool waslive;
LocList *locs; /* locations with this value */
} a; /* during available expression analysis */
int32 newid; /* during renumbering */
} v;
union {
struct { /* unary operand */
Exprn *e1;
} unary;
struct {
IPtr m; /* immediate const (or binder for ADCON) */
} unaryk;
struct {
Binder *b; /* see unaryk */
} unarykb;
struct {
FloatCon *f; /* ADCONF/D, MOVF/DK */
} unarykf;
struct {
Int64Con *i; /* ADCONLL */
} unaryki64;
struct {
StringSegList *s; /* STRING */
} unaryks;
struct { /* load or store some location */
Location *loc;
} loc;
struct {
Exprn *e1;
int32 m;
} binaryk;
struct {
Exprn *e1;
Exprn *e2;
} binary;
struct {
VRegnum r;
Location *rloc;
} loadr;
struct {
Exprn *e1;
Exprn *e2;
Exprn *e3;
J_OPCODE mask;
} ternary;
struct {
Binder *primary;
int32 argres; /* a jopcode argdesc, with the function result
type replacing the K_FLAGS */
Exprn *arg[1];
} call;
} u;
};
#define mknodeid_(nodeno, aliasandtype) ((nodeno)<<5 | (aliasandtype))
#define exid_(e) ((e)->nodeid >> 5)
#define extype_(e) ((e)->nodeid & 0xf)
#define EX_ALIASandTYPE 0x1f
#define EX_ALIAS 0x10
#define exalias_(e) ((e)->nodeid & EX_ALIAS)
#define e1_(e) ((e)->u.binary.e1)
#define e1k_(e) ((e)->u.unaryk.m)
#define e1b_(e) ((e)->u.unarykb.b)
#define e1f_(e) ((e)->u.unarykf.f)
#define e1i64_(e) ((e)->u.unaryki64.i)
#define e1s_(e) ((e)->u.unaryks.s)
#define e2_(e) ((e)->u.binary.e2)
#define e2k_(e) ((e)->u.binaryk.m)
#define e3_(e) ((e)->u.ternary.e3)
#define exmask_(e) ((e)->u.ternary.mask)
#define exloc_(e) ((e)->u.loc.loc)
#define exloadr_(e) ((e)->u.loadr.r)
#define exloadrloc_(e) ((e)->u.loadr.rloc)
#define exfn_(e) ((e)->u.call.primary)
#define exfntype_(e) ((e)->u.call.argres & REGSORTMASK)
#define exargdesc_(e) ((e)->u.call.argres & ~REGSORTMASK)
#define exnargs_(e) k_argregs_((e)->u.call.argres)
#define exargisfp_(e,i) k_argisfp_((e)->u.call.argres,i)
#define exnres_(e) k_resultregs_((e)->u.call.argres)
#define exarg_(e, i) ((e)->u.call.arg[i])
#define exlocs_(e) ((e)->v.a.locs)
#define exwaslive_(e) ((e)->v.a.waslive)
#define exnewid_(e) ((e)->v.newid)
#define exuses_(e) ((e)->uses)
#define exop_(e) ((e)->op)
#define exleaves_(e) ((e)->leaves)
#define is_calln(ex) ((exop_(ex) == J_CALLK || exop_(ex) == J_OPSYSK) && \
exnres_(ex) > 1)
typedef struct ExSet ExSet;
struct ExSet {
ExSet *cdr;
Exprn *exprn;
};
#define exs_ex_(p) ((p)->exprn)
typedef uint32 LocType;
/* LOC_xxx values can be store references (0..7) or LOC_VAR/LOC_PVAR */
#define LOC_(MEM_x) (MEM_x)
#define LOC_VAR 8
#define LOC_PVAR 9 /* non-local or address taken */
#define LOC_anyVAR (8+16) /* used in masks to detect LOC_VAR/LOC_VAR. */
#define LOC_REG 16
#define LOC_REALBASE 32
#define LOC_CONST 64
#define LOC_LOCAL 128
#define LOC_PEEK 256
struct Location {
Location *cdr;
ExSet *curvalue; /* the set of current values or Null if unknown */
uint32 idandtype; /* id<<8 | LOC_xxxx | LOC_REALBASE, see mkidandtype_() */
VRegSetP users; /* the set of Exprns killed if this location is */
/* stored into (those with this as a leaf). */
VRegSetP aliasusers; /* union over possible aliases of alias->users */
/* (includes this->users) */
Exprn *load; /* the Exprn which is a load from this location.
* (A plain load if the location is narrow)
*/
Location *synonym;
union {
struct {
Binder *binder;
LocType type;
} var;
struct {
VRegnum regno;
} reg;
struct {
int32 offset;
Exprn *base;
} mem;
} u;
};
#define mkidandtype_(id, type) ((id) << 8 | (type))
#define locvalue_(p) ((p)->curvalue)
#define loctype_(p) ((p)->idandtype & 0x1f)
#define locrealbase_(p) ((p)->idandtype & LOC_REALBASE)
#define locconst_(p) ((p)->idandtype & LOC_CONST)
#define locid_(p) ((p)->idandtype >> 8)
#define locreg_(p) ((p)->u.reg.regno)
#define locbind_(p) ((p)->u.var.binder)
#define locvartype_(p) ((p)->u.var.type)
#define locbase_(p) ((p)->u.mem.base)
#define locoff_(p) ((p)->u.mem.offset)
#define locsynonym_(p) ((p)->synonym)
#define locload_(p) ((p)->load)
#define ispublic(p) (loctype_(p) != LOC_VAR && !((p)->idandtype & LOC_LOCAL))
typedef struct CSEDef CSEDef;
typedef struct CSEUseList CSEUseList;
typedef struct SavedLocVals SavedLocVals;
struct CSEBlockHead {
VRegSetP wanted, available;
VRegSetP wantedlater;
VRegSetP wantedonallpaths;
VRegSetP killed;
CSEDef *defs;
ExSet *cmp;
SavedLocVals *locvals;
VRegnum ternaryr;
CSEDef *defs2;
CSEUseList *refs;
char reached, killedinverted, loopempty, scanned;
};
#define blk_defs_(p) (blkcse_(p)->defs)
#define blk_wanted_(p) (blkcse_(p)->wanted)
#define blk_wantedlater_(p) (blkcse_(p)->wantedlater)
#define blk_wantedonallpaths_(p) (blkcse_(p)->wantedonallpaths)
#define blk_available_(p) (blkcse_(p)->available)
#define blk_killed_(p) (blkcse_(p)->killed)
#define blk_killedexprns_(p) (blkcse_(p)->killedexprns)
#define blk_reached_(p) (blkcse_(p)->reached)
#define blk_pred_(p) (blkusedfrom_(p))
#define blk_killedinverted_(p) (blkcse_(p)->killedinverted)
#define blk_scanned_(p) (blkcse_(p)->scanned)
#define LOOP_NONEMPTY 1
#define LOOP_EMPTY 2
#define blk_loopempty_(p) (blkcse_(p)->loopempty)
#define blk_locvals_(p) (blkcse_(p)->locvals)
#define blk_cmp_(p) (blkcse_(p)->cmp)
#define blk_ternaryr_(p) (blkcse_(p)->ternaryr)
#define blk_defs2_(p) (blkcse_(p)->defs2)
#define blk_refs_(p) (blkcse_(p)->refs)
#define blockkills(n, b) (!cseset_member(n, blk_killed_(b)) == (blk_killedinverted_(b)))
#define blklabname_(p) lab_name_(blklab_(p))
#define EXPRNSEGSIZE 512
#define EXPRNINDEXSIZE 64
#define EXPRNSEGBITS 9
extern Exprn **exprnindex[EXPRNINDEXSIZE];
#define exprn_(id) (exprnindex[(id)>>EXPRNSEGBITS])[(id)&(EXPRNSEGSIZE-1)]
#define CSEAlloc SynAlloc
#define CSEAllocType AT_Syn
#define CSEList4 syn_list4
#define CSEList3 syn_list3
#define CSEList2 syn_list2
#define CSENew NewSyn
#define CSENewN NewSynN
#define CSENewK NewSynK
#define cseset_insert(x, s, oldp) s = vregset_insert(x, s, oldp, &cseallocrec)
#define cseset_delete(x, s, oldp) s = vregset_delete(x, s, oldp)
#define cseset_copy(s) vregset_copy(s, &cseallocrec)
#define cseset_discard(s) vregset_discard(s)
#define cseset_equal(s1, s2) vregset_equal(s1, s2)
#define cseset_compare(s1, s2) vregset_compare(s1, s2)
#define cseset_union(s1, s2) s1 = vregset_union(s1, s2, &cseallocrec)
#define cseset_intersection(s1, s2) s1 = vregset_intersection(s1, s2)
#define cseset_difference(s1, s2) s1 = vregset_difference(s1, s2)
#define cseset_member(x, s) vregset_member(x, s)
#define cseset_map(s, f, arg) vregset_map(s, f, arg)
#define cseset_size(s) (length((List *)(s)))
extern void cse_printset(VRegSetP s);
extern VRegSetAllocRec cseallocrec;
typedef struct SetSPList SetSPList;
struct SetSPList {
SetSPList *cdr;
BlockHead *block;
Icode *icode;
};
extern SetSPList *setsplist;
void cse_print_loc(Location const *x);
void cse_print_node(Exprn const *p);
void cse_printexits(int32 flags, LabelNumber *exit, LabelNumber *exit1);
bool cse_KillExprRef(ExSet *s, Icode *p);
bool cse_AddLocalCSE(Exprn *node, int valno, int nvals, BlockHead *b);
/* A use of node has occurred, with a previous evaluation in the same
basic block (b) still alive. No decision has been made as to the
desirability of making it into a CSE. Return value indicates whether
a CSE has been made.
*/
bool cse_AddPredecessor(LabelNumber *lab, BlockHead *b);
void cse_RemovePredecessor(LabelNumber *lab, BlockHead *b);
void cse_scanblocks(BlockHead *top);
Exprn *cse_AdconBase(Exprn *ex, bool allowvaroffsets);
extern ExprnUse *ExprnUse_New(ExprnUse *old, int flags, int valno);
bool cse_KilledInBlock(int32 expid);
bool ExSetsOverlap(ExSet const *a, ExSet const *b);
void ExSet_TransferExprnsInSet(VRegSetP *s1, VRegSetP *s2, ExSet const *set);
/* For all Exprns in <set> which are also in the set (of Exprn ids) */
/* <s1>, remove them from <s1> and add to <s2>. */
CSEBlockHead *CSEBlockHead_New(void);
#define MOVKinSet(set) ExSet_OpMember(set, J_MOVK, 0)
#define MOVFKinSet(set) ExSet_OpMember(set, J_MOVFK, 0)
#define MOVDKinSet(set) ExSet_OpMember(set, J_MOVDK, 0)
ExSet *ExSet_OpMember(ExSet *set, J_OPCODE op, int32 ignorebits);
bool ExSet_Member(Exprn const *e, ExSet const *set);
#if defined TARGET_HAS_SCALED_ADDRESSING || defined TARGET_HAS_SCALED_OPS || \
defined TARGET_HAS_SCALED_ADD
# define OpIsShifted(op) (((op) & J_SHIFTMASK) != 0)
# define UnshiftedOp(op) ((op) & ~J_SHIFTMASK)
# define OpWithShift(op, op1) ((op) | ((op1) & J_SHIFTMASK))
# define NEGINDEX J_NEGINDEX
int32 ShiftedVal(J_OPCODE op, int32 b);
#else
# define ShiftedVal(op,b) (b)
# define OpIsShifted(op) NO
# define UnshiftedOp(op) (op)
# define OpWithShift(op, op1) (op)
# define NEGINDEX 0L
#endif
FloatCon *CSE_NewDCon(DbleBin const *val);
FloatCon *CSE_NewFCon(FloatBin const *val);
Int64Con *CSE_NewLLCon(int64 const *ip);
bool CSE_Compare_F(int *res, FloatBin const *a, FloatBin const *b);
bool CSE_Compare_D(int *res, FloatCon const *a, FloatCon const *b);
FloatCon *CSE_EvalUnary_F(J_OPCODE op, ExSet *ex);
FloatCon *CSE_EvalUnary_D(J_OPCODE op, ExSet *ex);
bool CSE_EvalUnary_I(J_OPCODE op, int32 *resp, ExSet *ex);
FloatCon *CSE_EvalBinary_F(J_OPCODE op, ExSet *as, FloatCon const *b);
FloatCon *CSE_EvalBinary_D(J_OPCODE op, ExSet *as, FloatCon const *b);
bool CSE_EvalBinary_I(J_OPCODE op, int32 *resp, Exprn *ax, int32 b);
FloatCon *CSE_CanonicalFPConst(FloatCon *old);
Int64Con *CSE_CanonicalLLConst(Int64Con *old);
typedef struct {
union {
DbleBin d;
int64 i;
} val;
bool isdouble;
} DRes;
bool CSE_EvaluableDoubleValuedCall(
Expr const *fn, VRegnum res, int32 argres, ExSet *arg[], DRes *dresp);
bool CSE_EvaluableIntValuedCall(
Expr const *fn, VRegnum res, int32 argres, ExSet *arg[], int32 *resp);
extern BlockHead *cse_currentblock;
#endif
/* end of mip/cseguts.h */
|
stardot/ncc | tests/2099.c | /*
* 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"
/********************* 2099 ***********************/
void GLPen_TPtoCA (float x1, float y1, float x2, float y2, float x3, float y3,
float *xc, float *yc, float *sweep)
{
float a1, b1, c1, a2, b2, c2, xx1, yy1, denom;
xx1 = x1*x1;
yy1 = y1*y1;
a1 = 2.0F * (x2 - x1);
b1 = 2.0F * (y2 - y1);
c1 = xx1 - x2*x2 + yy1 - y2*y2;
a2 = 2.0F * (x3 - x1);
b2 = 2.0F * (y3 - y1);
c2 = xx1 - x3*x3 + yy1 - y3*y3;
denom = (a1*b2 - a2*b1);
*yc = (a2*c1 - a1*c2) / denom;
*xc = (b1*c2 - b2*c1) / denom;
return;
}
/* no executable test */
/********************* ***********************/
int main(void)
{
BeginTest();
EQI(0,0);
EndTest();
return 0;
}
|
stardot/ncc | mip/dwarf.c | /*
* C compiler file mip/dwarf.c
* Copyright: (C) 1995, Advanced RISC Machines Limited. All rights reserved.
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
/* The debug table formatter for DWARF debug tables, for embedding in ELF
or other object files.
*/
#ifdef __STDC__
# include <string.h>
#else
# include <strings.h>
#endif
#include <stddef.h>
#include "globals.h"
#if defined(TARGET_HAS_DEBUGGER) && defined(TARGET_HAS_DWARF)
#include "syn.h" /* for syn_note_generated_fn */
#ifdef TARGET_HAS_MULTIPLE_DEBUG_FORMATS
#define dbg_tableindex dwarf_tableindex
#define dbg_notefileline dwarf_notefileline
#define dbg_addcodep dwarf_addcodep
#define dbg_scope dwarf_scope
#define dbg_topvar dwarf_topvar
#define dbg_type dwarf_type
#define dbg_proc dwarf_proc
#define dbg_locvar dwarf_locvar
#define dbg_locvar1 dwarf_locvar1
#define dbg_commblock dwarf_commblock
#define dbg_enterproc dwarf_enterproc
#define dbg_bodyproc dwarf_bodyproc
#define dbg_return dwarf_return
#define dbg_xendproc dwarf_xendproc
#define dbg_define dwarf_define
#define dbg_undef dwarf_undef
#define dbg_include dwarf_include
#define dbg_notepath dwarf_notepath
#define dbg_init dwarf_init
#define dbg_finalise dwarf_finalise
#define dbg_setformat dwarf_setformat
#define dbg_final_src_codeaddr dwarf_final_src_codeaddr
#define dbg_needsframepointer dwarf_needsframepointer
#define obj_notefpdesc dwarf_notefpdesc
#define dbg_debugareaexists dwarf_debugareaexists
#define dbg_writedebug dwarf_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, thissym etc */
#include "bind.h"
#include "simplify.h" /* mcrep */
#include "dwarf.h"
#include "unmangle.h" /* unmangle() */
#include "dw_int.h"
Symstr *dw_debug_sym, *dw_lineinfo_sym;
Symstr *dw_macro_sym, *dw_abbrev_sym, *dw_location_sym;
static int dw_version;
static uint32 dw_nameindex_size;
static Dw_ItemList *dw_section;
#ifndef TARGET_HAS_MULTIPLE_DEBUG_FORMATS
char dbg_name[] = "DWARF";
int usrdbgmask;
#endif
static void dw_sub_init(void);
static bool dw_init_done, dw_sub_init_done;
#define DbgAlloc(n) GlobAlloc(SU_Dbg, n)
#define DbgNew(type) ((type *)DbgAlloc(sizeof(type)))
Dw_ItemList *dw_list, *dw_listproc;
Dw_ItemList *dw_basetypes;
Dw_LocList *dw_loclist;
Dw_MacroList *dw_macrolist;
struct Dw_BaseSeg dw_baseseg;
typedef struct Dw_Scope Dw_Scope;
struct Dw_Scope {
Dw_Scope *cdr;
Dw_ItemList *item;
Dw_ItemList **childlist;
Dw_ItemList **childp;
};
static Dw_Scope *freescopes,
*scopestack;
#define Dw_ItemAlloc(variant, tag) \
Dw_ItemAlloc_S((size_t)(sizeof(dw_list->car.variant)+offsetof(Dw_ItemList,car)), tag)
static Dw_ItemList *Dw_ItemAlloc_S(size_t size, unsigned tag) {
Dw_ItemList *p = (Dw_ItemList *)DbgAlloc(size);
debsort_(p) = tag;
dbgloc_(p) = 0;
return p;
}
#define dw_additem(sort, tag) \
dw_additem_s((size_t)(sizeof(dw_list->car.sort)+offsetof(Dw_ItemList,car)), tag)
static Dw_ItemList *dw_additem_s(size_t size, unsigned tag) {
Dw_ItemList *p = (Dw_ItemList *)DbgAlloc(size);
debsort_(p) = tag;
sibling_(p) = NULL; *scopestack->childp = p; scopestack->childp = &sibling_(p);
cdr_(p) = dw_list; dw_list = p;
dbgloc_(p) = 0;
return p;
}
static Dw_ItemList *dw_addtoitemlist(Dw_ItemList *p) {
sibling_(p) = NULL; *scopestack->childp = p; scopestack->childp = &sibling_(p);
cdr_(p) = dw_list; dw_list = p;
return p;
}
static void PushScope(Dw_ItemList *item, Dw_ItemList **childp) {
Dw_Scope *p = freescopes;
if (p != NULL)
freescopes = cdr_(freescopes);
else
p = DbgNew(Dw_Scope);
cdr_(p) = scopestack; p->item = item; p->childp = childp; p->childlist = childp;
*childp = NULL;
scopestack = p;
}
static void PopScope(bool force) {
Dw_Scope *p = scopestack;
scopestack = cdr_(p);
cdr_(p) = freescopes;
freescopes = p;
if (*p->childlist != NULL || force) {
/* Normally, if the current scope has no child debug items, no end scope
* item is generated here. This works happily for DWARF1, where the
* criterion for an item to have children is that its sibling isn't the
* next item. For DWARF2, it works only if there are two sets of abbreviation
* entries for the parent item (one declaring there are children, one not).
* For items which almost always have children, less output is produced if
* there's only the 'has children' one, in which case an end of scope
* item must always be produced.
*/
Dw_ItemList *terminator = Dw_ItemAlloc(DEB_NULL, TAG_padding);
cdr_(terminator) = dw_list; dw_list = terminator;
sibling_(terminator) = NULL;
null_parent_(terminator) = p->childlist;
*p->childp = terminator;
}
}
Dw_PathList *dw_pathlist;
static Uint dw_pathindex;
Dw_FileList *dw_filelist;
static Uint dw_fileindex;
/* The next two vars are (code order) list & tail pointer */
Dw_FileCoord *dw_coord_p, **dw_coord_q;
Dw_FileCoord dw_coord_sentinel =
{ 0, /* cdr */
0, 0, /* file, nextinfile */
0, 0xffff, 0 /* line, col, codeaddr(set by dbg_fileinfo).*/
};
int32 dbg_tableindex(int32 dt_number)
{
IGNORE(dt_number);
return 0;
}
static Dw_FileList *Dw_FindFile(char const *name) {
Dw_FileList *p = dw_filelist;
for (; p != NULL; p = cdr_(p))
if (p->filename == name) return p;
p = DbgNew(Dw_FileList);
cdr_(p) = dw_filelist; p->filename = name; p->linelist = 0;
p->index = (name != NULL && StrEq(name, "<command line>")) ? 0 : ++dw_fileindex;
p->dir = NULL; p->timestamp = 0; p->filelength = 0;
dw_filelist = p;
return p;
}
void *dbg_notefileline(FileLine fl) {
Dw_FileList *x;
if (!dw_sub_init_done) dw_sub_init();
x = Dw_FindFile(fl.f);
if (usrdbg(DBG_LINE)) {
Dw_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 = DbgNew(Dw_FileCoord);
cdr_(l) = NULL,
l->nextinfile = x->linelist, x->linelist = l,
l->file = x, l->line = fl.l, l->col = fl.column,
l->codeaddr = -1;
l->codeseg = dw_init_done ? bindsym_(codesegment) : 0;
x->lastline = fl.l;
return (void *)l;
}
return DUFF_ADDR;
}
static Dw_ItemList *dw_listscope;
/* 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(void *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);
{ Dw_ItemList *p = dw_listscope, *next;
for (; p != NULL; p = next) {
next = startscope_next_(p);
startscope_codeaddr_(p) = codeaddr;
}
dw_listscope = NULL;
}
} else if (usrdbg(DBG_LINE)) {
Dw_FileCoord *p = (Dw_FileCoord *)dbgaddr;
if (debugging(DEBUG_Q))
cc_msg("%p ('%s' line %u/%u) @ %.6lx\n", 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;
*dw_coord_q = p;
dw_coord_q = &cdr_(p);
}
}
}
DataXref *dw_xrefs;
DataXref *Dw_Relocate(DataXref *xrefs, int32 where, Symstr const *symbol) {
return (DataXref*)global_list3(SU_Xref, xrefs, where, symbol);
}
uint32 Dw_WriteInlineString(char const *s, uint32 offset) {
uint32 n = strlen(s);
obj_writedebug(s, n+1);
return offset + n + 1;
}
uint32 Dw_WriteB(unsigned u, uint32 offset) {
char b[1];
b[0] = u; obj_writedebug(b, 1);
return offset + 1;
}
uint32 Dw_WriteBN(uint8 const *p, int32 n, uint32 offset) {
obj_writedebug(p, n);
return offset + n;
}
uint32 Dw_WriteH(uint32 u, uint32 offset) {
uint16 h[1];
h[0] = (uint16)u; obj_writedebug(h, 1+DBG_SHORTFLAG);
return offset + 2;
}
uint32 Dw_WriteW(uint32 u, uint32 offset) {
obj_writedebug(&u, 1+DBG_INTFLAG);
return offset + 4;
}
uint32 Dw_WriteL(uint32 const *d, uint32 offset) {
obj_writedebug(d, 2+DBG_INTFLAG);
return offset + 8;
}
uint32 Dw_WriteW_Relocated(uint32 w, Symstr const *sym, uint32 offset) {
dw_xrefs = Dw_Relocate(dw_xrefs, offset, sym);
return Dw_WriteW(w, offset);
}
/* End of file/line co-ordinate code */
static Dw_TypeRep *Dw_PrimType(int typecode) {
Dw_TypeRep *p = dw_basetypes;
for (; p != NULL; p = basetype_next_(p))
if (basetype_typecode_(p) == typecode)
return p;
p = dw_additem(DEB_BASETYPE, DW_TAG_base_type);
basetype_next_(p) = dw_basetypes; dw_basetypes = p;
basetype_typecode_(p) = typecode;
basetype_qual_(p) = NULL;
return p;
}
static void dw_typerep(TypeExpr *, Dw_TypeRep **typep);
typedef struct Dw_fmlList Dw_fmlList;
struct Dw_fmlList {
Dw_fmlList *cdr;
Binder *fb;
Dw_ItemList *p;
};
static Dw_fmlList *dw_fmllist;
static FileLine dbg_invented_fl = {0, 0, 0};
static void dw_generate_default_fn(Expr *e, Dw_ItemList *fml) {
Symstr *fname = sym_insert_id(symname_(gensymval(YES)));
TypeExprFnAux s;
Cmd *p = (Cmd *)GlobAlloc(SU_Other, (int32)offsetof(Cmd, cmd2));
TypeExpr *ftype = g_mkTypeExprfn(t_fnap, typeofexpr(e), 0, 0,
packTypeExprFnAux(s, 0, 0, 0, 0, 0));
DeclRhsList *d = mkDeclRhsList(fname, ftype, bitofstg_(s_static)|b_fnconst);
Binder *fbind = instate_declaration(d, TOPLEVEL);
binduses_(fbind) |= u_referenced;
p->fileline = dbg_invented_fl;
h0_(p) = s_return;
cmd1e_(p) = optimise0(mk_expr1(s_return, typeofexpr(e), e));
syn_note_generated_fn(mkTopDeclFnDef(s_fndef, fbind, NULL,
mk_cmd_block(dbg_invented_fl, 0, mkCmdList(0, p)), 0));
{ Dw_fmlList *l = DbgNew(Dw_fmlList);
cdr_(l) = dw_fmllist, l->fb = fbind, l->p = fml, dw_fmllist = l;
}
}
static void dw_formalparameterlistrep(TypeExpr *x) {
FormTypeList *ft = typefnargs_(x);
for (; ft != NULL; ft = ft->ftcdr) {
Dw_ItemList *p = Dw_ItemAlloc(DEB_FORMAL, DW_TAG_proctype_formal);
formal_invented_(p) = NO;
formal_name_(p) = ft->ftname;
if (LanguageIsCPlusPlus && ft->ftname != NULL && ft->ftname == thissym)
formal_invented_(p) = YES;
dw_typerep(ft->fttype, &formal_type_(p));
dw_addtoitemlist(p);
{ Expr *e = ft->ftdefault;
if (e != NULL)
switch (h0_(e)) {
default:
dw_generate_default_fn(e, p);
/* drop through */
case s_integer:
case s_floatcon:
case s_string:
formal_defltexpr_(p) = e;
break;
}
else
formal_defltexpr_(p) = NULL;
}
}
if (fntypeisvariadic(x))
dw_additem(DEB_REST, DW_TAG_unspecified_parameters);
}
/*
static bool dw_hasdefaultvalues(FormTypeList *ft) {
for (; ft != NULL; ft = ft->ftcdr)
if (ft->ftdefault != NULL)
return YES;
return NO;
}
*/
static Dw_TypeRep *dw_arrayrep(TypeExpr *t, Expr *e)
{ /* e is the array size. Since C arrays start at 0, the upper bound is */
/* one less */
Dw_ItemList *p = Dw_ItemAlloc(DEB_ARRAY, DW_TAG_array_type);
if (e && h0_(e) == s_binder) e = NULL;
array_open_(p) = e == NULL;
dw_typerep(t, &array_basetype_(p));
array_lowerbound_(p) = 0;
array_upperbound_(p) = e ? evaluate(e)-1:0;
array_size_(p) = sizeoftype(t);
array_qual_(p) = NULL;
dw_addtoitemlist(p); /* do this last (typerep above) */
PushScope(p, &array_children_(p));
{ Dw_ItemList *bound = dw_additem(DEB_ARRAYBOUND, DW_TAG_array_bound);
arraybound_open_(bound) = array_open_(p);
arraybound_upperbound_(bound) = array_upperbound_(p);
}
PopScope(NO);
return p;
}
static void move_children(Dw_ItemList *p, Dw_ItemList *prevlist) {
/* Move the child entries of p, currently at the head of dw_list (up to */
/* but not including prevlist) to immediately before p (after it when the */
/* list is reversed) */
Dw_ItemList *end = dw_list,
*before;
for (; cdr_(end) != prevlist; end = cdr_(end)) continue;
for (before = prevlist; cdr_(before) != p; before = cdr_(before)) continue;
cdr_(before) = dw_list; cdr_(end) = p;
dw_list = prevlist;
}
/* bit like dw_additem(); makes move_children() redundant
for structs. maybe enum too, but that's less important.
*/
static void move_to_top(Dw_ItemList *p)
{ Dw_ItemList *before = cdr_(p);
for (; before && sibling_(before) != p; before = cdr_(before));
if (before) sibling_(before) = sibling_(p);
if (!LanguageIsCPlusPlus)
{ /* how could this be possible??? */
for (before = cdr_(p); before; before = cdr_(before))
if ((debsort_(before) == DW_TAG_structure_type ||
debsort_(before) == DW_TAG_union_type ||
debsort_(before) == DW_TAG_class_type) &&
struct_children_(before) == p)
{ struct_children_(before) = sibling_(p);
break;
}
}
if (sect_children_(dw_section) == p)
sect_children_(dw_section) = sibling_(p);
cdr_(sibling_(p)) = cdr_(p);
sibling_(p) = NULL;
cdr_(p) = dw_list; dw_list = p;
*scopestack->childp = p; scopestack->childp = &sibling_(p);
}
static void dw_typeinternal(Symstr *name, Dw_TypeRep *t, TypeExpr *type);
static Dw_ItemList *Dw_ProcDeclRep(Symstr *name, Binder *b, Dw_ItemList *parent, int ext) {
Dw_ItemList *d = Dw_ItemAlloc(DEB_PROCDECL, DW_TAG_procdecl);
TypeExpr *t = princtype(bindtype_(b));
dw_typerep(typearg_(t), &procdecl_type_(d));
procdecl_name_(d) = symname_(name);
procdecl_variadic_(d) = fntypeisvariadic(t);
procdecl_global_(d) = ext;
procdecl_stg_(d) = bindstg_(b);
procdecl_parent_(d) = parent;
procdecl_voffset_(d) = (bindstg_(b) & bitofstg_(s_virtual)) ? bindxx_(b) : -1;
dw_addtoitemlist(d); /* do this last (typerep above) */
PushScope(d, &procdecl_children_(d));
dw_formalparameterlistrep(t);
PopScope(dw_version == 2);
binddbg_(b) = (IPtr)d;
return d;
}
static Dw_TypeRep *dw_structentry(Dw_TypeRep *p, TagBinder *b, TypeExpr *x) {
SET_BITMAP sort = tagbindbits_(b) & CLASSBITS;
int itemsort = sort == bitoftype_(s_struct) ? DW_TAG_structure_type :
sort == bitoftype_(s_union) ? DW_TAG_union_type :
DW_TAG_class_type;
#if 0
Dw_ItemList *prev_dw_list = NULL;
#endif
if (p == NULL) {
p = dw_additem(DEB_STRUCT, itemsort);
struct_size_(p) = 0; /* filled in later */
struct_name_(p) = isgensym(tagbindsym_(b)) ? NULL : symname_(tagbindsym_(b));
struct_children_(p) = NULL;
struct_qual_(p) = NULL;
struct_friends_(p) = NULL;
if (b != NULL) tagbinddbg_(b) = (IPtr)p;
if (!(tagbindbits_(b) & TB_DEFD)) {
debsort_(p) = DW_TAG_fref;
struct_undefsort_(p) = itemsort;
struct_size_(p) = 0;
return p;
}
} else {
debsort_(p) = itemsort;
if (LanguageIsCPlusPlus) struct_friends_(p) = b->friends;
#if 0
if (p != dw_list) prev_dw_list = dw_list;
#else
if (p != dw_list) move_to_top(p);
#endif
}
struct_size_(p) = sizeoftype(x);
{ StructPos sp;
Dw_ItemList **pp = &struct_children_(p);
ClassMember *l;
PushScope(p, pp);
structpos_init(&sp, b);
for (l = tagbindmems_(b); l != 0; l = memcdr_(l))
if (memsv_(l) != NULL &&
(structfield(l, sort, &sp) || LanguageIsCPlusPlus)) {
if (LanguageIsCPlusPlus && attributes_(l) & (CB_BASE|CB_VBASE)) {
Dw_ItemList *base = dw_additem(DEB_INHERIT, DW_TAG_inheritance);
TagBinder *tb_base = typespectagbind_(princtype(memtype_(l)));
inherit_type_(base) = (Dw_TypeRep *)tagbinddbg_(tb_base);
inherit_offset_(base) = sp.woffset;
inherit_virt_(base) = (attributes_(l) & CB_VBASE) != 0;
} else if (h0_(memtype_(l)) == t_ovld || attributes_(l) & CB_ANON ||
h0_(l) == s_tagbind) {
/* nothing */
} else if (isfntype(memtype_(l))) {
Dw_ItemList *d = Dw_ProcDeclRep(memsv_(l), realbinder_(l), p, 0);
IGNORE(d);
} else if (bindstg_(l) & bitofstg_(s_typedef)) {
dw_typeinternal(bindsym_(l), 0, bindtype_(l));
} else if (h0_(l) == s_member || bindstg_(l) & b_pseudonym) {
Dw_ItemList *mem;
Dw_TypeRep *type;
if (sp.bsize == 0) {
dw_typerep(memtype_(l), &type);
} else {
TypeExpr te; te = *memtype_(l);
typespecmap_(&te) &= ~BITFIELD;
dw_typerep(&te, &type);
}
/* note that memsv is 0 for padding bit fields */
mem = dw_additem(DEB_MEMBER, DW_TAG_member);
member_offset_(mem) = (bindstg_(l) & b_pseudonym) ? -1 : sp.woffset;
member_name_(mem) = symname_(memsv_(l));
member_boffset_(mem) = (uint8)sp.boffset;
member_bsize_(mem) = (uint8)sp.bsize;
member_type_(mem) = type;
}
}
PopScope(NO);
}
#if 0
if (prev_dw_list != NULL && prev_dw_list != dw_list)
move_children(p, prev_dw_list);
#endif
return p;
}
static Dw_TypeRep *dw_enumentry(Dw_TypeRep *p, TagBinder *b) {
static unsigned const c[] =
{ FT_signed_char, FT_signed_short, FT_signed_integer, FT_signed_integer,
FT_unsigned_char, FT_unsigned_short, FT_unsigned_integer, FT_unsigned_integer
};
static char const s[] = { 1, 2, 4, 4, 1, 2, 4, 4};
Dw_ItemList *prev_dw_list = NULL;
if (p == NULL) {
p = dw_additem(DEB_ENUM, DW_TAG_enumeration_type);
enum_children_(p) = NULL;
enum_name_(p) = isgensym(tagbindsym_(b)) ? NULL : symname_(tagbindsym_(b));
enum_qual_(p) = NULL;
if (b != NULL) tagbinddbg_(b) = (IPtr)p;
if (!(tagbindbits_(b) & TB_DEFD)) {
debsort_(p) = DW_TAG_fref;
return p;
}
} else {
debsort_(p) = DW_TAG_enumeration_type;
prev_dw_list = dw_list;
}
{ int32 container = (tagbindbits_(b) & TB_CONTAINER) >> TB_CONTAINER_SHIFT;
enum_container_(p) = Dw_PrimType(c[container]);
enum_size_(p) = s[container];
}
PushScope(p, &enum_children_(p));
{ BindList *members = tagbindenums_(b);
for (; members != 0; members = members->bindlistcdr) {
Dw_ItemList *mem = dw_additem(DEB_ENUMERATOR, DW_TAG_enumerator);
Binder *elt = members->bindlistcar;
enumerator_name_(mem) = symname_(bindsym_(elt));
enumerator_val_(mem) = bindenumval_(elt);
}
}
PopScope(NO);
if (prev_dw_list != NULL) move_children(p, prev_dw_list);
return p;
}
static Dw_TypeRep *struct_typerep(TypeExpr *x) {
TagBinder *b = typespectagbind_(x);
Dw_TypeRep *t = (Dw_TypeRep *)tagbinddbg_(b);
if (t == NULL || /* not yet seen */
(debsort_(t) == DW_TAG_fref && (tagbindbits_(b) & TB_DEFD))
/* previously seen, (undefined), now defined */
) {
if (tagbindbits_(b) & bitoftype_(s_enum))
t = dw_enumentry(t, b);
else
t = dw_structentry(t, b, x);
}
return t;
}
static int typename_match(char *mangled, char *generic)
{ int l = strlen(generic);
if (mangled == generic) return 1;
if (StrnEq(mangled, generic, l) &&
StrnEq(mangled+l, "__", 2)) return 1;
return 0;
}
typedef struct Dw_QualType Dw_QualType;
struct Dw_QualType {
Dw_QualType *cdr;
int qual;
};
#define dw_mk_qualtype(t, p) ((Dw_QualType *)syn_list2(p, t))
static Dw_QualType *CVQualType(SET_BITMAP m, Dw_QualType *p) {
if (m & bitoftype_(s_const)) p = dw_mk_qualtype(DW_TAG_const_type, p);
if (m & bitoftype_(s_volatile)) p = dw_mk_qualtype(DW_TAG_volatile_type, p);
return p;
}
typedef struct Dw_ftList Dw_ftList;
struct Dw_ftList {
Dw_ftList *cdr;
TypeExpr *t;
Dw_ItemList *p;
};
static Dw_ftList *dw_ftlist;
static Dw_ItemList *find_ftlist(TypeExpr *te)
{ Dw_ftList *ft = dw_ftlist;
for (; ft != NULL; ft = cdr_(ft))
if (ft->t == te) return ft->p;
return NULL;
}
static Dw_TypeRep *dw_fnrep(TypeExpr *x) {
Dw_ItemList *t = find_ftlist(x);
if (t != NULL) return t;
t = Dw_ItemAlloc(DEB_PROCTYPE, DW_TAG_subroutine_type);
dw_typerep(typearg_(x), &proctype_type_(t));
proctype_qual_(t) = NULL;
dw_addtoitemlist(t);
PushScope(t, &proctype_children_(t));
dw_formalparameterlistrep(x);
PopScope(dw_version == 2);
{ Dw_ftList *p = DbgNew(Dw_ftList);
cdr_(p) = dw_ftlist;
p->t = x; p->p = t; dw_ftlist = p;
}
return t;
}
static Dw_TypeRep *dw_ptrtomemrep(TypeExpr *x)
{ Dw_ItemList *t = Dw_ItemAlloc(DEB_ARRAY, DW_TAG_ptr_to_member_type);
ptrtomem_container_(t) = (Dw_TypeRep *)tagbinddbg_(typespectagbind_(x));
dw_typerep(typearg_(x), &ptrtomem_type_(t));
ptrtomem_qual_(t) = NULL;
dw_addtoitemlist(t);
return t;
}
static void dw_typerep(TypeExpr *x, Dw_TypeRep **typep)
{ /* note that we do NOT call prunetype() here so we still see typedefs */
Dw_QualType *quals = NULL;
Dw_TypeRep *restype = NULL;
for (;;) {
switch (h0_(x)) {
case t_content:
quals = CVQualType(typeptrmap_(x), quals);
quals = dw_mk_qualtype(DW_TAG_pointer_type, quals);
x = typearg_(x);
continue;
case t_ref:
quals = CVQualType(typeptrmap_(x), quals);
quals = dw_mk_qualtype(DW_TAG_reference_type, quals);
x = typearg_(x);
continue;
case t_coloncolon:
restype = dw_ptrtomemrep(x);
break;
case t_subscript:
restype = dw_arrayrep(typearg_(x), typesubsize_(x));
break;
case t_fnap:
restype = dw_fnrep(x);
break;
case s_typespec:
{ SET_BITMAP m = typespecmap_(x);
quals = CVQualType(m, quals);
switch (m & -m) { /* LSB - unsigned/long etc. are higher */
case bitoftype_(s_enum):
restype = struct_typerep(x);
break;
case bitoftype_(s_struct):
case bitoftype_(s_class):
case bitoftype_(s_union):
restype = struct_typerep(x);
break;
case bitoftype_(s_typedefname):
{ Binder *b = typespecbind_(x);
/* is there already a table entry for it ? */
{ Dw_ItemList *l;
for ( l = dw_list ; l != NULL ; l = cdr_(l))
if ( debsort_(l)==DW_TAG_typedef &&
type_typex_(l)==bindtype_(b) &&
typename_match(type_name_(l), symname_(bindsym_(b)))) {
restype = l;
break;
}
if (l == NULL) syserr("typerep $b", b);
}
break;
}
case bitoftype_(s_char):
{ int32 mcr = mcrepoftype(x);
restype = Dw_PrimType((mcr & MCR_SORT_MASK) == MCR_SORT_SIGNED ?
FT_signed_char : FT_unsigned_char);
break;
}
case bitoftype_(s_int):
if (m & BITFIELD) syserr(syserr_dbg_bitfield);
{ int32 mcr = mcrepoftype(x);
int32 size = mcr & MCR_SIZE_MASK;
int tc;
if ((mcr & MCR_SORT_MASK) == MCR_SORT_SIGNED)
tc = size == 2 ? FT_signed_short :
size == 8 ? FT_signed_long_long :
FT_signed_integer;
else
tc = size == 2 ? FT_unsigned_short :
size == 8 ? FT_unsigned_long_long :
FT_unsigned_integer;
restype = Dw_PrimType(tc);
break;
}
case bitoftype_(s_double):
restype = Dw_PrimType((m & bitoftype_(s_short)) ? FT_float : FT_dbl_prec_float);
break;
case bitoftype_(s_bool):
restype = Dw_PrimType(FT_boolean);
break;
case bitoftype_(s_void):
restype = Dw_PrimType(FT_void);
break;
default:
syserr(syserr_dbg_typerep, x, (long)m);
restype = NULL;
return;
}
break;
}
/* drop through for now */
default:
syserr(syserr_dbg_typerep, x, (long)typespecmap_(x));
restype = NULL;
return;
}
break;
}
if (quals != NULL) {
Dw_TypeRep *basetype = restype;
Dw_TypeRep *q, **qp;
int n = 1;
int maxn = (int)length((List *)quals);
uint8 *qualmap = (uint8 *)SynAlloc(maxn);
uint8 *qualp = &qualmap[maxn];
switch (debsort_(restype)) {
case DW_TAG_ptr_to_member_type: qp = &ptrtomem_qual_(restype); break;
case DW_TAG_array_type: qp = &array_qual_(restype); break;
case DW_TAG_subroutine_type: qp = &proctype_qual_(restype); break;
case DW_TAG_enumeration_type: qp = &enum_qual_(restype); break;
case DW_TAG_fref:
case DW_TAG_class_type:
case DW_TAG_union_type:
case DW_TAG_structure_type: qp = &struct_qual_(restype); break;
case DW_TAG_typedef:
case DW_TAG_base_type: qp = &type_qual_(restype); break;
default: syserr("dw_typerep: %d", debsort_(restype));
qp = NULL;
}
for (; quals != NULL; quals = cdr_(quals), n++) {
*--qualp = quals->qual == DW_TAG_pointer_type ? MOD_pointer_to :
quals->qual == DW_TAG_reference_type ? MOD_reference_to :
quals->qual == DW_TAG_const_type ? MOD_const :
MOD_volatile;
for (; (q = *qp) != NULL; qp = &qualtype_next_(q))
if (qualtype_n_(q) > n) {
q = NULL;
break;
} else if (qualtype_n_(q) == n
&& memcmp(qualtype_map_(q), qualp, n) == 0) {
break;
}
if (q == NULL) {
q = dw_additem(DEB_QUALTYPE, quals->qual);
qualtype_type_(q) = restype;
qualtype_n_(q) = n;
qualtype_map_(q) = (uint8 *)DbgAlloc(n);
memcpy(qualtype_map_(q), qualp, n);
qualtype_next_(q) = *qp; *qp = q;
qualtype_basetype_(q) = basetype;
qualtype_qualifiedtype_(q) = restype;
}
restype = q;
}
}
if (typep != NULL) *typep = restype;
}
static void dw_addvar(Symstr *name, Dw_TypeRep *t,
StgClass stgclass, SymOrReg base, int32 addr, TypeExpr *type)
{ unsigned tag = stgclass >= Stg_ArgReg ? DW_TAG_formal_parameter: DW_TAG_variable;
Dw_ItemList *p = Dw_ItemAlloc(DEB_VAR, tag);
var_type_(p) = t;
var_stgclass_(p) = stgclass;
var_loc_(p) = addr;
var_sym_(p) = name;
var_base_(p) = base;
if (type != NULL) dw_typerep(type, &var_type_(p));
dw_addtoitemlist(p);
}
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
*/
Dw_ItemList *p;
SymOrReg base;
StgClass stg = (stgclass & DS_REG) ? Stg_Reg :
(stgclass & DS_EXT) ? Stg_Extern :
Stg_Static;
IGNORE(fl);
base.sym = NULL;
if (stgclass & (DS_EXT|DS_BSS))
base.sym = name, addr = 0;
#ifdef CONST_DATA_IN_CODE
else if (stgclass & DS_CODE)
base.sym = bindsym_(constdatasegment);
#endif
else if (!(stgclass & DS_REG))
base.sym = bindsym_(datasegment);
if (debugging(DEBUG_Q))
cc_msg("top var $r @ %.6lx\n", name, (long)addr);
if (stgclass != 0 && stg != Stg_Reg)
for ( p = dw_list ; p != NULL ; p = cdr_(p))
if ( debsort_(p) == DW_TAG_variable &&
(var_stgclass_(p) == Stg_Extern ||
var_stgclass_(p) == Stg_Static) &&
var_loc_(p) == 0 &&
var_sym_(p) == name) {
var_loc_(p) = addr;
var_base_(p) = base;
return;
}
dw_addvar(name, 0, stg, base, addr, t);
}
}
static void dw_typeinternal(Symstr *name, Dw_TypeRep *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))
dw_typerep(type, NULL);
else {
Dw_ItemList *p = Dw_ItemAlloc(DEB_TYPE, DW_TAG_typedef);
if (debugging(DEBUG_Q))
cc_msg("type $r\n", name);
/* If there isn't already an internal representation ... */
if (t == NULL && type != NULL)
dw_typerep(type, &type_type_(p));
else
type_type_(p) = t;
type_typex_(p) = type;
type_name_(p) = symname_(name);
type_qual_(p) = NULL;
dw_addtoitemlist(p);
}
}
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);
dw_typeinternal(name, 0, t);
}
static Dw_FileCoord *cur_proc_coord;
void dbg_proc(Binder *b, TagBinder *parent, bool ext, FileLine fl)
{ if (usrdbg(DBG_PROC))
{ Symstr *name = bindsym_(b);
TypeExpr *t = princtype(bindtype_(b));
Dw_ItemList *p = Dw_ItemAlloc(DEB_PROC, DW_TAG_subprogram);
if (debugging(DEBUG_Q)) cc_msg("startproc $r\n", name);
if (h0_(t) != t_fnap) syserr(syserr_dbg_proc);
/*
if ((Dw_ItemList *)binddbg_(b) == NULL
&& dw_hasdefaultvalues(typefnargs_(t)))
Dw_ProcDeclRep(name, b, NULL, ext);
*/
dw_typerep(typearg_(t), &proc_type_(p));
proc_entry_(p) = 0; /* fill in at dbg_enterproc */
proc_body_(p) = 0; /* fill in at dbg_bodyproc */
proc_endproc_(p) = 0; /* fill in at dbg_xendproc */
proc_name_(p) = symname_(name);
proc_codeseg_(p) = bindsym_(codesegment);
proc_global_(p) = ext;
proc_variadic_(p) = fntypeisvariadic(t);
proc_parent_(p) = NULL;
if (parent != NULL)
dw_typerep(tagbindtype_(parent), &proc_parent_(p));
proc_decl_(p) = (Dw_ItemList *)binddbg_(b);
dw_listproc = dw_addtoitemlist(p); /* do this last (typerep above) */
PushScope(p, &proc_children_(p));
if (dw_fmllist != NULL && dw_fmllist->fb == bind_global_(name)) {
formal_defltfn_(dw_fmllist->p) = p;
dw_fmllist = cdr_(dw_fmllist);
}
}
if (usrdbg(DBG_LINE))
cur_proc_coord = (Dw_FileCoord *)fl.p;
dw_loclist = 0;
}
void dbg_enterproc(void)
{ if (usrdbg(DBG_PROC))
{ Dw_ItemList *p = dw_listproc;
if (p == 0 || debsort_(p) != DW_TAG_subprogram || proc_entry_(p) != 0)
syserr(syserr_dbg_proc1);
if (debugging(DEBUG_Q))
cc_msg("enter '%s' @ %.6lx\n", proc_name_(p), (long)codebase);
proc_entry_(p) = 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))
{ Dw_ItemList *p = dw_listproc;
if (p == 0 || debsort_(p) != DW_TAG_subprogram || proc_body_(p) != 0)
syserr(syserr_dbg_proc1);
if (debugging(DEBUG_Q))
cc_msg("body '%s' @ %.6lx\n", proc_name_(p), (long)(codebase+codep));
proc_body_(p) = codebase+codep;
}
}
void dbg_return(int32 addr)
{ if (usrdbg(DBG_PROC))
{ if (debugging(DEBUG_Q))
cc_msg("return @ %.6lx\n", addr);
/* No way to represent this in DWARF */
}
}
void dbg_xendproc(FileLine fl)
{ IGNORE(fl);
if (bindsym_(codesegment) == dw_baseseg.sym) dw_baseseg.len = codebase+codep;
if (usrdbg(DBG_PROC))
{ Dw_ItemList *q = dw_listproc;
Dw_ItemList *p = Dw_ItemAlloc(DEB_ENDPROC, DW_TAG_endproc);
if (q == 0 || debsort_(q) != DW_TAG_subprogram || proc_endproc_(q) != 0)
syserr(syserr_dbg_proc1);
/* ... for nested fns */
for (dw_listproc = cdr_(dw_list); dw_listproc != NULL; dw_listproc = cdr_(dw_listproc))
if (debsort_(dw_listproc) == DW_TAG_subprogram
&& proc_endproc_(dw_listproc) == 0
&& proc_body_(dw_listproc) == 0
&& proc_entry_(dw_listproc) == 0)
break;
if (debugging(DEBUG_Q))
cc_msg("endproc '%s' @ %.6lx\n", proc_name_(q), (long)(codebase+codep));
proc_endproc_(q) = p;
endproc_endaddr_(p) = codebase+codep;
cdr_(p) = dw_list; dw_list = p;
dw_loclist = 0;
PopScope(dw_version == 2);
}
}
/* 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 */
Dw_LocList *p = (Dw_LocList*) BindAlloc(sizeof(Dw_LocList));
if (debugging(DEBUG_Q))
cc_msg("note loc var $b\n", name);
cdr_(p) = dw_loclist;
p->name = name;
p->pos = fl.l;
p->size = sizeoftypelegal(bindtype_(name)) ? sizeoftype(bindtype_(name)) :
sizeof_int;
dw_typerep(bindtype_(name), &p->typeref);
dw_loclist = p;
if (bindstg_(name) & bitofstg_(s_typedef))
dw_typeinternal(bindsym_(name), p->typeref, bindtype_(name));
}
}
static Dw_LocList *dbg_findloclist(Binder *b)
{ Dw_LocList *p;
for (p = dw_loclist; p != NULL; p = cdr_(p))
if (p->name == b) return p;
return NULL;
}
void dbg_locvar1(Binder *b) {
Symstr *name = bindsym_(b);
SymOrReg base;
Dw_LocList *p = dbg_findloclist(b);
StgClass stgclass;
int stgclassname;
int32 addr = bindaddr_(b);
base.sym = NULL;
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>");
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 = Stg_Static, stgclassname = 'S';
if (bindstg_(b) & b_fnconst) {
base.sym = bindsym_(b);
addr = 0;
} else
base.sym =
#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 = (addr & BINDADDR_MASK) == BINDADDR_ARG ? Stg_ArgReg : Stg_Reg;
stgclassname = 'R', addr = register_number(bindxx_(b));
} else switch (addr & BINDADDR_MASK) {
case BINDADDR_ARG:
stgclass = Stg_ArgAuto, stgclassname = 'A', addr = local_fpaddress(b);
if (p->size < 4 && !target_lsbytefirst) addr += 4 - p->size;
base.r = local_fpbase(b);
break;
case BINDADDR_LOC:
stgclass = Stg_Auto, stgclassname = 'P', addr = local_fpaddress(b);
if (p->size < 4 && !target_lsbytefirst) addr += 4 - p->size;
base.r = local_fpbase(b);
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);
dw_addvar(name, p->typeref, stgclass, base, addr, NULL);
}
static void dwarf_scope_2(int entering, BindListList *newbll, BindListList *oldbll)
{ if (oldbll != NULL) {
BindListList *bll = newbll;
Dw_ItemList *last = NULL;
for (bll = newbll; bll != oldbll; bll = bll->bllcdr) {
if (bll == NULL) syserr(syserr_dbg_scope);
if (bll->bllcar != NULL) {
Dw_ItemList *p;
if (entering > 0) {
p = dw_additem(DEB_STARTSCOPE, DW_TAG_lexical_block);
startscope_next_(p) = last; /* filled in soon by INFOSCOPE */
startscope_codeseg_(p) = bindsym_(codesegment);
PushScope(p, &startscope_children_(p));
} else {
p = Dw_ItemAlloc(DEB_ENDSCOPE, DW_TAG_end_lexical_block);
startscope_next_(p) = last; /* filled in soon by INFOSCOPE */
startscope_end_(scopestack->item) = p;
PopScope(NO);
cdr_(p) = dw_list; dw_list = p;
}
last = p;
dw_listscope = 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");
}
}
}
static bool dwarf_scope_1(BindListList *newbll, BindListList *oldbll) {
int32 entering = length((List *)newbll) - length((List *)oldbll);
if (entering == 0) return NO;
/* A bodge here to ensure that there's no START/ENDSCOPE pair around */
/* the variable items for the outermost BindList (arguments) */
/* XRAY for one is unhappy if there is. */
/* (dwarf_scope_i copes with the case where there's just one BindList */
/* being added or removed : code is needed here for the case there's */
/* more than one because of removal of an empty block with a */
/* different debenv from its predecessor */
if (entering > 0) {
if (oldbll == NULL && entering > 1) {
BindListList *p = newbll;
do
p = p->bllcdr;
while (p->bllcdr != NULL);
dwarf_scope_2(1, p, oldbll);
oldbll = p; --entering;
}
dwarf_scope_2(entering, newbll, oldbll);
} else {
if (newbll == NULL && entering < -1) {
BindListList *p = oldbll;
do
p = p->bllcdr;
while (p->bllcdr != NULL);
dwarf_scope_2(1, p, newbll);
newbll = p; ++entering;
}
dwarf_scope_2(entering, oldbll, newbll);
}
/* Ask for INFOSCOPE item to get called back more or less immediately */
/* from the local cg (INFOSCOPE item) to fill in the codeaddr */
return YES;
}
bool dbg_scope(BindListList *newbll, BindListList *oldbll) {
int32 entering = length((List *)newbll) - length((List *)oldbll);
if (oldbll == newbll)
return NO;
if (newbll == NULL || oldbll == NULL)
return dwarf_scope_1(newbll, oldbll);
if (entering > 0) {
BindListList *bll;
for (bll = newbll; bll != 0; bll = bll->bllcdr)
if (bll == oldbll)
return dwarf_scope_1(newbll, oldbll);
} else if (entering < 0) {
BindListList *bll;
for (bll = oldbll; bll != 0; bll = bll->bllcdr)
if (bll == newbll)
return dwarf_scope_1(newbll, oldbll);
}
/* Neither list is a subset of the other (can happen thanks to dead */
/* block elimination). Find the common tail. */
{ BindListList *bll_n, *bll_o;
for (bll_n = newbll->bllcdr; bll_n != NULL; bll_n = bll_n->bllcdr)
for (bll_o = oldbll->bllcdr; bll_o != NULL; bll_o = bll_o->bllcdr)
if (bll_o == bll_n) {
dwarf_scope_1(bll_o, oldbll);
return dwarf_scope_1(newbll, bll_o);
}
}
/* There is no common tail to oldbll and newbll */
syserr(syserr_dbg_scope);
return NO;
}
/* 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 Dw_MacroList *Dw_NewMacroList(FileLine const *fl, int sort) {
Dw_MacroList *p = DbgNew(Dw_MacroList);
Dw_FileList *fp = Dw_FindFile(fl->f);
p->fl.index = fp->index; p->fl.l = fl->l; p->fl.column = fl->column;
p->sort = sort;
cdr_(p) = dw_macrolist;
dw_macrolist = p;
return p;
}
void dbg_define(char const *name, bool objectmacro, char const *body,
dbg_ArgList const *args, FileLine fl) {
if (dw_version == 2) {
Dw_MacroList *p = Dw_NewMacroList(&fl, DW_MACINFO_define);
size_t namelen = strlen(name);
size_t len = namelen;
if (!objectmacro) {
dbg_ArgList const *p;
for (p = args; p != NULL; p = p->next)
len += strlen(p->name) + 1;
len += args == NULL ? 2 : 1;
}
len += strlen(body) + 2;
{ char *value = (char *)DbgAlloc(len);
p->data.s = value;
memcpy(value, name, namelen); value += namelen;
if (!objectmacro) {
dbg_ArgList const *p;
*value++ = '(';
for (p = args; p != NULL; p = p->next) {
namelen = strlen(p->name);
if (p != args) *value++ = ',';
memcpy(value, p->name, namelen);
value += namelen;
}
*value++ = ')';
}
*value++ = ' ';
strcpy(value, body);
}
if (debugging(DEBUG_Q))
cc_msg("%s:%d #define %s\n", fl.f, fl.l, p->data.s);
}
}
void dbg_undef(char const *name, FileLine fl) {
if (dw_version == 2) {
Dw_MacroList *p = Dw_NewMacroList(&fl, DW_MACINFO_undef);
p->data.s = name;
if (debugging(DEBUG_Q))
cc_msg("%s:%d #undef %s\n", fl.f, fl.l, name);
}
}
static Dw_PathList *FindPath(char const *pathname) {
size_t len = strlen(pathname);
Dw_PathList *p = dw_pathlist;
for (; p != NULL; p = cdr_(p))
if (len == p->len && memcmp(p->name, pathname, len) == 0)
return p;
p = (Dw_PathList *)DbgAlloc(sizeof(Dw_PathList)+len);
cdr_(p) = dw_pathlist; dw_pathlist = p;
p->index = ++dw_pathindex;
p->len = len;
memcpy(p->name, pathname, len+1);
return p;
}
void dbg_include(char const *filename, char const *path, FileLine fl) {
if (dw_version == 2) {
if (filename == NULL) {
Dw_MacroList *p = Dw_NewMacroList(&fl, DW_MACINFO_end_file);
p->data.i = 0;
if (debugging(DEBUG_Q))
cc_msg("%s:%d #end include\n", fl.f, fl.l);
} else {
Dw_MacroList *p = Dw_NewMacroList(&fl, DW_MACINFO_start_file);
Dw_FileList *fp = Dw_FindFile(filename);
p->data.i = fp->index;
fp->dir = path == NULL || path[0] == 0 ? NULL : FindPath(path);
if (debugging(DEBUG_Q)) {
cc_msg("%s:%d #include %s", fl.f, fl.l, filename);
if (path != NULL) cc_msg(" %s", path);
cc_msg("\n");
}
}
}
}
void dbg_notepath(char const *pathname) {
if (dw_version == 2) {
if (!dw_sub_init_done) dw_sub_init();
{ Uint ix = dw_pathindex;
if (FindPath(pathname)->index > ix &&
debugging(DEBUG_Q))
cc_msg("note path %s\n", pathname);
}
}
}
int32 dw_mapped_codebase, dw_mapped_codep;
void dbg_final_src_codeaddr(int32 code_base, int32 code_p)
{ dw_mapped_codebase = code_base,
dw_mapped_codep = code_p;
}
char const *Dw_Unmangle(char const *s)
{
static char unmangle_buf[256];
static char const sstring[] = "static";
size_t len = strlen(s), slen = strlen(sstring);
if (!StrnEq(s, "__ct__F", 7) &&
!StrnEq(s, "__dt__F", 7) &&
!StrnEq(s, "__as__F", 7) &&
(len < 4 || !StrEq(s+len-3, "__C")))
{ const char *name = unmangle2(s, unmangle_buf, sizeof unmangle_buf);
if (name != s)
{ char *t = strchr(unmangle_buf, '(');
if (t != NULL && t < &unmangle_buf[sizeof unmangle_buf])
*t = '\0';
return (StrnEq(unmangle_buf, sstring, slen)) ? &unmangle_buf[slen+1] :
unmangle_buf;
}
}
return s;
}
static uint32 Dw_1or2_NameindexSize(void) {
Dw_ItemList const *p = sect_children_(dw_section);
uint32 n = 0;
for (; p != NULL; p = sibling_(p))
switch (debsort_(p)) {
case DW_TAG_subprogram:
n += (uint32)strlen(Dw_Unmangle(proc_name_(p))) + 5;
break;
case DW_TAG_variable:
n += (uint32)strlen(Dw_Unmangle(symname_(var_sym_(p)))) + 5;
break;
case DW_TAG_typedef:
n += (uint32)strlen(type_name_(p)) + 5;
break;
case DW_TAG_fref:
case DW_TAG_class_type:
case DW_TAG_union_type:
case DW_TAG_structure_type:
if (struct_name_(p) != NULL)
n += (uint32)strlen(struct_name_(p)) + 5;
break;
case DW_TAG_enumeration_type:
if (enum_name_(p) != NULL)
n += (uint32)strlen(enum_name_(p)) + 5;
{ Dw_ItemList *elts = enum_children_(p);
for (; elts != NULL; elts = sibling_(elts))
if (debsort_(elts) == DW_TAG_enumerator)
n += (uint32)strlen(enumerator_name_(elts)) + 5;
}
break;
default:
break;
}
return n;
}
static void Dw_1or2_WriteNameindexEntry(Dw_ItemList const *p, char const *s) {
Dw_WriteW(dbgloc_(p), 0);
Dw_WriteInlineString(s, 0);
}
static void Dw_1or2_WriteNameindex(void) {
Dw_ItemList const *p = sect_children_(dw_section);
DataXref *xrefs = NULL;
uint32 size = dw_nameindex_size + 9 + /* header (excluding length word) */
4; /* terminator */
uint32 roundup = (size & 3) ? 4 - (size & 3) : 0;
obj_startdebugarea(NameIndexAreaName);
Dw_WriteW(size + roundup, 0);
Dw_WriteB(1, 0);
Dw_WriteW(0, 0);
Dw_WriteW(dw_baseseg.len, 0);
xrefs = Dw_Relocate(xrefs, 5, dw_debug_sym);
for (; p != NULL; p = sibling_(p))
switch (debsort_(p)) {
case DW_TAG_subprogram:
Dw_1or2_WriteNameindexEntry(p, Dw_Unmangle(proc_name_(p)));
break;
case DW_TAG_variable:
Dw_1or2_WriteNameindexEntry(p, Dw_Unmangle(symname_(var_sym_(p))));
break;
case DW_TAG_typedef:
Dw_1or2_WriteNameindexEntry(p, type_name_(p));
break;
case DW_TAG_fref:
case DW_TAG_class_type:
case DW_TAG_union_type:
case DW_TAG_structure_type:
if (struct_name_(p) != NULL)
Dw_1or2_WriteNameindexEntry(p, struct_name_(p));
break;
case DW_TAG_enumeration_type:
if (enum_name_(p) != NULL)
Dw_1or2_WriteNameindexEntry(p, enum_name_(p));
{ Dw_ItemList *elts = enum_children_(p);
for (; elts != NULL; elts = sibling_(elts))
if (debsort_(elts) == DW_TAG_enumerator)
Dw_1or2_WriteNameindexEntry(p, enumerator_name_(elts));
}
break;
default:
break;
}
Dw_WriteW(0, 0);
if (roundup) {
uint32 w = 0;
obj_writedebug(&w, roundup);
}
obj_enddebugarea(NameIndexAreaName, xrefs);
}
#ifdef TARGET_HAS_FP_OFFSET_TABLES
void obj_notefpdesc(ProcFPDesc const *fpd) {
/* Only representable in DWARF version 2 */
IGNORE(fpd);
return;
}
#endif
void dbg_finalise(void) {
dw_init_done = dw_sub_init_done = NO;
}
bool dbg_debugareaexists(char const *name) {
if (StrEq(name, DebugAreaName))
return dw_list != NULL;
else if (StrEq(name, LineInfoAreaName))
return dw_coord_p != NULL;
else if (StrEq(name, NameIndexAreaName))
return (dw_nameindex_size = Dw_1or2_NameindexSize()) != 0;
else if (StrEq(name, RangeIndexAreaName))
return NO;
else if (StrEq(name, MacroAreaName))
return dw_macrolist != NULL;
else if (StrEq(name, AbbrevAreaName))
return dw_list != NULL;
else if (StrEq(name, LocationAreaName))
return NO;
return NO;
}
void dbg_writedebug(void) {
Dw_ItemList *p;
if (dw_list != NULL) {
PopScope(NO);
dw_list = (Dw_ItemList *)dreverse((List *)dw_list);
}
dw_macrolist = (Dw_MacroList *)dreverse((List *)dw_macrolist);
for (p = dw_list; p != NULL; p = cdr_(p))
if (debsort_(p) == DW_TAG_subprogram && proc_variadic_(p)) {
Dw_ItemList *q,
**prevp = &cdr_(p),
**prevsibling = &proc_children_(p);
for (q = proc_children_(p); q != NULL; q = sibling_(q))
if (debsort_(q) == DW_TAG_formal_parameter) {
prevsibling = &sibling_(q);
prevp = &cdr_(q);
}
q = (Dw_ItemList *)DbgAlloc(sizeof(dw_list->car.DEB_REST)+offsetof(Dw_ItemList,car));
debsort_(q) = DW_TAG_unspecified_parameters;
sibling_(q) = *prevsibling; cdr_(q) = *prevp;
*prevsibling = q; *prevp = q;
}
if (dw_version == 1) {
if (dw_list != NULL) Dw_1_WriteInfo();
if (dw_coord_p != NULL) Dw_1_WriteLineinfo();
if (dw_nameindex_size != 0) Dw_1or2_WriteNameindex();
} else {
if (dw_list != NULL) Dw_2_WriteInfo();
if (dw_coord_p != NULL) Dw_2_WriteLineinfo();
if (dw_nameindex_size != 0) Dw_1or2_WriteNameindex();
if (dw_macrolist != NULL) Dw_2_WriteMacros();
if (dw_list != NULL) Dw_2_WriteAbbrevs();
}
if (usrdbg(DBG_PROC) && dw_fmllist != NULL) syserr("dw_fmllist non empty!");
}
static void dw_sub_init(void) {
dw_list = NULL; dw_basetypes = NULL;
dw_baseseg.len = 0;
dw_listproc = NULL;
dw_listscope = NULL;
dw_filelist = NULL; dw_fileindex = 0;
dw_pathlist = NULL; dw_pathindex = 0;
dw_coord_p = NULL; dw_coord_q = &dw_coord_p;
dw_loclist = NULL;
dw_sub_init_done = YES;
dw_nameindex_size =0;
dw_ftlist = NULL;
dw_fmllist = NULL;
dw_macrolist = NULL;
}
bool dbg_needsframepointer(void) {
return dw_version == 1;
}
void dbg_setformat(char const *format) {
int form = format[0];
if (form == 0)
form = 1; /* -dwarf on its own defaults to dwarf version 1 */
else
form = form - '0';
dw_version = form;
}
void dbg_init(void) {
if (!dw_sub_init_done) dw_sub_init();
dw_baseseg.sym = bindsym_(codesegment);
if (usrdbg(DBG_ANY))
{ Dw_ItemList *p = Dw_ItemAlloc(DEB_SECTION, DW_TAG_compile_unit);
dw_section = p;
dw_debug_sym = obj_notedebugarea(DebugAreaName);
dw_lineinfo_sym = obj_notedebugarea(LineInfoAreaName);
obj_notedebugarea(NameIndexAreaName);
obj_notedebugarea(RangeIndexAreaName);
if (dw_version == 2) {
dw_macro_sym = obj_notedebugarea(MacroAreaName);
dw_abbrev_sym = obj_notedebugarea(AbbrevAreaName);
dw_location_sym = obj_notedebugarea(LocationAreaName);
}
sect_name_(p) = sourcefile;
sect_codeseg_(p) = bindsym_(codesegment);
cdr_(p) = NULL;
freescopes = NULL;
scopestack = NULL; PushScope(p, §_children_(p));
{ Dw_ItemList *q, **pp = &dw_list;
for (; (q = *pp) != NULL; pp = &cdr_(q)) continue;
*pp = p;
}
if (usrdbg(DBG_LINE))
{ Dw_FileList *x = dw_filelist;
for (; x != NULL; x = cdr_(x)) {
Dw_FileCoord *l = x->linelist;
for (; l != NULL; l = l->nextinfile)
l->codeseg = bindsym_(codesegment);
}
}
}
dw_init_done = YES;
}
#else
typedef int dummy; /* prevent translation unit from being empty */
#endif /* defined(TARGET_HAS_DWARF) && defined(TARGET_HAS_DEBUGGER) */
/* End of mip/dwarf.c */
|
stardot/ncc | mip/coffobj.c | /* C compiler file coffobj.c : Copyright (C) Codemist Ltd, 1988. */
/* SPDX-Licence-Identifier: Apache-2.0 */
/* 'COFF' (system V unix) output routines */
/* version 13j */
/*
* RCS $Revision$
* 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 <time.h> /* see time() below */
#include "globals.h" /* loads host.h,options.h,target.h,defaults.h */
#include "mcdep.h"
/* #include "mcdpriv.h" */
#include "store.h"
#include "codebuf.h"
#include "builtin.h"
#include "xrefs.h"
#include "errors.h"
#ifndef __STDC__
# include <sys/types.h>
# include <a.out.h> /* sysV coff definitions */
/* On SysV this just does:
#include <nlist.h>
#include <filehdr.h>
#include <aouthdr.h>
#include <scnhdr.h>
#include <reloc.h>
#include <linenum.h>
#include <syms.h>
*/
#else
/*
* "target.h" (via globals.h) must be included before "coff.h", since our
* private version of a header defining the COFF 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".
*/
# include "coff.h" /* Codemist private version */
#endif
#ifdef TARGET_IS_MIPS
# define R_DIR32 R_REFWORD /* /* (beware DIR32 == 17) rationalise */
# define R_PCRLONG R_JMPADDR /* rationalise... */
#endif
/* 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
#ifdef TARGET_IS_MIPS
# define HDRSIZE (sizeof(struct filehdr) + sizeof(AOUTHDR) + \
NSCNS*sizeof(struct scnhdr))
#else
# define HDRSIZE (sizeof(struct filehdr) + NSCNS*sizeof(struct scnhdr))
#endif
/* 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 int32 obj_fwrite_cnt;
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 fwrite(buff,(size_t)n,(size_t)m,f);
}
FILE *objstream;
/* imports: codebase, dataloc */
static unsigned32 ncoderelocs, ndatarelocs, obj_symcount;
ExtRef *obj_symlist;
CodeXref *codexrefs;
/* DataXref *dataxrefs; -- now exported from codebuf.c as data.xrefs. */
#ifdef COMPILING_ON_SMALL_MEMORY
/* Buffer code in a temporary file */
FILE *obj_tmpfile;
____notyetfinished;
#else /* !COMPILING_ON_SMALL_MEMORY */
/* Buffer code in memory */
/* 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
#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)+((n>>16)&0xffff);
}
}
static int32 get_code(int32 q)
{ return ((q&3)==0 ? xcode_inst_(q) :
((xcode_inst_(q+2))<<16) + (((xcode_inst_(q))>>16)&0xffff));
}
# 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)+((n>>16)&0xffff);
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) + (((xcode_inst_(q+2))>>16)&0xffff));
}
# endif
#else
#ifdef TARGET_IS_ADENART
/* This may need re-work for SPARC host byte sex!. */
# define get_code(q) ((int32)xcode_byte_((q)+0)<<0 | \
(int32)xcode_byte_((q)+1)<<8)
# define set_code(q,n) (xcode_byte_((q)+0)=(int)((n)>>0), \
xcode_byte_((q)+1)=(int)((n)>>8))
#else
# define get_code(q) xcode_inst_(q)
# define set_code(q,n) xcode_inst_(q)=n
#endif
#endif
/* 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... */
#ifndef TARGET_IS_MIPS
cxr->codexrsym = SYM_FULLY_RELOCATED;
#endif
#ifdef TARGET_IS_STARDENT
cxr->codexrsym = SYM_FULLY_RELOCATED;
#endif
/* @@@ 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_I860
/* 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_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_MIPS
#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
# define obj_codeupdate(x) syserr(syserr_coff_pcrel)
#endif
#ifdef TARGET_IS_AMD
# define obj_codeupdate(x) syserr(syserr_coff_pcrel)
#endif
#ifdef TARGET_IS_ADENART
# define obj_codeupdate(x) set_code(codeoff, x)
#endif
#ifdef TARGET_IS_ALPHA
# define obj_codeupdate(x) set_code(codeoff, x)
#endif
#ifndef obj_codeupdate
#error Missing COFF self-relocation code (unknown target machine).
#define obj_codeupdate(x) syserr(syserr_coff_pcrel)
#endif
#ifdef TARGET_IS_MIPS /* X_JmpAddr */
obj_codeupdate(x->extoffset);
#else
obj_codeupdate(x->extoffset-codeoff);
#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 */
/* Code here may need changing if you set ORG_TEXT &c to non-zero. */
#if (R_DIR32 == 17)
/* When using R_DIR32 (code 17), COFF (as seen on 68000/i386) requires */
/* common refs to have their size (->extoffset) added in when */
/* generated, so the linker can later subtract the size and add in the */
/* address. Wonderful unix. Hence the following code (which is a noop */
/* for non-common extern refs). */
obj_codeupdate(x->extoffset);
#else
/* More obviously sensible code including 88000 (R_DIR32 = 133) */
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.
*/
#ifndef TARGET_IS_STARDENT
obj_codeupdate(x->extoffset);
#endif
}
#endif
break;
case X_DataAddr: /* 88000, MIPS, (+i860 etc) -- high 16 bits */
#ifndef TARGET_IS_88000 /* 88000 ocs has ls 16 bits even in high half! */
{ unsigned32 d = cxr->codexrlitoff;
#ifndef TARGET_IS_STARDENT
if (x->extflags & (xr_defloc | xr_defext))
d += x->extoffset; /* see comment for absreloc */
#endif
#ifdef TARGET_IS_ADENART
/* in fact all machines which don't sign-extend offsets. */
set_code(codeoff, (w & 0xffff0000) | (d >> 16));
#else
/* the 0x8000 on the next line is for MIPS -- check. */
set_code(codeoff, (w & 0xffff0000) | (d+0x8000 >> 16));
#endif
}
break;
#endif
case X_DataAddr1: /* 88000, MIPS, (+i860 etc) -- low 16 bits */
{ int32 d = cxr->codexrlitoff;
#ifndef TARGET_IS_STARDENT
if (x->extflags & (xr_defloc | xr_defext))
d += x->extoffset; /* see comment for absreloc */
#endif
/* 88000 ocs requires ls 16 bits even in high loading half. */
set_code(codeoff, (w & 0xffff0000) | (d & 0xffff));
}
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};
#ifdef TARGET_IS_ADENART
buffer_code(pad, 3); /* Double word aligned (and mult. of 3) */
#else
buffer_code(pad, 1); /* Double word aligned */
#endif
}
#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);
}
#endif /* COMPILING_ON_SMALL_MEMORY */
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;
}
}
/* the remaining fns are intended to be internal only */
#ifdef TARGET_IS_MIPS /* MIPS, bless its little heart, has odd symtab */
/* and the Stardent is even odder */
/* The two following routines do much the same thing... */
#ifdef TARGET_IS_STARDENT
static int32 count_symb(Symstr *ss, int32 *d)
{
ExtRef *x;
int32 cnt = 0;
for (x = obj_symlist; x != 0; x = x->extcdr) {
if (x->extsym == ss) {
*d = (x->extflags & xr_defloc ? 0 : 1);
return cnt;
}
cnt++;
}
}
#else
static void obj_renumber_symbols()
{ ExtRef *x;
int32 newidx = 0;
/* renumber externs from 0, flag internals with -1. */
for (x = obj_symlist; x != 0; x = x->extcdr)
{ int32 flags = x->extflags;
x->extindex =
x->extsym == bindsym_(codesegment) ? 0x80000000 + R_SN_TEXT :
x->extsym == bindsym_(datasegment) ? 0x80000000 + R_SN_DATA :
(flags & xr_defloc) ? -1 : newidx++;
}
}
#endif
static void obj_outsymtab()
{ ExtRef *x;
unsigned32 estrct = 0, estrct2 = 0, esymct = 0;
#ifdef TARGET_IS_STARDENT
#define LOCSTRCT 0 /* What is the purpose of this?? */
#else
#define LOCSTRCT 4 /* improve one day */
#endif
for (x = obj_symlist; x != 0; x = x->extcdr)
#ifndef TARGET_IS_STARDENT
if (x->extindex >= 0)
#endif
{ Symstr *s = x->extsym;
char *name = symname_(s);
size_t n = strlen(name);
if (debugging(DEBUG_OBJ)) cc_msg("extsym $r ", s);
estrct += (size_t)(n+1);
esymct++;
}
estrct = (estrct + 3) & ~(int32)3;
{ int32 symbase = HDRSIZE + codesize + dataloc +
ncoderelocs*RELSZ + ndatarelocs*RELSZ;
HDRR h; FDR f;
memclr(&h, sizeof(h)); memclr(&f, sizeof(f));
h.magic = magicSym, h.vstamp = MIPSvstamp;
#ifndef TARGET_IS_STARDENT
h.isymMax = 0;
h.cbSymOffset = symbase + sizeof(h)+sizeof(f);
#endif
h.iextMax = esymct;
#ifndef TARGET_IS_STARDENT
h.cbExtOffset = symbase + sizeof(h)+sizeof(f);
h.issMax = LOCSTRCT;
h.cbSsOffset = symbase + sizeof(h)+sizeof(f) + esymct*sizeof(EXTR);
#endif
h.issExtMax = estrct;
#ifdef TARGET_IS_STARDENT
h.cbExtOffset = symbase + sizeof(h) + estrct + LOCSTRCT;
h.cbSsExtOffset = symbase + sizeof(h) + LOCSTRCT;
#else
h.cbSsExtOffset = symbase + sizeof(h)+sizeof(f) + esymct*sizeof(EXTR)
+ LOCSTRCT;
h.ifdMax = 1;
h.cbFdOffset = symbase + sizeof(h);
#endif
obj_fwrite(&h, sizeof(h), 1, objstream);
#ifndef TARGET_IS_STARDENT
f.cbSs = LOCSTRCT; /* include oneday filename */
obj_fwrite(&f, sizeof(f), 1, objstream);
#endif
}
#ifndef TARGET_IS_STARDENT
for (x = obj_symlist; x != 0; x = x->extcdr)
if (x->extindex >= 0)
{ Symstr *s = x->extsym;
char *name = symname_(s);
size_t n = strlen(name);
int32 flags = x->extflags;
/* #ifdef TARGET_IS_STARDENT
** DL_XSYM v;
** v.index = indexNil;
** v.iss = estrct2;
** v.auxval = x->extoffset;
** v.value = (!(flags & xr_defloc+xr_defext) ? ORG_TEXT :
** (flags & xr_code ? ORG_TEXT : ORG_DATA));
** v.flags = DL_DEF + DL_FLAG + (flags & xr_code ? DL_TEXT : DL_DATA);
** if (flags & xr_defloc) v.flags += DL_LOCAL;
** #else
*/
EXTR v;
v.reserved = 0; v.ifd = 0;
v.asym.st = stGlobal;
v.asym.sc = !(flags & xr_defloc+xr_defext) ? scUndefined :
flags & xr_code ? scText : scData;
v.asym.reserved = 0;
v.asym.index = indexNil;
v.asym.iss = estrct2;
v.asym.value = x->extoffset +
(v.asym.sc == scData ? ORG_DATA : ORG_TEXT);
obj_fwrite(&v, sizeof(v), 1, objstream);
estrct2 += (size_t)(n+1);
}
obj_fwrite("\0\0\0", LOCSTRCT, 1, objstream);
#endif
/* write the string table ... */
for (x = obj_symlist; x != 0; x = x->extcdr)
#ifndef TARGET_IS_STARDENT
if (x->extindex >= 0)
#endif
{ Symstr *s = x->extsym;
char *name = symname_(s);
size_t n = strlen(name);
obj_fwrite(name, 1, (size_t)(n+1), objstream);
#ifdef TARGET_IS_STARDENT
estrct -= n+1;
#endif
}
#ifdef TARGET_IS_STARDENT
if (estrct) obj_fwrite("\0\0\0", estrct, 1, objstream);
estrct = 0;
for (x = obj_symlist; x != 0; x = x->extcdr)
{ Symstr *s = x->extsym;
char *name = symname_(s);
DL_XSYM tt;
int flags = x->extflags;
memclr(&tt,sizeof(tt));
tt.iss = estrct;
tt.value = x->extoffset +
(flags & xr_code ? ORG_TEXT : ORG_DATA);
tt.flags = DL_FLAG + (flags & xr_code ? DL_TEXT : DL_DATA);
if (flags & xr_defloc) tt.flags |= DL_LOCAL | DL_DEF;
if (flags & xr_defext) tt.flags |= DL_DEF;
tt.index =
/* x->extsym == bindsym_(codesegment) ? 0x80000000 + R_SN_TEXT : */
/* x->extsym == bindsym_(datasegment) ? 0x80000000 + R_SN_DATA : */
/* (flags & xr_defloc) ? -1 :*/ 0;
obj_fwrite(&tt, 1, sizeof(tt), objstream);
estrct += strlen(name)+1;
}
#else
while (estrct2 != estrct) obj_fwrite("", 1, 1, objstream), estrct2++;
#endif
}
#else /* TARGET_IS_MIPS */ /* i.e. all normal SysV COFF machines. */
/* In COFF, the data segment label is required to be .data etc. */
#define coffname_(s) ((s) == bindsym_(codesegment) ? ".text" : \
(s) == bindsym_(datasegment) ? ".data" : \
symname_(s))
/* TEMPHACK: */
union auxent {
struct syment pad;
struct { long int x_scnlen;
unsigned short x_nreloc;
unsigned short x_nlinno;
} x_scn;
};
/* TEMPHACK: */
static void segaux(int32 seglen, int32 nrelocs)
{ union auxent v;
memclr(&v, sizeof(v));
v.x_scn.x_scnlen = seglen;
v.x_scn.x_nreloc = (unsigned int)nrelocs;
v.x_scn.x_nlinno = 0;
obj_fwrite(&v, SYMESZ, 1, objstream);
}
/* TEMPHACK: */
static void outbsslabel()
{
struct syment v;
memclr(&v, sizeof(v));
strncpy(v.n_name, ".bss", SYMNMLEN);
v.n_value = ORG_BSS;
v.n_scnum = N_BSS;
v.n_type = T_NULL;
v.n_sclass = C_STAT;
v.n_numaux = 1;
obj_fwrite(&v, SYMESZ, 1, objstream);
segaux(0,0);
}
/* TEMPHACK end */
static void obj_outsymtab()
{ ExtRef *x;
unsigned32 obj_stringpos = sizeof(obj_stringpos);
obj_symlist = (ExtRef *)dreverse((List *)obj_symlist);
/* oldest = smallest numbered first */
for (x = obj_symlist; x != 0; x = x->extcdr)
{ Symstr *s = x->extsym;
char *name = coffname_(s);
size_t n = strlen(name),
k = name[0]=='.' ? 0 : sizeof(target_coff_prefix)-1;
int32 flags = x->extflags;
struct syment v;
memclr(&v, sizeof(v)); /* clear 88k etc pad fields */
if (debugging(DEBUG_OBJ)) cc_msg("sym $r%lx ", s, (long)flags);
if (n+k > SYMNMLEN) /* NB: '>' (not '>=') is OK here */
/* do the long form, name in the string table */
v.n_zeroes = 0,
v.n_offset = obj_stringpos,
obj_stringpos += (size_t)(n+k+1);
else
{ if (k > 0) strncpy(v.n_name, target_coff_prefix, k);
strncpy(v.n_name+k, name, SYMNMLEN-k);
}
/* 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. */
/* BSS mods needed on next three lines when cfe supports bss better. */
v.n_scnum = !(flags & xr_defloc+xr_defext) ? N_UNDEF :
flags & xr_code ? N_TEXT : N_DATA;
v.n_value = x->extoffset + (v.n_scnum == N_DATA ? ORG_DATA : ORG_TEXT);
v.n_type = T_NULL; /* not set yet */
/* below, note that C_EXTDEF is documented as "internal to C, use C_EXT". */
v.n_sclass = flags & xr_defloc ? C_STAT : C_EXT;
v.n_numaux = 0;
/* TEMPHACK: */ if (s == bindsym_(codesegment)) v.n_numaux = 1;
/* TEMPHACK: */ if (s == bindsym_(datasegment)) v.n_numaux = 1;
/* NB note that sizeof(struct syment) > SYMESZ on many machines */
obj_fwrite(&v, SYMESZ, 1, objstream);
/* TEMPHACK: */ if (s == bindsym_(codesegment)) segaux(codesize,ncoderelocs);
/* TEMPHACK: */ if (s == bindsym_(datasegment)) segaux(dataloc,ndatarelocs);
/* TEMPHACK: */ if (s == bindsym_(datasegment)) outbsslabel();
}
/* now write the string table, preceded by its length */
obj_fwrite(&obj_stringpos, sizeof(obj_stringpos), 1, objstream);
for (x = obj_symlist; x != 0; x = x->extcdr)
{ Symstr *s = x->extsym;
char *name = coffname_(s);
size_t n = strlen(name),
k = name[0]=='.' ? 0 : sizeof(target_coff_prefix)-1;
if (n+k > SYMNMLEN)
{ if (k > 0) obj_fwrite(target_coff_prefix, 1, k, objstream);
obj_fwrite(name, 1, (size_t)(n+1), objstream);
}
}
}
#endif /* TARGET_IS_MIPS */
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))
/* honest external or segment defining symbol */
return x->extindex;
else
return obj_checksym(x->extflags & xr_code ?
bindsym_(codesegment) : bindsym_(datasegment));
}
syserr(syserr_coff_checksym, s);
return 0;
}
static void obj_wr_reloc(struct reloc *p, int r)
{ p->r_type = r;
/* NB note that sizeof(struct reloc) > RELSZ on many machines */
obj_fwrite(p, RELSZ, 1, objstream);
ncoderelocs++;
}
static void obj_coderelocation()
{ CodeXref *x;
struct reloc v;
for (x = codexrefs; x!=NULL; x = x->codexrcdr)
{ Symstr *s = x->codexrsym; int32 symndx;
if (s == SYM_FULLY_RELOCATED) continue;
v.r_vaddr = (x->codexroff & 0xffffff) + ORG_TEXT;
v.r_symndx = symndx = obj_checksym(s);
#ifdef TARGET_IS_MIPS
# ifdef TARGET_IS_STARDENT
{ int32 d;
v.r_symndx = count_symb(s, &d);
v.r_extern = /* d */ 1;
}
# else
v.r_extern = (symndx >= 0);
# endif
v.r_reserved = 0;
#endif
#ifdef TARGET_IS_88000
v.r_offset = 0;
#endif
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;
/* The following cases apply to 88000, MIPS, Adenart, i860, 29000(?) */
/* only tested for the first 3. */
/* For the 88000 see p50 of 88open OCS (draft 10 Mar 89). */
/* See also fixups at case X_DataAddr in relocate_code_refs_to_locals. */
case X_DataAddr:
if (debugging(DEBUG_OBJ)) cc_msg("DataAddr$r ", s);
#ifdef TARGET_IS_88000 /* extra r_offset field... */
v.r_vaddr += 2; /* (not for MIPS) */
{ ExtRef *x1 = symext_(s); int32 d = x->codexrlitoff;
if (x1->extflags & (xr_defloc | xr_defext))
d += x1->extoffset;
v.r_offset = d >> 16; }
#endif
obj_wr_reloc(&v, R_REFHI);
break;
case X_DataAddr1:
if (debugging(DEBUG_OBJ)) cc_msg("DataAddr1$r ", s);
#ifdef TARGET_IS_88000 /* extra r_offset field... */
v.r_vaddr += 2; /* (not for MIPS) */
{ ExtRef *x1 = symext_(s); int32 d = x->codexrlitoff;
if (x1->extflags & (xr_defloc | xr_defext))
d += x1->extoffset;
v.r_offset = d >> 16; }
#endif
obj_wr_reloc(&v, R_REFLO);
break;
case X_absreloc: /* abs ref to external */
#ifdef TARGET_IS_STARDENT
if (debugging(DEBUG_OBJ)) cc_msg("addreloc$r ", s);
obj_wr_reloc(&v, R_PCRLONG); /* target_coff_abs? */
break;
#endif
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 void obj_datarelocation()
{ DataXref *x;
struct reloc v;
for (x = dataxrefs; x!=NULL; x = x->dataxrcdr)
{ Symstr *s = x->dataxrsym; int32 symndx;
/* all data relocs are implicitly X_absreloc so far */
if (debugging(DEBUG_OBJ)) cc_msg("data reloc $r ", s);
v.r_type = R_DIR32; /* target_coff_abs? */
v.r_vaddr = x->dataxroff+ORG_DATA; /* & 0xffffff ? */
v.r_symndx = symndx = obj_checksym(s);
#ifdef TARGET_IS_MIPS
# ifdef TARGET_IS_STARDENT
v.r_symndx = count_symb(s, &symndx);
v.r_extern = /* symndx*/ 1;
# else
v.r_extern = (symndx >= 0);
# endif
v.r_reserved = 0;
#endif
#ifdef TARGET_IS_88000
v.r_offset = 0; /* zero for R_DIR32 or R_VRT32 */
#endif
/* NB note that sizeof(struct reloc) > RELSZ on many machines */
obj_fwrite(&v, RELSZ, 1, objstream);
ndatarelocs++;
}
}
static void obj_writedata() /* follows gendc exactly! */
{ DataInit *p;
for (p = datainitp; p != 0; p = p->datacdr)
{ int32 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_coff_gendata, (long)sort);
case LIT_BBBB: /* the next 4 are the same as LIT_NUMBER except */
case LIT_HH: /* for (as yet unsupported) cross compilation. */
case LIT_BBH:
case LIT_HBB:
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 (R_DIR32 == 17)
/* The following line corrects offsets of forward refs within a module, */
/* but also adds in size in a COMMON ref. (COFF non-intuitively needs). */
val += xr->extoffset;
#else
if (xr->extflags & (xr_defloc|xr_defext)) val += xr->extoffset;
#endif
/* 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);
else syserr(syserr_coff_data,
(long)rpt, (long)len, fc->floatstr);
while (rpt-- != 0)
obj_fwrite(&(fc->floatbin), len, 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)) obj_symcount++;
/* TEMPHACK: */ if (s == bindsym_(datasegment)) obj_symcount+=3;
}
/* 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, dataloc);
}
void obj_common_end(void) {}
void obj_init()
{ ncoderelocs = 0, ndatarelocs = 0, obj_symcount = 0;
obj_symlist = 0;
dataxrefs = 0;
codexrefs = 0;
codesize = 0; /* remove */
}
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 = target_coff_magic;
h.f_nscns = NSCNS;
h.f_timdat = time(NULL); /* hope unix format -- norcroft use too. */
h.f_symptr = HDRSIZE + codesize + dataloc +
/* @@@ round to multiple of 4? (RELSZ = 10) */
ncoderelocs*RELSZ + ndatarelocs*RELSZ;
#ifdef TARGET_IS_MIPS
h.f_nsyms = sizeof(HDRR);
h.f_opthdr = sizeof(AOUTHDR);
#else
h.f_nsyms = obj_symcount;
h.f_opthdr = 0; /* no optional header */
#endif
h.f_flags = 0; /* default F_xxxx flags */
obj_fwrite(&h, sizeof(h), 1, objstream);
#ifdef TARGET_IS_MIPS
{ AOUTHDR a;
memclr(&a, sizeof(a));
a.magic = OMAGIC;
a.vstamp = MIPSvstamp;
a.entry = 0;
a.text_start = ORG_TEXT, a.data_start = ORG_DATA;
# ifdef TARGET_IS_STARDENT
a.tsize = 0, a.dsize = dataloc, a.bsize = 0;
a.bss_start = ORG_DATA+dataloc;
# else
a.tsize = codesize, a.dsize = dataloc, a.bsize = 0;
a.bss_start = ORG_BSS;
a.gprmask = -1; /* improve */
a.cprmask[0] = 0; a.cprmask[1] = 0; a.cprmask[2] = 0; a.cprmask[3] = 0;
# endif
a.gp_value = GP_DISP; /* what should go here? */
obj_fwrite(&a, sizeof(a), 1, objstream);
}
#endif
/* code section header */
strncpy(s.s_name, ".text", sizeof(s.s_name));
s.s_paddr = s.s_vaddr = ORG_TEXT;
s.s_size = codesize;
s.s_scnptr = HDRSIZE;
s.s_relptr = HDRSIZE + codesize + dataloc;
#ifdef TARGET_IS_STARDENT
s.o_nreloc = s.filler2 = 0;
#else
s.s_lnnoptr = 0; /* no line number info */
#endif
s.s_nreloc = (unsigned int)ncoderelocs;
#ifndef TARGET_IS_STARDENT
s.s_nlnno = 0; /* no line number info */
#endif
s.s_flags = STYP_TEXT;
obj_fwrite(&s, sizeof(s), 1, objstream);
/* data section header */
strncpy(s.s_name, ".data", sizeof(s.s_name));
s.s_paddr = s.s_vaddr = ORG_DATA;
s.s_size = dataloc;
s.s_scnptr = HDRSIZE + codesize;
s.s_relptr = HDRSIZE + codesize + dataloc + ncoderelocs*RELSZ;
#ifdef TARGET_IS_STARDENT
s.o_nreloc = s.filler2 = 0;
#else
s.s_lnnoptr = 0; /* no line number info */
#endif
s.s_nreloc = (unsigned int)ndatarelocs;
#ifndef TARGET_IS_STARDENT
s.s_nlnno = 0; /* no line number info */
#endif
s.s_flags = STYP_DATA;
obj_fwrite(&s, sizeof(s), 1, objstream);
#ifndef TARGET_IS_STARDENT
/* bss section header */
strncpy(s.s_name, ".bss", sizeof(s.s_name));
s.s_paddr = s.s_vaddr = ORG_BSS;
s.s_size = 0;
/* scnptr and relptr are irrelevant since size and nreloc are zero, */
/* but set them up in the natural manner (after the end of data scn). */
s.s_scnptr = HDRSIZE + codesize + dataloc;
s.s_relptr = HDRSIZE + codesize + dataloc +
ncoderelocs*RELSZ + ndatarelocs*RELSZ;
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 = STYP_BSS;
obj_fwrite(&s, sizeof(s), 1, objstream);
#endif
}
void obj_trailer()
{ codexrefs = (CodeXref *)dreverse((List *)codexrefs);
dataxrefs = (DataXref *)dreverse((List *)dataxrefs);
obj_symlist = (ExtRef *)dreverse((List *)obj_symlist);
/* oldest = smallest numbered first */
#ifdef TARGET_IS_MIPS
# ifndef TARGET_IS_STARDENT
obj_renumber_symbols();
# endif
#endif
if (debugging(DEBUG_OBJ)) cc_msg("writecode\n");
obj_writecode();
if (debugging(DEBUG_OBJ)) cc_msg("writedata\n");
obj_writedata();
if (debugging(DEBUG_OBJ)) cc_msg("coderelocation\n");
obj_coderelocation();
if (debugging(DEBUG_OBJ)) cc_msg("datarelocation\n");
obj_datarelocation();
if (debugging(DEBUG_OBJ)) cc_msg("symtab\n");
obj_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(). */
}
/* end of coffobj.c */
|
stardot/ncc | mip/jopcode.h | /*
* file mip/jopcode.h
* Copyright (C) Codemist Ltd., 1989.
* Copyright 1991-1997 Advanced Risc Machines Limited. All rights reserved
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$ Codemist 37
* Checkin $Date$
* Revising $Author$
*/
/*
* Some bits of information now live in the joptable[] array, while things
* like J_DEAD_R1 still live in the main code, since they need to be set
* on a per-instruction basis.
*/
#ifndef _jopcode_LOADED
#define _jopcode_LOADED 1
#ifndef _defs_LOADED
# include "defs.h"
#endif
/* The following are in for compatibility with old back ends only. */
#define J_MOVFR1 J_MOVIFR
#define J_MOVDR1 J_MOVIDR
#define J_double(op) J_fltisdouble(op)
/* Opcodes in the intermediate code that I generate. */
/* Idea -- the things beginning with '_' are local to this file, but... */
/* ... strictly speaking this contravenes ANSI's rules on '_' use. */
/* The following bits give 'global' (not per-use) properties of */
/* J_opcodes. The J_opcodes themselves are an enumeration below. */
/* _J_OPTYPE field must be LS bits since it is used as index. */
#define _J_OPTYPE 0x000fL /* Used just for LDR/STR opcodes (MEM_xxx) */
#define _J_READ_R1 0x0010L
#define _J_SET_R1 0x0020L
#define _J_READ_R2 0x0040L
#define _J_SET_R2 0x0080L /* only for MOVDIR/MOVLIR, arriving... */
#define _J_READ_R3 0x0100L /* r3 field is a register rather than literal */
#define _J_REGMOVE 0x0200L
#define _J_ASYMDIAD 0x0400L
#define _J_READ_R4 0x0800L
/* the next few bits are regarded JOP adressing modes. */
/* N.B. read the BEWARE on LDRK before using */
#define _J_MEM 0x1000L /* distinguishes mem ref from op */
#define _J_MEMA 0x3000L /* address of memory - really _J_MEM+0x2000 */
/* *** N.B. but for LDRV1 we could arrange that _J_MEMA was 0x104 ??? */
#define _J_STACKREF 0x4000L
#define _J_IVD 0x8000L /* indexed var + disp (only with _J_STACKREF) */
#define _J_GAP1 0x010000L /* r1 field always unused (printing) */
#define _J_GAP2 0x020000L /* r2 field always unused (printing) */
/* @@@ _J_FLOATING/_J_DOUBLE are dying -- only used in 'J_fltisdouble' */
/* @@@ 'floatiness()' and the latter is dying -- see cse.c */
/* It is arguable that these could be J_destregsort(op)->INTREG &c? */
#define _J_FLOATING 0x040000L /* overlaps use of MEM_F! */
#define _J_DOUBLE 0x080000L /* overlaps use of MEM_D! */
#define _J_PSEUDO_READS_R2 0x00100000L
#define _J_COMMUTATIVE 0x00200000L
#define _J_MEMW 0x80000000L /* writes to memory */
#define _J_MEMR 0x40000000L /* reads from memory */
/*
* The above bits are for joptable[], those which follow are part of the main
* opcode, but must not be used when indexing into joptable[].
*/
#define J_TABLE_BITS 0x1ff /* Room for 500 distinct jopcodes */
#define _joptable(o) (joptable[(o) & J_TABLE_BITS].bits)
#define J_BASEALIGN4 0x0200L
#define J_VOLATILE 0x0400L /* replacing J_USE/J_VSTORE, only LDRx/STRx */
/* N.B. The compiler currently does not represent 'volatile' on J_MOVC */
/* because large structs are not subject to dataflow analysis. */
/* Maybe it should, and hence maybe there should be two J_VOLATILE bits. */
#define J_DEAD_R1 0x0800L /* for dataflow analysis */
#define J_DEAD_R2 0x1000L /* for dataflow analysis */
#define J_DEAD_R3 0x2000L /* for dataflow analysis */
#define J_DEAD_R4 0x4000L /* for dataflow analysis */
#define J_DEADBITS (J_DEAD_R1+J_DEAD_R2+J_DEAD_R3+J_DEAD_R4)
#if defined TARGET_HAS_SCALED_ADDRESSING || defined TARGET_HAS_SCALED_OPS || \
defined TARGET_HAS_SCALED_ADD
# define J_NEGINDEX 0x8000L /* currently or-able with load/store only */
# define J_SHIFTMASK 0xff0000L
# define J_SHIFTPOS 16
# define SHIFT_MASK 0x3fL
# define SHIFT_RIGHT 0x80L
# define SHIFT_ARITH 0x40L
#endif
#define J_ALIGNMENT 0x03000000L /* May 92 experiment. */
#define J_ALIGN1 0x00000000L /* May 92 experiment. */
#define J_ALIGN2 0x01000000L /* May 92 experiment. */
#define J_ALIGN4 0x02000000L /* May 92 experiment. */
#define J_ALIGN8 0x03000000L /* May 92 experiment. */
#define J_ALIGNPOS 24
#define j_aligned(op,align) (((op) & J_ALIGNMENT) >= (align))
#define J_SIGNED 0x04000000L /* orable with LDRBx, LDRWx, also fix/float */
#define J_UNSIGNED 0x08000000L /* ditto */
#define J_ALIGNWR J_SIGNED /* => J_STRxx may write to J_ALIGN padding */
/* type bits (reallocate?) ... n.b. Q_UBIT shares with J_UNSIGNED */
/*
* The next few macros represent all the places where arithmetic is done
* on jopcodes to map between them, and hence these lines imply all the
* constraints that there are on the ordering of jopcodes within the
* enumeration:
* 1. When an instruction occurs in both R and K formats, the codes for the
* two must be adjacent. E.g. ADDK then ADDR.
* 2. The J_LDRVK forms loads and stores must immediately follow the RR form.
* 3. The J_LDRxx and J_STRxx opcodes are parallel (for J_LDtoST()).
* 4. The J_LDRV1 (I/F/K), J_MOVK (I/F/K), J_PUSH (I/F/K) are parallel (for
* flowgraf.c via J_XtoY()).
*/
#define J_RTOK(a) ((a) - 1)
#define J_KTOR(a) ((a) + 1)
#define J_addvk(a) ((a) + 2)
#define J_subvk(a) ((a) - 2)
#define J_KtoV(a) ((a) + 3) /* = J_XtoY(a, J_LDRK, J_LDRVK) etc. */
#define J_XtoY(a,x,y) ((a) + ((y)-(x)))
#define J_LDtoST(a) ((a) + (J_STRK-J_LDRK))
#define J_V1toV(a) ((a) + (J_LDRV-J_LDRV1))
/* It would be nice to arrange J_LDRxK = J_LDRBK + 4*MEM_x too. */
#define tailify_(a) ((a) + (J_TAILCALLK-J_CALLK))
/*
* TAILCALL & CALL separation does not impose any extra constraints here.
*/
/* auxiliary bits in the r2 field of OPSYSK and CALLK/R... */
#define K_ARGWORDMASK 0x00000fffL
#define K_FLAGS (~0x00ffffffL)
#define K_VACALL 0x01000000L /* call to variadic function */
#define K_VAFUNC K_VACALL /* function is variadic */
#define K_PURE 0x02000000L /* replaces J_CALLP */
#define K_SPECIAL_ARG 0x04000000L /* extra arg in an odd register */
#define K_INLINE 0x08000000L /* backend intends special expansion */
/* ECN: Use to mark a J_CALLK which is actually an entry in a Thunk table */
#define K_THUNK 0x10000000L /* C++ virtual function call */
/* ECN: Do not tailcall this call - hack for use with pSOS - used to */
/* improve debugability of system calls under pROBE */
#define K_NOTAILCALL 0x20000000L /* do not tailcall this call */
#define K_COMMUTATIVE 0x40000000L
#define K_RESULTINFLAGS 0x80000000L /* returns result in flags only */
#define k_argwords_(n) ((n)&K_ARGWORDMASK)
#define k_resultregs_(n) (((n)>>12)&15) /* struct result regs, 0 for function or procedure!!!! */
#define k_setresultregs_(n, k) (((n) & (~0x0000f000L)) | ((k) << 12))
#define k_setflags_(n, k) (((n) & ~K_FLAGS) | (k))
#define k_isvariadic_(n) ((n) & K_VACALL)
#define k_ispure_(n) ((n) & K_PURE)
#define k_iscommutative_(n) ((n) & K_COMMUTATIVE)
#define iscalln_(op, n) (isproccall_(op) && k_resultregs_(n) > 1)
#ifdef TARGET_FP_ARGS_IN_FP_REGS /* TARGET_FP_ARGS_CALLSTD1 */
#define k_argisfp_(n,i) ((i)<k_fltregs_(n))
#define k_intregs_(n) (((n)>>20)&15)
#define k_fltregs_(n) (((n)>>16)&15)
#define k_argregs_(n) (k_intregs_(n)+k_fltregs_(n))
#define k_argdesc_(aw, fm, ni, nf, nres, f) (((aw) >= 4095 ? 4095 : (aw)) | (f) | \
(((unsigned32)ni)<<20) | (((unsigned32)nf)<<16) | ((nres)<<12))
#else /* TARGET_FP_ARGS in integer registers only */
# define k_fltregs_(n) 0
#define k_argisfp_(n,i) 0
#define k_argregs_(n) (k_argwords_(n) < NARGREGS ? k_argwords_(n) : NARGREGS)
#define k_argdesc_(aw, fm, ni, nf, nres, f) \
((aw) | (f) | ((nres)<<12))
#endif
/*
* Now macros which test characteristics of codes. In some cases this is
* currently implemented as sets of tests where allocating extra bits in
* joptable may allow conversion to simple bit testing.
*/
#define register_movep(a) (_joptable(a) & _J_REGMOVE)
#define floatiness_(a) (_joptable(a) & (_J_DOUBLE+_J_FLOATING))
#define J_fltisdouble(a) (_joptable(a) & _J_DOUBLE)
#define vkformat(a) ((_joptable(a) & _J_MEM+_J_IVD) == _J_MEM+_J_IVD)
#define gap_r1(a) (_joptable(a) & _J_GAP1)
#define loads_r1(a) (_joptable(a) & _J_SET_R1)
#define reads_r1(a) (_joptable(a) & _J_READ_R1)
#define uses_r1(a) (_joptable(a) & (_J_SET_R1 | _J_READ_R1))
#define updates_r1(a) ((_joptable(a) & (_J_READ_R1 | _J_SET_R1)) == (_J_READ_R1 | _J_SET_R1))
/* The following test could easily be indicated by SET_R1+READ_R1 but */
/* currently various parts of the compiler assumes they are disjoint. */
/* Merging in certain J_MOVC cases seems indicated here too. */
/* <NAME> - remove for CC */
#ifndef CALLABLE_COMPILER
#ifndef TARGET_IS_ARM_OR_THUMB /* ARM/Thumb defines corrupts_r1/r2 in mcdep */
#ifdef TARGET_CORRUPTS_SWITCH_REGISTER
# define corrupts_r1(a) ((a)->op == J_CASEBRANCH)
#else
# define corrupts_r1(a) 0
#endif
#define corrupts_r2(a) 0
#endif
#endif /* ifndef CALLABLE_COMPILER */
#define stores_r1(a) ((_joptable(a) & (_J_MEM | _J_READ_R1)) == (_J_MEM | _J_READ_R1))
#define gap_r2(a) (_joptable(a) & _J_GAP2)
#define loads_r2(a) (_joptable(a) & _J_SET_R2)
#define reads_r2(a) (_joptable(a) & _J_READ_R2)
#define uses_r2(a) (_joptable(a) & (_J_SET_R2 | _J_READ_R2))
#define updates_r2(a) ((_joptable(a) & (_J_READ_R2 | _J_SET_R2)) == (_J_READ_R2 | _J_SET_R2))
#define reads_r3(a) (_joptable(a) & _J_READ_R3)
#define uses_r3(a) reads_r3(a)
#define reads_r4(a) (_joptable(a) & _J_READ_R4)
#define uses_r4(a) reads_r4(a)
#define uses_stack(a) ((_joptable(a) & _J_STACKREF+_J_MEM) == _J_STACKREF+_J_MEM)
#define reads_mem(a) (_joptable(a) & _J_MEMR)
#define writes_mem(a) (_joptable(a) & _J_MEMW)
#define j_is_ldr_or_str(a) ((_joptable(a) & (_J_MEM | _J_MEMA)) == _J_MEM)
#define j_is_commutative(a) (_joptable(a) & _J_COMMUTATIVE)
/* WD: TODO - make function of isproccall - include SWI!!! */
#ifdef TARGET_COUNT_IS_PROC
# define isproccall_(op) ((op) == J_CALLK || (op) == J_OPSYSK || \
(op) == J_CALLR || (op) == J_COUNT)
#else
# define isproccall_(op) ((op) == J_CALLK || (op) == J_OPSYSK || \
(op) == J_CALLR)
#endif
#ifdef TARGET_HAS_2ADDRESS_CODE
# define jop_asymdiadr_(op) \
((_joptable(op) & _J_ASYMDIAD+_J_READ_R3+_J_MEM) == _J_ASYMDIAD+_J_READ_R3)
/* maybe insert an is_anydiadr() here, but this think w.r.t. ADDK/ADDR and */
/* possible uses of load address target instructions. */
#endif
#define j_is_adcon(a) ((_joptable(a) & _J_MEMA) == _J_MEMA)
#define j_is_diadr(a) ((_joptable(a) & (_J_MEM | _J_READ_R4 | _J_READ_R3 |\
_J_READ_R2 | _J_READ_R1)) ==\
(_J_READ_R3 | _J_READ_R2))
#define j_is_diadk(a) ((_joptable(a) & (_J_MEM | _J_READ_R4 | _J_READ_R3 |\
_J_READ_R2 | _J_READ_R1)) ==\
(_J_READ_R2))
/* Note: is-diadicx does not imply sets_r1 */
/* The following two macros are only used by jopprint.c and regalloc.c -- */
/* this is important since they are not overkeen about masking Q_MASK or */
/* J_DEADBITS. Note that they must correspond to the loop optimisation */
/* code in loopopt.c and its friends in flowgraf.c */
/* Note that J_FNCON does not need considering as only this is only used */
/* in the interface to xxxgen.c from flowgraf.c (q.v.) */
#ifdef RANGECHECK_SUPPORTED
# define pseudo_reads_r1(a) (((a) & ~Q_MASK) == J_CMPK ||\
(a)==J_CHKLK || (a)==J_CHKUK || (a)==J_CHKNEK)
# define j_is_check(op) \
((J_CHKLK<=(op) && (op)<=J_CHKUR) || (J_CHKNEFK<=(op) && (op)<=J_CHKNER))
#else
# define pseudo_reads_r1(a) (((a) & ~Q_MASK) == J_CMPK)
# define j_is_check(op) 0
#endif
#define pseudo_reads_r2(a) (_joptable(a) & _J_PSEUDO_READS_R2)
/* The following give machine types of store reference in LD/STxxx. */
#define MEM_B 0L
#define MEM_W 1L
#define MEM_I 2L /* 32 bits -- avoid suffix L for a while. */
#define MEM_F 3L
#define MEM_D 4L
#define MEM_LL 5L /* 64 bits -- avoid suffix L for a while. */
#define j_memsize(a) (_joptable(a) & _J_OPTYPE) /* (MEM_xxx not bytes) */
/* It would be nice to arrange J_LDRxK = J_LDRBK + 4*MEM_x too. */
/* Note: if someone sets alignof_double < 8 then they could */
/* hardly expect J_ALIGN8 on a double to have any meaning? */
/* Hence we set J_ALIGN8 for all J_LDRDK's, even if alignof_double=4. */
/* Think a little more about SPARC with mis-aligned double. */
#define MEM_to_J_LDRxK_table \
{ J_LDRBK|J_ALIGN1, J_LDRWK|J_ALIGN2, J_LDRK|J_ALIGN4, \
J_LDRFK|J_ALIGN4, J_LDRDK|J_ALIGN8, J_LDRLK|J_ALIGN8 }
#ifdef TARGET_LACKS_MULDIV_LITERALS
# define jop_canRTOK(op) \
(((op) != J_MULR) && \
((op) & ~(J_SIGNED+J_UNSIGNED)) != J_DIVR && \
((op) & ~(J_SIGNED+J_UNSIGNED)) != J_REMR)
#else
#ifdef TARGET_LACKS_MULTIPLY_LITERALS
# define jop_canRTOK(op) \
((op) != J_MULR)
#else
#ifdef TARGET_LACKS_DIVIDE_LITERALS
# define jop_canRTOK(op) \
(((op) & ~(J_SIGNED+J_UNSIGNED)) != J_DIVR && \
((op) & ~(J_SIGNED+J_UNSIGNED)) != J_REMR)
#else
# define jop_canRTOK(op) 1
#endif
#endif
#endif
#ifdef DEFINE_JOPTABLE
/*
* Although it is generally a nasty thing to do, I have a definition of
* the initialised array joptable here in a header file, in such a way that
* it is only activated if the macro DEFINE_JOPTABLE is defined. This must
* be so for exactly one place in the source where jopcode.h gets included.
* Doing things this way allows me to keep the enumeration of codes in step
* with associated entries in the array.
* NB: conditional compilation within this table might cause things to
* get out of step - so beware.
*/
# if defined ENABLE_CG || defined ENABLE_REGS || defined ENABLE_CSE
# define with_bits(n, b) {n, b},
extern struct JopTable { char *name; unsigned32 bits; } joptable[];
struct JopTable joptable[] = {
# else
# define with_bits(n, b) { b },
extern struct JopTable { unsigned32 bits; } joptable[];
struct JopTable joptable[] = {
# endif
#else
# define with_bits(n, b)
# if defined ENABLE_CG || defined ENABLE_REGS || defined ENABLE_CSE
extern struct JopTable { char *name; unsigned32 bits; } joptable[];
# else
extern struct JopTable { unsigned32 bits; } joptable[];
# endif
#endif
/*
* Note that whenever an operand has both an R and a K (register and literal
* operand) form the two must appear adjacent in this table for J_RTOK()
* Towards the start of this table there are some other numbering nasties
* which allow rapid conversion between related codes - see the macros defined
* above for what is done, and do not re-order this table or insert or
* delete entries without understanding the consequences.
* In particular, note that there must be no gaps, since the numbering
* of jopcodes is used as an index into the table created by with_bits().
*/
#define _ldr(MEM_x) _J_MEMR+_J_MEM+MEM_x /* loads a single byte/short/word from memory */
#define _str(MEM_x) _J_MEMW+_J_MEM+MEM_x /* stores a single byte/short/word to memory */
#define _memr(MEM_x) _J_MEMW+MEM_x /* reads data from memory */
#define _memw(MEM_x) _J_MEMW+MEM_x /* stores data to memory */
#define _memrw(MEM_x) _J_MEMR+_J_MEMW+MEM_x /* reads and writes data to memory */
#define J_NOOP 0L
with_bits("NOOP", _J_GAP1+_J_GAP2)
#define J_LABEL 1L
with_bits("LABEL", _J_GAP1+_J_GAP2)
#define J_B 2L
with_bits("B", _J_GAP1+_J_GAP2)
#define J_BXX 3L /* as J_B but within branch table */
with_bits("BXX", _J_GAP1+_J_GAP2)
#define J_LDRK 4L /* see J_LDRV1 for ordering */
with_bits("LDRK", _ldr(MEM_I)+_J_READ_R2+_J_SET_R1)
#define J_LDRR 5L
with_bits("LDRR", _ldr(MEM_I)+_J_READ_R3+_J_READ_R2+_J_SET_R1+_J_COMMUTATIVE)
#define J_LDRVK 6L
with_bits("LDRVK", _ldr(MEM_I)+_J_STACKREF+_J_IVD+_J_SET_R1)
#define J_LDRV 7L
with_bits("LDRV", _ldr(MEM_I)+_J_SET_R1+_J_STACKREF+_J_GAP2)
#define J_LDRBK 8L
with_bits("LDRBK", _ldr(MEM_B)+_J_READ_R2+_J_SET_R1)
#define J_LDRBR 9L
with_bits("LDRBR", _ldr(MEM_B)+_J_READ_R3+_J_READ_R2+_J_SET_R1+_J_COMMUTATIVE)
#define J_LDRBVK 10L
with_bits("LDRBVK", _ldr(MEM_B)+_J_STACKREF+_J_IVD+_J_SET_R1)
#define J_LDRBV 11L /* unused Apr 92 */
with_bits("LDRBV", _ldr(MEM_B)+_J_SET_R1+_J_STACKREF+_J_GAP2)
#define J_LDRWK 12L
with_bits("LDRWK", _ldr(MEM_W)+_J_READ_R2+_J_SET_R1)
#define J_LDRWR 13L
with_bits("LDRWR", _ldr(MEM_W)+_J_READ_R3+_J_READ_R2+_J_SET_R1+_J_COMMUTATIVE)
#define J_LDRWVK 14L
with_bits("LDRWVK", _ldr(MEM_W)+_J_STACKREF+_J_IVD+_J_SET_R1)
#define J_LDRWV 15L /* unused Apr 92 */
with_bits("LDRWV", _ldr(MEM_W)+_J_SET_R1+_J_STACKREF+_J_GAP2)
#define J_LDRLK 16L
with_bits("LDRLK", _ldr(MEM_LL)+_J_READ_R2+_J_SET_R1)
#define J_LDRLR 17L
with_bits("LDRLR", _ldr(MEM_LL)+_J_READ_R3+_J_READ_R2+_J_SET_R1+_J_COMMUTATIVE)
#define J_LDRLVK 18L
with_bits("LDRLVK", _ldr(MEM_LL)+_J_STACKREF+_J_IVD+_J_SET_R1)
#define J_LDRLV 19L /* unused Apr 92 */
with_bits("LDRLV", _ldr(MEM_LL)+_J_SET_R1+_J_STACKREF+_J_GAP2)
#define J_LDRFK 20L
with_bits("LDRFK", _J_FLOATING+_ldr(MEM_F)+_J_READ_R2+_J_SET_R1)
#define J_LDRFR 21L
with_bits("LDRFR", _J_FLOATING+_ldr(MEM_F)+_J_READ_R3+_J_READ_R2+_J_SET_R1+_J_COMMUTATIVE)
#define J_LDRFVK 22L
with_bits("LDRFVK", _J_FLOATING+_ldr(MEM_F)+_J_STACKREF+_J_IVD+_J_SET_R1)
#define J_LDRFV 23L
with_bits("LDRFV", _J_FLOATING+_ldr(MEM_F)+_J_SET_R1+_J_STACKREF+_J_GAP2)
#define J_LDRDK 24L
with_bits("LDRDK", _J_DOUBLE+_ldr(MEM_D)+_J_READ_R2+_J_SET_R1)
#define J_LDRDR 25L
with_bits("LDRDR", _J_DOUBLE+_ldr(MEM_D)+_J_READ_R3+_J_READ_R2+_J_SET_R1+_J_COMMUTATIVE)
#define J_LDRDVK 26L
with_bits("LDRDVK", _J_DOUBLE+_ldr(MEM_D)+_J_STACKREF+_J_IVD+_J_SET_R1)
#define J_LDRDV 27L
with_bits("LDRDV", _J_DOUBLE+_ldr(MEM_D)+_J_SET_R1+_J_STACKREF+_J_GAP2)
#define J_STRK 28L
with_bits("STRK", _str(MEM_I)+_J_READ_R2+_J_READ_R1)
#define J_STRR 29L
with_bits("STRR", _str(MEM_I)+_J_READ_R3+_J_READ_R2+_J_READ_R1+_J_COMMUTATIVE)
#define J_STRVK 30L
with_bits("STRVK", _str(MEM_I)+_J_STACKREF+_J_IVD+_J_READ_R1)
#define J_STRV 31L
with_bits("STRV", _str(MEM_I)+_J_READ_R1+_J_STACKREF+_J_GAP2)
#define J_STRBK 32L
with_bits("STRBK", _str(MEM_B)+_J_READ_R2+_J_READ_R1)
#define J_STRBR 33L
with_bits("STRBR", _str(MEM_B)+_J_READ_R3+_J_READ_R2+_J_READ_R1+_J_COMMUTATIVE)
#define J_STRBVK 34L
with_bits("STRBVK", _str(MEM_B)+_J_STACKREF+_J_IVD+_J_READ_R1)
#define J_STRBV 35L /* unused Apr 92 */
with_bits("STRBV", _str(MEM_B)+_J_READ_R1+_J_STACKREF+_J_GAP2)
#define J_STRWK 36L
with_bits("STRWK", _str(MEM_W)+_J_READ_R2+_J_READ_R1)
#define J_STRWR 37L
with_bits("STRWR", _str(MEM_W)+_J_READ_R3+_J_READ_R2+_J_READ_R1+_J_COMMUTATIVE)
#define J_STRWVK 38L
with_bits("STRWVK", _str(MEM_W)+_J_STACKREF+_J_IVD+_J_READ_R1)
#define J_STRWV 39L /* unused Apr 92 */
with_bits("STRWV", _str(MEM_W)+_J_READ_R1+_J_STACKREF+_J_GAP2)
#define J_STRLK 40L
with_bits("STRLK", _str(MEM_LL)+_J_READ_R2+_J_READ_R1)
#define J_STRLR 41L
with_bits("STRLR", _str(MEM_LL)+_J_READ_R3+_J_READ_R2+_J_READ_R1+_J_COMMUTATIVE)
#define J_STRLVK 42L
with_bits("STRLVK", _str(MEM_LL)+_J_STACKREF+_J_IVD+_J_READ_R1)
#define J_STRLV 43L /* unused Apr 92 */
with_bits("STRLV", _str(MEM_LL)+_J_READ_R1+_J_STACKREF+_J_GAP2)
#define J_STRFK 44L
with_bits("STRFK", _J_FLOATING+_str(MEM_F)+_J_READ_R2+_J_READ_R1)
#define J_STRFR 45L
with_bits("STRFR", _J_FLOATING+_str(MEM_F)+_J_READ_R3+_J_READ_R2+_J_READ_R1+_J_COMMUTATIVE)
#define J_STRFVK 46L
with_bits("STRFVK", _J_FLOATING+_str(MEM_F)+_J_STACKREF+_J_IVD+_J_READ_R1)
#define J_STRFV 47L
with_bits("STRFV", _J_FLOATING+_str(MEM_F)+_J_READ_R1+_J_STACKREF+_J_GAP2)
#define J_STRDK 48L
with_bits("STRDK", _J_DOUBLE+_str(MEM_D)+_J_READ_R2+_J_READ_R1)
#define J_STRDR 49L
with_bits("STRDR", _J_DOUBLE+_str(MEM_D)+_J_READ_R3+_J_READ_R2+_J_READ_R1+_J_COMMUTATIVE)
#define J_STRDVK 50L
with_bits("STRDVK", _J_DOUBLE+_str(MEM_D)+_J_STACKREF+_J_IVD+_J_READ_R1)
#define J_STRDV 51L
with_bits("STRDV", _J_DOUBLE+_str(MEM_D)+_J_READ_R1+_J_STACKREF+_J_GAP2)
#define J_LDRV1 52L /* see LDRFV1 */
with_bits("LDRV1", _ldr(MEM_I)+_J_SET_R1+_J_STACKREF+_J_GAP2)
#define J_PUSHR 53L
with_bits("PUSHR", _memw(0)+_J_READ_R1+_J_GAP2)
#define J_MOVK 54L
with_bits("MOVK", _J_SET_R1+_J_PSEUDO_READS_R2)
#define J_MOVR 55L
with_bits("MOVR", _J_READ_R3+_J_SET_R1+_J_REGMOVE+_J_GAP2)
#define J_CMPK 56L /* see pseudo_reads_r2() (loop opt) */
with_bits("CMPK", _J_READ_R2)
#define J_CMPR 57L
with_bits("CMPR", _J_READ_R3+_J_READ_R2+_J_GAP1)
#define J_CHKLK 58L
with_bits("CHKLK", _J_READ_R2)
#define J_CHKLR 59L
with_bits("CHKLR", _J_READ_R3+_J_READ_R2+_J_GAP1)
#define J_CHKUK 60L
with_bits("CHKUK", _J_READ_R2)
#define J_CHKUR 61L
with_bits("CHKUR", _J_READ_R3+_J_READ_R2+_J_GAP1)
#define J_STACK 62L
with_bits("STACK", _J_GAP1+_J_GAP2)
#define J_SETSPENV 63L
with_bits("SETSPENV", _J_GAP1+_J_GAP2)
#define J_LDRLV1 64L /* must be J_LDRV1 + (J_LDRLK-K_LDRVK) */
with_bits("LDRLV1", _ldr(MEM_I)+_J_SET_R1+_J_STACKREF+_J_GAP2)
#define J_PUSHL 65L
with_bits("PUSHL", _memw(0)+_J_READ_R1+_J_GAP2)
#define J_MOVLK 66L
with_bits("MOVLK", _J_SET_R1)
#define J_MOVLR 67L
with_bits("MOVLR", _J_READ_R3+_J_SET_R1+_J_REGMOVE+_J_GAP2)
#define J_LDRFV1 68L /* must be J_LDRV1 + (J_LDRFK-K_LDRVK) */
with_bits("LDRFV1", _J_FLOATING+_ldr(MEM_F)+_J_SET_R1+_J_STACKREF+_J_GAP2)
#define J_PUSHF 69L
with_bits("PUSHF", _J_FLOATING+_J_READ_R1+_J_GAP2)
#define J_MOVFK 70L
with_bits("MOVFK", _J_FLOATING+_J_SET_R1+_J_GAP2)
#define J_MOVFR 71L
with_bits("MOVFR", _J_FLOATING+_J_READ_R3+_J_SET_R1+_J_REGMOVE+_J_GAP2)
#define J_LDRDV1 72L /* must be J_LDRV1 + (J_LDRDK-K_LDRVK) */
with_bits("LDRDV1", _J_DOUBLE+_ldr(MEM_D)+_J_SET_R1+_J_STACKREF+_J_GAP2)
#define J_PUSHD 73L
with_bits("PUSHD", _memw(0)+_J_DOUBLE+_J_READ_R1+_J_GAP2)
#define J_MOVDK 74L
with_bits("MOVDK", _J_DOUBLE+_J_SET_R1+_J_GAP2)
#define J_MOVDR 75L
with_bits("MOVDR", _J_DOUBLE+_J_READ_R3+_J_SET_R1+_J_REGMOVE+_J_GAP2)
#define J_ANDK 76L
with_bits("ANDK", _J_READ_R2+_J_SET_R1)
#define J_ANDR 77L
with_bits("ANDR", _J_READ_R3+_J_READ_R2+_J_SET_R1+_J_COMMUTATIVE)
#define J_ORRK 78L
with_bits("ORRK", _J_READ_R2+_J_SET_R1)
#define J_ORRR 79L
with_bits("ORRR", _J_READ_R3+_J_READ_R2+_J_SET_R1+_J_COMMUTATIVE)
#define J_EORK 80L
with_bits("EORK", _J_READ_R2+_J_SET_R1)
#define J_EORR 81L
with_bits("EORR", _J_READ_R3+_J_READ_R2+_J_SET_R1+_J_COMMUTATIVE)
#define J_ADDK 82L
with_bits("ADDK", _J_READ_R2+_J_SET_R1)
#define J_ADDR 83L
with_bits("ADDR", _J_READ_R3+_J_READ_R2+_J_SET_R1+_J_COMMUTATIVE)
#define J_CALLK 84L
with_bits("CALLK", _J_SET_R1)
#define J_CALLR 85L
with_bits("CALLR", _J_READ_R3+_J_SET_R1)
#define J_MULK 86L
with_bits("MULK", _J_READ_R2+_J_SET_R1)
#define J_MULR 87L
with_bits("MULR", _J_READ_R3+_J_READ_R2+_J_SET_R1+_J_COMMUTATIVE)
#define J_CMPFK 88L
with_bits("CMPFK", _J_FLOATING+_J_READ_R2+_J_GAP1)
#define J_CMPFR 89L
with_bits("CMPFR", _J_FLOATING+_J_READ_R3+_J_READ_R2+_J_GAP1)
#define J_CHKNEFK 90L
with_bits("CHKNEFK", _J_FLOATING+_J_READ_R2+_J_GAP1)
#define J_CHKNEFR 91L
with_bits("CHKNEFR", _J_FLOATING+_J_READ_R3+_J_READ_R2+_J_GAP1)
#define J_CHKNEDK 92L /* was misspelt J_CMPNEDK */
with_bits("CHKNEDK", _J_DOUBLE+_J_READ_R2+_J_GAP1)
#define J_CHKNEDR 93L
with_bits("CHKNEDR", _J_DOUBLE+_J_READ_R3+_J_READ_R2+_J_GAP1)
#define J_CHKNEK 94L
with_bits("CHKNEK", _J_READ_R2)
#define J_CHKNER 95L
with_bits("CHKNER", _J_READ_R3+_J_READ_R2+_J_GAP1)
#define J_OPSYSK 96L
with_bits("OPSYSK", _J_SET_R1)
#define CSE_LOADR 97L /* wanted internally by CSE */
with_bits("CSE_LOADR", _J_SET_R1)
#define J_INIT 98L
with_bits("INIT", _J_SET_R1+_J_GAP2)
#define J_ENTER 99L /* special effect on registers */
with_bits("ENTER", _J_GAP1+_J_GAP2)
#define J_ENDPROC 100L
with_bits("ENDPROC", _J_GAP1+_J_GAP2)
/*
* From here onwards the order of jopcodes is less important.
*/
#define J_ADCONF 101L /* only if SOFTWARE_FLOATING_POINT */
with_bits("ADCONF", _J_MEMA+_J_SET_R1+_J_PSEUDO_READS_R2)
#define J_ADCOND 102L /* only if SOFTWARE_FLOATING_POINT */
with_bits("ADCOND", _J_MEMA+_J_SET_R1+_J_PSEUDO_READS_R2)
#define J_STRING 103L
with_bits("STRING", _J_SET_R1)
#define J_SUBK 104L
with_bits("SUBK", _J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_SUBR 105L
with_bits("SUBR", _J_READ_R3+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_DIVK 106L /* must or in J_SIGNED/J_UNSIGNED */
with_bits("DIVK", _J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_DIVR 107L
with_bits("DIVR", _J_READ_R3+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_RSBK 108L /* should only happen as J_RSBR+J_SHIFTM */
with_bits("RSBK", _J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_RSBR 109L /* should only happen as J_RSBR+J_SHIFTM */
with_bits("RSBR", _J_READ_R3+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_REMK 110L /* must or in J_SIGNED/J_UNSIGNED */
with_bits("REMK", _J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_REMR 111L
with_bits("REMR", _J_READ_R3+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_SHLK 112L /* must or in J_SIGNED/J_UNSIGNED */
with_bits("SHLK", _J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_SHLR 113L
with_bits("SHLR", _J_READ_R3+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_SHRK 114L /* must or in J_SIGNED/J_UNSIGNED */
with_bits("SHRK", _J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_SHRR 115L
with_bits("SHRR", _J_READ_R3+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_INLINE1 116L
with_bits("INLINE1", _J_READ_R2+_J_SET_R1)
#define J_NEGR 117L
with_bits("NEGR", _J_READ_R3+_J_SET_R1+_J_GAP2)
#define J_NOTR 118L
with_bits("NOTR", _J_READ_R3+_J_SET_R1+_J_GAP2)
#define J_ADCONV 119L /* special use of r2 field */
with_bits("ADCONV", _J_MEMA+_J_SET_R1+_J_STACKREF+_J_PSEUDO_READS_R2)
#define J_USEF 120L
with_bits("USEF", _J_FLOATING+_J_READ_R1+_J_GAP2)
#define J_INITF 121L
with_bits("INITF", _J_FLOATING+_J_SET_R1+_J_GAP2)
#define J_ADDFK 122L
with_bits("ADDFK", _J_FLOATING+_J_READ_R2+_J_SET_R1)
#define J_ADDFR 123L
with_bits("ADDFR", _J_FLOATING+_J_READ_R3+_J_READ_R2+_J_SET_R1+_J_COMMUTATIVE)
#define J_MULFK 124L
with_bits("MULFK", _J_FLOATING+_J_READ_R2+_J_SET_R1)
#define J_MULFR 125L
with_bits("MULFR", _J_FLOATING+_J_READ_R3+_J_READ_R2+_J_SET_R1+_J_COMMUTATIVE)
#define J_INLINE1F 126L
with_bits("INLINE1F", _J_FLOATING+_J_READ_R2+_J_SET_R1)
#define J_SUBFK 127L
with_bits("SUBFK", _J_FLOATING+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_SUBFR 128L
with_bits("SUBFR", _J_FLOATING+_J_READ_R3+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_DIVFK 129L
with_bits("DIVFK", _J_FLOATING+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_DIVFR 130L
with_bits("DIVFR", _J_FLOATING+_J_READ_R3+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_NEGFR 131L
with_bits("NEGFR", _J_FLOATING+_J_READ_R3+_J_SET_R1+_J_GAP2)
#define J_FLTFR 132L
with_bits("FLTFR", _J_FLOATING+_J_READ_R3+_J_SET_R1)
#define J_FIXFR 133L
with_bits("FIXFR", _J_FLOATING+_J_READ_R3+_J_SET_R1)
#define J_MOVDFR 134L
with_bits("MOVDFR", _J_FLOATING+_J_READ_R3+_J_SET_R1+_J_GAP2)
#define J_MOVIFR 135L
with_bits("MOVIFR", _J_FLOATING+_J_READ_R3+_J_SET_R1+_J_GAP2)
#define J_ADCON 136L
with_bits("ADCON", _J_MEMA+_J_SET_R1+_J_PSEUDO_READS_R2)
#define J_USED 137L
with_bits("USED", _J_DOUBLE+_J_READ_R1+_J_GAP2)
#define J_INITD 138L
with_bits("INITD", _J_DOUBLE+_J_SET_R1+_J_GAP2)
#define J_CMPDK 139L
with_bits("CMPDK", _J_DOUBLE+_J_READ_R2+_J_GAP1)
#define J_CMPDR 140L
with_bits("CMPDR", _J_DOUBLE+_J_READ_R3+_J_READ_R2+_J_GAP1)
#define J_ADDDK 141L
with_bits("ADDDK", _J_DOUBLE+_J_READ_R2+_J_SET_R1)
#define J_ADDDR 142L
with_bits("ADDDR", _J_DOUBLE+_J_READ_R3+_J_READ_R2+_J_SET_R1+_J_COMMUTATIVE)
#define J_MULDK 143L
with_bits("MULDK", _J_DOUBLE+_J_READ_R2+_J_SET_R1)
#define J_MULDR 144L
with_bits("MULDR", _J_DOUBLE+_J_READ_R3+_J_READ_R2+_J_SET_R1+_J_COMMUTATIVE)
#define J_MOVIDR 145L /* a bit special - doesn't require r1/r3 clash. */
with_bits("MOVIDR", _J_DOUBLE+_J_READ_R3+_J_READ_R2+_J_SET_R1)
#define J_INLINE1D 146L
with_bits("INLINE1D", _J_DOUBLE+_J_READ_R2+_J_SET_R1)
#define J_SUBDK 147L
with_bits("SUBDK", _J_DOUBLE+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_SUBDR 148L
with_bits("SUBDR", _J_DOUBLE+_J_READ_R3+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_DIVDK 149L
with_bits("DIVDK", _J_DOUBLE+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_DIVDR 150L
with_bits("DIVDR", _J_DOUBLE+_J_READ_R3+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_NEGDR 151L
with_bits("NEGDR", _J_DOUBLE+_J_READ_R3+_J_SET_R1+_J_GAP2)
#define J_FLTDR 152L
with_bits("FLTDR", _J_DOUBLE+_J_READ_R3+_J_SET_R1+_J_GAP2)
#define J_FIXDR 153L
with_bits("FIXDR", _J_DOUBLE+_J_READ_R3+_J_SET_R1+_J_GAP2)
#define J_MOVFDR 154L
with_bits("MOVFDR", _J_DOUBLE+_J_READ_R3+_J_SET_R1+_J_GAP2)
#define CSE_WORD1 155L
with_bits("CSE_WORD1", _J_DOUBLE+_J_READ_R3+_J_SET_R1)
#define CSE_WORD2 156L
with_bits("CSE_WORD2", _J_DOUBLE+_J_READ_R3+_J_SET_R1)
/*
* Things from here on are not needed for all targets.
*/
#define J_CLRC 157L
with_bits("CLRC", _memw(0)+_J_READ_R1)
#define J_MOVC 158L
with_bits("MOVC", _memrw(0)+_J_READ_R2+_J_READ_R1)
#define J_TAILCALLK 159L /* see tailify_() */
with_bits("TAILCALLK", _J_SET_R1)
#define J_TAILCALLR 160L /* see tailify_() */
with_bits("TAILCALLR", _J_READ_R3+_J_SET_R1)
/* The following are not used at present, but may be sometime - when they
* are the numbering of jopcodes will probably need rearranging to fit these
* in somewhere better than at the end. Indeed some of these MAY be used now...
* but sort of experimentally!
*/
#define J_COUNT 161L
with_bits("COUNT", _J_GAP1+_J_GAP2)
#define J_INFOLINE 162L
with_bits("INFOLINE", 0)
#define J_INFOSCOPE 163L
with_bits("INFOSCOPE", _J_GAP1+_J_GAP2)
#define J_INFOBODY 164L
with_bits("INFOBODY", 0)
#define J_RESULT2 165L
with_bits("RESULT2", _J_READ_R3+_J_SET_R1)
#define J_FNCON 166L /* only if TARGET_CALL_USES_DESCRIPTOR */
with_bits("FNCON", _J_MEMA+_J_SET_R1)
/* AM reserves the next two opcodes for flt->int reg moves. */
/* Note that MOVDIR sets r1 and r2. Regalloc beware. */
#define J_MOVDIR 167L
with_bits("MOVDIR", _J_SET_R1+_J_SET_R2+_J_READ_R3)
#define J_MOVFIR 168L
with_bits("MOVFIR", _J_SET_R1+_J_READ_R3+_J_GAP2)
#define J_THUNKTABLE 169L /* compare J_CASEBRANCH */
with_bits("THUNKTABLE", _J_GAP1)
#define J_EXTEND 170L /* sign extend */
with_bits("EXTEND", _J_SET_R1+_J_READ_R2)
#define J_RORK 171L
with_bits("RORK", _J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_RORR 172L
with_bits("RORR", _J_READ_R3+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_ORG 173L
with_bits("ORG", _J_GAP1+_J_GAP2)
#define J_SAVE 174L
with_bits("SAVE", _J_GAP1+_J_GAP2)
#define J_PUSHM 175L /* for the back end, reg map */
with_bits("PUSHM", _memw(0)+_J_GAP1+_J_GAP2)
#define J_spare176 176L
with_bits("x176x", _J_GAP1+_J_GAP2)
#define J_WORD 177L
with_bits("WORD", _J_GAP1+_J_GAP2)
#define J_CONDEXEC 178L
with_bits("CONDEXEC", _J_GAP1+_J_GAP2)
#define J_VSTORE 179L
with_bits("VSTORE", _J_GAP1+_J_GAP2)
#define J_MOVLIR 180L
with_bits("MOVLIR", _J_SET_R1+_J_SET_R2+_J_READ_R3)
#define J_MOVILR 181L
with_bits("MOVILR", _J_SET_R1+_J_READ_R2+_J_READ_R3)
#define J_SETSPGOTO 182L
with_bits("SETSPGOTO", _J_GAP1+_J_GAP2)
#define J_SETSP 183L
with_bits("SETSP", _J_GAP1)
#define J_CASEBRANCH 184L /* dispatch into branch table */
with_bits("CASEBRANCH", _J_READ_R1)
#define J_USE 185L /* uses R1 (for support of 'volatile') */
with_bits("USE", _J_READ_R1+_J_GAP2)
#define J_SCCK 186L /* compare J_CONDEXEC */
with_bits("SCCK", _J_SET_R1)
#define J_BZ 187L /* For 88000 back-end use only */
with_bits("BZ", _J_READ_R2)
/* ECN: Some jopcodes for creating Thumb vtables
* J_WORD_ADCON -> DCD extern
* J_WORD_LABEL -> DCD L<n>
* J_THIS_ADJUST -> ADD R1, R2, #K (but cannot be done using J_ADDK
* because we need to know it
* is a pointer adjustment so we
* can generate ARM or Thumb
* instructions as appropriate)
* ECN: It is too difficult to try and conditionalise this on THUMB_CPLUSPLUS
* as peepgen includes this header to derive peeppat.c. May be generically
* useful anyway (at least J_WORD_ADCON & J_WORD_LABEL).
*/
#define J_WORD_ADCON 188L
with_bits("WORD.A", _J_GAP1+_J_GAP2)
#define J_WORD_LABEL 189L
with_bits("WORD.L", _J_GAP1+_J_GAP2)
#define J_THIS_ADJUST 190L
with_bits("ADJUST", _J_READ_R2+_J_SET_R1)
#define J_RSBDK 191L
with_bits("RSBDK", _J_DOUBLE+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_RSBDR 192L
with_bits("RSBDR", _J_DOUBLE+_J_READ_R3+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_RDVDK 193L
with_bits("RDVDK", _J_DOUBLE+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_RDVDR 194L
with_bits("RDVDR", _J_DOUBLE+_J_READ_R3+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_RSBFK 195L
with_bits("RSBDK", _J_FLOATING+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_RSBFR 196L
with_bits("RSBDR", _J_FLOATING+_J_READ_R3+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_RDVFK 197L
with_bits("RDVFK", _J_DOUBLE+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_RDVFR 198L
with_bits("RDVFR", _J_DOUBLE+_J_READ_R3+_J_READ_R2+_J_SET_R1+_J_ASYMDIAD)
#define J_MLAR 199
with_bits("MLAR", _J_READ_R4+_J_READ_R3+_J_READ_R2+_J_SET_R1)
#define J_MLAK 200
with_bits("MLAK", _J_READ_R4+_J_READ_R2+_J_SET_R1)
#define J_MULL 201
with_bits("MULL", _J_READ_R4+_J_READ_R3+_J_SET_R2+_J_SET_R1)
#define J_MLAL 202
with_bits("MLAL", _J_READ_R4+_J_READ_R3+_J_READ_R2+_J_READ_R1+_J_SET_R2+_J_SET_R1)
#define J_ADCONLL 203
with_bits("ADCONLL", _J_MEMA+_J_SET_R1+_J_PSEUDO_READS_R2)
#define CSE_COND 204
with_bits("CSE_COND", 0)
#define J_TYPECASE 205
with_bits("TYPECASE", 0)
#define J_FIXFRM 206L
with_bits("FIXDRM", _J_DOUBLE+_J_READ_R3+_J_SET_R1+_J_GAP2)
#define J_FIXDRM 207L
with_bits("FIXDRM", _J_FLOATING+_J_READ_R3+_J_SET_R1+_J_GAP2)
#define J_EXTABLE 208L
with_bits("EXTABLE", 0)
#define J_EXHANDLER 209L
with_bits("EXHANDLER", 0)
#if !defined(ARM_INLINE_ASSEMBLER) && !defined(THUMB_INLINE_ASSEMBLER)
/* WD: ARM & Thumb share a few opcodes (LDM/STM/BL/SWI) Separate these out later */
#define J_LAST_JOPCODE 209
#else
#define J_FIRST_ASM_JOPCODE 210
#define J_ABINRK J_FIRST_ASM_JOPCODE
with_bits("BINRK", _J_READ_R2+_J_SET_R1)
#define J_ABINRR (J_FIRST_ASM_JOPCODE+1)
with_bits("BINRR", _J_READ_R3+_J_READ_R2+_J_SET_R1)
#define J_ABINRRK (J_FIRST_ASM_JOPCODE+2)
with_bits("BINRRK", _J_READ_R3+_J_READ_R2+_J_SET_R1)
#define J_ABINRRR (J_FIRST_ASM_JOPCODE+3)
with_bits("BINRRR", _J_READ_R4+_J_READ_R3+_J_READ_R2+_J_SET_R1)
#define J_AMOVK (J_FIRST_ASM_JOPCODE+4)
with_bits("MOVK", _J_SET_R1)
#define J_AMOVR (J_FIRST_ASM_JOPCODE+5)
with_bits("MOVR", _J_READ_R3+_J_SET_R1)
#define J_AMOVRK (J_FIRST_ASM_JOPCODE+6)
with_bits("MOVRK", _J_READ_R3+_J_SET_R1)
#define J_AMOVRR (J_FIRST_ASM_JOPCODE+7)
with_bits("MOVRR", _J_READ_R4+_J_READ_R3+_J_SET_R1)
#define J_ACMPK (J_FIRST_ASM_JOPCODE+8)
with_bits("CMPK", _J_READ_R2)
#define J_ACMPR (J_FIRST_ASM_JOPCODE+9)
with_bits("CMPR", _J_READ_R2+_J_READ_R3)
#define J_ACMPRK (J_FIRST_ASM_JOPCODE+10)
with_bits("CMPRK", _J_READ_R2+_J_READ_R3)
#define J_ACMPRR (J_FIRST_ASM_JOPCODE+11)
with_bits("CMPRR", _J_READ_R2+_J_READ_R3+_J_READ_R4)
#define J_ALDRK (J_FIRST_ASM_JOPCODE+12)
with_bits("LDRK", _ldr(MEM_B)+_J_READ_R2+_J_SET_R1)
#define J_ALDRR (J_FIRST_ASM_JOPCODE+13)
with_bits("LDRR", _ldr(MEM_B)+_J_READ_R3+_J_READ_R2+_J_SET_R1)
#define J_ALDRKW (J_FIRST_ASM_JOPCODE+14)
with_bits("LDRKW", _ldr(MEM_B)+_J_READ_R2+_J_SET_R2+_J_SET_R1)
#define J_ALDRRW (J_FIRST_ASM_JOPCODE+15)
with_bits("LDRRW", _ldr(MEM_B)+_J_READ_R3+_J_READ_R2+_J_SET_R2+_J_SET_R1)
#define J_ASTRK (J_FIRST_ASM_JOPCODE+16)
with_bits("STRK", _str(MEM_B)+_J_READ_R2+_J_READ_R1)
#define J_ASTRR (J_FIRST_ASM_JOPCODE+17)
with_bits("STRR", _str(MEM_B)+_J_READ_R3+_J_READ_R2+_J_READ_R1)
#define J_ASTRKW (J_FIRST_ASM_JOPCODE+18)
with_bits("STRKW", _str(MEM_B)+_J_READ_R2+_J_SET_R2+_J_READ_R1)
#define J_ASTRRW (J_FIRST_ASM_JOPCODE+19)
with_bits("STRRW", _str(MEM_B)+_J_READ_R3+_J_READ_R2+_J_SET_R2+_J_READ_R1)
#define J_LDM (J_FIRST_ASM_JOPCODE+20)
with_bits("LDM", _memr(MEM_I)+_J_READ_R1+_J_GAP2)
#define J_LDMW (J_FIRST_ASM_JOPCODE+21)
with_bits("LDMW", _memr(MEM_I)+_J_READ_R1+_J_SET_R1+_J_GAP2)
#define J_STM (J_FIRST_ASM_JOPCODE+22)
with_bits("STM", _memw(MEM_I)+_J_READ_R1+_J_GAP2)
#define J_STMW (J_FIRST_ASM_JOPCODE+23)
with_bits("STMW", _memw(MEM_I)+_J_READ_R1+_J_SET_R1+_J_GAP2)
#define J_MRS (J_FIRST_ASM_JOPCODE+24)
with_bits("MRS", _J_SET_R1+_J_GAP2)
#define J_MSR (J_FIRST_ASM_JOPCODE+25)
with_bits("MSR", _J_READ_R3+_J_GAP1+_J_GAP2)
#define J_MSK (J_FIRST_ASM_JOPCODE+26)
with_bits("MSK", _J_GAP1+_J_GAP2)
#define J_SWP (J_FIRST_ASM_JOPCODE+27)
with_bits("SWP", _memrw(MEM_I)+_J_SET_R1+_J_READ_R2+_J_READ_R3)
#define J_SWPB (J_FIRST_ASM_JOPCODE+28)
with_bits("SWPB", _memrw(MEM_B)+_J_SET_R1+_J_READ_R2+_J_READ_R3)
#define J_SWI (J_FIRST_ASM_JOPCODE+29)
with_bits("SWI", 0)
#define J_CDP (J_FIRST_ASM_JOPCODE+30)
with_bits("CDP", 0)
#define J_MRC (J_FIRST_ASM_JOPCODE+31)
with_bits("MRC", _J_SET_R1)
#define J_MCR (J_FIRST_ASM_JOPCODE+32)
with_bits("MCR", _J_READ_R1)
#define J_LDC (J_FIRST_ASM_JOPCODE+33)
with_bits("LDC", _memr(MEM_I)+_J_READ_R2)
#define J_LDCW (J_FIRST_ASM_JOPCODE+34)
with_bits("LDCW", _memr(MEM_I)+_J_READ_R2+_J_SET_R2)
#define J_STC (J_FIRST_ASM_JOPCODE+35)
with_bits("STC", _memw(MEM_I)+_J_READ_R2)
#define J_STCW (J_FIRST_ASM_JOPCODE+36)
with_bits("STCW", _memw(MEM_I)+_J_READ_R2+_J_SET_R2)
#define J_NULLOP (J_FIRST_ASM_JOPCODE+37)
with_bits("NOP", _J_GAP1+_J_GAP2)
#define J_BL (J_FIRST_ASM_JOPCODE+38)
with_bits("BL", 0)
#ifdef THUMB_INLINE_ASSEMBLER
/* YEAH - I know.... */
#define J_TEMP_JOPCODE (J_FIRST_ASM_JOPCODE+38)
#define J_ADCK (J_TEMP_JOPCODE+1L)
with_bits("ADCK", _J_READ_R2+_J_SET_R1)
#define J_ADCR (J_TEMP_JOPCODE+2L)
with_bits("ADCR", _J_READ_R2+_J_READ_R3+_J_SET_R1)
#define J_SBCK (J_TEMP_JOPCODE+3L)
with_bits("SBCK", _J_READ_R2+_J_SET_R1)
#define J_SBCR (J_TEMP_JOPCODE+4L)
with_bits("SBCR", _J_READ_R2+_J_READ_R3+_J_SET_R1)
#define J_RSCK (J_TEMP_JOPCODE+5L)
with_bits("RSCK", _J_READ_R2+_J_SET_R1)
#define J_RSCR (J_TEMP_JOPCODE+6L)
with_bits("RSCR", _J_READ_R2+_J_READ_R3+_J_SET_R1)
#define J_TSTK (J_TEMP_JOPCODE+7L)
with_bits("TSTK", _J_READ_R2)
#define J_TSTR (J_TEMP_JOPCODE+8L)
with_bits("TSTR", _J_READ_R2+_J_READ_R3)
#define J_BICK (J_TEMP_JOPCODE+9L)
with_bits("BICK", _J_READ_R2+_J_SET_R1)
#define J_BICR (J_TEMP_JOPCODE+10L)
with_bits("BICR", _J_READ_R2+_J_READ_R3+_J_SET_R1)
#define J_CMNK (J_TEMP_JOPCODE+11L)
with_bits("CMNK", _J_READ_R2)
#define J_CMNR (J_TEMP_JOPCODE+12L)
with_bits("CMNR", _J_READ_R2+_J_READ_R3)
#define J_MVNK (J_TEMP_JOPCODE+13L)
with_bits("MVNK", _J_READ_R2)
#define J_MVNR (J_TEMP_JOPCODE+14L)
with_bits("MVNR", _J_READ_R2+_J_READ_R3)
#define J_LAST_ASM_JOPCODE (J_TEMP_JOPCODE+14)
#define J_LAST_JOPCODE J_LAST_ASM_JOPCODE
#else
#define J_LAST_ASM_JOPCODE (J_FIRST_ASM_JOPCODE+38)
#define J_LAST_JOPCODE J_LAST_ASM_JOPCODE
#endif
#endif /* ARM_INLINE_ASSEMBLER */
#ifdef DEFINE_JOPTABLE
0 };
#endif
#define J_POPM @@@ Please see "mip/jopcode.h".
/* J_POPM has been superceded on all targets. Its functionality */
/* is provided by use of other J_OPCODE's and the new J_MOVDIR. */
/* J_MOVDIR is unused if TARGET_FP_ARGS_CALLSTD2, but otherwise */
/* back-ends may naively treat J_MOVDIR r1,r2,r3 as PUSHD r3 followed */
/* by dropping into the code for POPM {r1,r2} (r2==r1+1 assumable). */
/*************************************/
/* end of emumeration of all opcodes */
/*************************************/
typedef uint32 J_OPCODE; /* really ENUMERATED_OPCODE but ensure 32 bits */
/* n.b Q_UBIT is the same as J_UNSIGNED */
#define Q_MASK (~(int32)0x07ffffff)
#define Q_UBIT ((int32)0x08000000) /* for test of signed/unsigned CMP */
#define Q_NEGATE(x) ((x)^Q_NOT)
#define Q_issame(x,y) (((x)|Q_UBIT) == ((y)|Q_UBIT))
/* The next macro may only be applied to Q_GE and Q_LT. */
#define Q_tocmpz(x) ((x) ^ (Q_GE^Q_PL)) /* also (Q_LT^Q^MI) */
#define Q_CondPair(x,y) \
(((uint32)(x)>(uint32)(y)) ? ((uint32)(x)>>27)|((uint32)(y)>>22) :\
((uint32)(x)>>22)|((uint32)(y)>>27))
/* The following idea of conditions are machine independent - so any new */
/* code (e.g. Q_CC) should have a different number even if they have the */
/* same effect on your favorite machine - just as Q_HS and Q_GE differ even */
/* though they have the same effect on the 370 (the comparison differs). */
#define Q_AL ((int32)0x00000000)
#define Q_NOT ((int32)0x10000000) /* obsolete */
#define Q_GT ((int32)0x20000000)
#define Q_LE ((int32)0x30000000)
#define Q_GE ((int32)0x40000000)
#define Q_LT ((int32)0x50000000)
#define Q_HI ((int32)0x60000000|Q_UBIT)
#define Q_LS ((int32)0x70000000|Q_UBIT)
#define Q_VS ((int32)0x80000000)
#define Q_VC ((int32)0x90000000)
#define Q_PL ((int32)0xa0000000)
#define Q_MI ((int32)0xb0000000)
#define Q_HS ((int32)0xc0000000|Q_UBIT)
#define Q_LO ((int32)0xd0000000|Q_UBIT)
#define Q_EQ ((int32)0xe0000000)
#define Q_NE ((int32)0xf0000000)
/* The following are added by AM to check conversion to new style J_CMP */
/* Q_UEQ and Q_UNE are unsigned equality tests. May be useful one day? */
#define Q_UEQ (Q_EQ|Q_UBIT)
#define Q_UNE (Q_NE|Q_UBIT)
/* Special unknown condition, used in CMPs only, for 3 way tests
where the exact condition is unknown, except for the signedness.
*/
#define Q_UKN (Q_NOT)
/* Special undefined condition, used in CMPs only, after merging
signed and unsigned tests where the result isn't signed nor unsigned.
*/
#define Q_UNDEF (Q_AL)
#define Q_RealMask(m) ((m) != Q_UNDEF && (m) != Q_UKN)
#ifndef JOPCODEDEF_ONLY
#define is_block_label(lab) ((uint32)(lab) < (uint32)NOTALAB) /* Nasty HACK! */
char *condition_name(uint32 mask);
void print_jopcode(const Icode *const ic);
void print_jopcode_1(const Icode *const ic);
void jopprint_opname(J_OPCODE o);
void jopprint_op3(J_OPCODE op, VRegInt r2, VRegInt r3);
void print_xjopcode(const Icode *const ic, char *fmt, ...);
void flowgraf_printblock(BlockHead *p, bool deadbits);
void flowgraf_print(const char *mess, bool deadbits);
void pr_bindlist(BindList *p);
bool Q_implies(int32 cond1, int32 cond2);
#endif
#endif
/* End of jopcode.h */
|
stardot/ncc | mip/misc.c | /*
* misc.c: Misc features for the Norcroft C compiler
* Copyright (C) Codemist Ltd, 1988-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 70
* Checkin $Date$
* Revising $Author$
*/
/* Find cc_err below for discussion on error messages, and errors.h */
/*
* IDJ: 06-Jun-94: added code to support Acorn's DDE throwback facility:
* all errors result in a SWI to DDEUtils module to send errors back
* to the editor. All guarded by #ifdef FOR_ACORN.
*
*/
#include <stddef.h>
#ifdef __STDC__
# include <stdlib.h>
# include <stdarg.h>
# include <string.h>
#else
# include <varargs.h>
# include <strings.h>
#endif
#include <ctype.h>
#include "globals.h"
#ifndef _defs_LOADED
# include "defs.h"
#endif
#include "store.h"
#include "compiler.h"
#include "aeops.h"
#include "aetree.h"
#include "lex.h" /* for curlex... */
#include "bind.h" /* for isgensym... */
#include "util.h"
#ifdef CPLUSPLUS
# include "unmangle.h"
#else
# define unmangle_with_class(name,b,c,d,e) name
# define unmangle_class(name,b,c) name
#endif
#include "msg.h" /* NLS */
#include "backchat.h"
#ifdef FOR_ACORN
#include "dde.h"
#include "dem.h" /* cfront name demangling */
#endif
#define listing() (listingstream != NULL)
#ifndef NLS
# undef msg_sprintf
# define msg_sprintf _sprintf
# undef msg_vfprintf
# define msg_vfprintf _vfprintf
# define DEFINE_MSG_COMPRESSION_TABLE 1
# include "errors.h"
# undef DEFINE_MSG_COMPRESSION_TABLE
#else
# include "errors.h" /* Could set COMPRESSED_MESSAGES */
# if defined(COMPRESSED_MESSAGES)
# undef COMPRESSED_MESSAGES /* ... which isn't true for NLS ... */
# endif
#endif
long sysdebugmask;
int32 suppress, feature;
int32 localcg_debugcount;
FILE *listingstream;
FILE *errors;
#ifdef PASCAL /*ECN*/
int32 rtcheck;
#endif
/* The following routines are generic list-manipulation routines. */
/* They can only be implemented by a hack in C, but in C++ they can */
/* be implemented by basing all list-like classes on 'List'. */
/* In C, a struct S with a 'cdr' pointer at offset 0 can be reversed */
/* destructively by (e.g.) (S *)dreverse((List *)whatever). */
int32 length(List const *l)
{
int32 i = 0;
for (; l != NULL; l = cdr_(l)) i++;
return i;
}
List *dreverse(List *x) /* return reverse(x) by destroying x. */
{ List *y = 0, *t;
while (x != 0)
{ t = cdr_(x);
cdr_(x) = y;
y = x;
x = t;
}
return y;
}
/* Similar to above except for cdr_ */
Binder *dreverse_binder(Binder *x)
{ Binder *y = 0, *t;
while (x != 0)
{ t = bindcdr_(x);
bindcdr_(x) = y;
y = x;
x = t;
}
return y;
}
List *nconc(List *x, List *y) /* return append(x,y) by destroying x. */
{ if (x == 0) return y;
else
{ List *t, *a = x;
while ((t = cdr_(x)) != 0) x = t;
cdr_(x) = y;
return a;
}
}
int32 max(int32 a, int32 b)
{
return (a>b ? a : b);
}
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 logbase2(int32 n)
{
/* n known to be a power of two */
int32 r = 0;
while ((n & 1)==0) n >>= 1, r++;
return r;
}
/* 'real' in the following represents generic float/double/long double */
/* real_of_string() uses GLOBAL store for its value. Is this reasonable? */
/* Special case flag==0 for real_to_real (and sem.c/fltrep_from_widest()) */
FloatCon *real_of_string(const char *s, int32 flag)
{ int32 wsize = offsetof(FloatCon,floatstr[0]) + padstrlen(strlen(s));
FloatCon *x = (FloatCon *) GlobAlloc(SU_Const, wsize);
/* real_of_string is now also used to initialise fc_two_32. */
x->h0 = s_floatcon;
strcpy(x->floatstr, s);
if (flag)
{ int failed;
x->floatlen = flag; /* the bitoftype_ / curlex.a2.flag pun!!! */
/* Currently sizeof_double==sizeof_ldble is assumed. */
failed = fltrep_stod(s, &x->floatbin.db, NULL);
if (failed > flt_ok) flt_report_error(failed);
if (sizeof_double == 4 ||
sizeof_float < sizeof_double && (flag & bitoftype_(s_short)))
/* so we only need to narrow once */
fltrep_narrow_round(&x->floatbin.db, &x->floatbin.fb);
}
return x;
}
Int64Con *mkint64const(SET_BITMAP m, int64 const *i64) {
Int64Con *e = (Int64Con *)GlobAlloc(SU_Const, sizeof(Int64Con));
h0_(e) = s_int64con;
e->typespec = m;
e->bin.i = *i64;
return e;
}
/* the next two routines do not really belong here, but they do manipulate
the same structure as make_floating */
#ifdef FORTRAN
/* This code was previously used in flt->flt casts only, now exploits */
/* the more general code around sem.c/trycastreduce(). */
/* Check f77/pascal don't use. */
FloatCon *real_to_real(FloatCon *fc, SET_BITMAP m)
{ FloatCon *x = real_of_string(fc->floatstr, 0);
/* N.B. the last line just copies the floating point number text
and so this text does not reflect narrowing and re-widening.
The string is only provided for the ASM output not AOF, and so
the inaccuracy in it is not critical: the associated binary FP
value will be kept exactly as it should be and that is what
matters. */
x->floatlen = m;
memcpy(&x->floatbin, &fc->floatbin, sizeof(x->floatbin));
/* long double = double in this implementation so widen/narrow is easy: */
if (sizeof_float < sizeof_double)
{ SET_BITMAP mfc = fc->floatlen;
if ((m & bitoftype_(s_short)) && !(mfc & bitoftype_(s_short)))
fltrep_narrow(&fc->floatbin.db, &x->floatbin.fb);
else if (!(m & bitoftype_(s_short)) && (mfc & bitoftype_(s_short)))
fltrep_widen(&fc->floatbin.fb, &x->floatbin.db);
}
return x;
}
#endif
FloatCon *int_to_real(int32 n, int32 u, SET_BITMAP m)
{ char s[20];
/* there must be better ways - e.g. fltrep_itod in fltrep.c ?? */
/* The use of sprintf/real_of_string ensures that the floatcon that */
/* is generated has a sensible string attached to it so leave this */
/* code alone - it works quite well enough. */
if (u) _sprintf(s, "%lu.0", (long)n);
else _sprintf(s, "%ld.0", (long)n);
return real_of_string(s,m);
}
/* error message routines...
0) cc_msg: Internal compiler messages, enabled by DEBUG_xxx flags.
1) cc_warn: perfectly legal, but curious, C program (e.g. = for ==),
or 'undefined at run time' (e.g. printf("%f", 1);).
2) Offences againgst ANSI draft (Return normally).
2') cc_pccwarn: Recoverable, only a warning if in pcc mode.
2a) cc_rerr: Recoverable error without loss of code (e.g. int *x=1;)
Code 'works' -- compiled as on UNIX.
2b) cc_err: Code probably lost, e.g. syntax error, or
{ struct {int a;}*x; f(x->b); }
Sets 'compilation failed' flag.
3) cc_extension: ditto, but allows controlled extension use.
3) cc_fatalerr: A cause for giving up compilation (e.g. out of store/
too many errors). NEVER returns.
4) syserr: Internal consistency error. Exits with legs in air,
unless debugging (syserr_behaviour) flag set.
N.B. May return for system debuggers only.
Note all messages (except class 0 and 4) must now be in errors.h (q.v.).
*/
int32 warncount=0, recovercount=0, errorcount=0;
/* The following 2 vars count suppressed errors/warns. They needn't */
/* be printed on systems where this would be unusual. */
int32 xwarncount=0;
int32 syserr_behaviour = 0;
#ifndef NO_LISTING_OUTPUT
/* The following variables should only be ref'd if listingstream != NULL */
static char *errsaves;
static uint32 errsavep, errsaven;
#endif
static char *errbuf;
static uint32 errbufp, errbufn;
/* VERY HACKED - INTEGRATE THESE CHANGES */
static struct uncompression_record
{
char *pointer;
char compressed;
unsigned char height;
#ifdef COMPRESSED_MESSAGES
char stack[MSGSTACKDEPTH];
#endif
} errmsg;
#ifdef COMPRESSED_MESSAGES
static void start_string_char(char *s) /* Compressed but still a string */
{
errmsg.height = 0;
errmsg.pointer = s;
errmsg.compressed = 1;
}
static int fetch_string_char(void)
/*
* This is the same code (pretty well) as pp_fetch_string_char() in
* "pp.c", but having a separate version here keeps the module structure
* of the compiler cleaner and only spends about 150 bytes. It also
* reserves the option of using different compression techniques for
* error messages and built-in headers.
*/
{
int c, k;
if (errmsg.height == 0) c = *errmsg.pointer++;
else c = errmsg.stack[--errmsg.height];
for (;;)
{ c &= 0xff;
k = ecompression_info[c];
if (k == c || errmsg.compressed == 0) return c;
/*
* The genhdrs utility establishes the greatest possible depth needed in
* this stack and arranges to define MSGTACKDEPTH suitably - thus no
* run-time check for stack overflow is needed.
*/
errmsg.stack[errmsg.height++] = k;
c = k >> 8;
}
}
static void unfetch_string_char(int ch)
{
errmsg.stack[errmsg.height++] = ch;
}
#else
static void start_string_char(char *s)
{
errmsg.pointer = s;
}
static int fetch_string_char(void)
{
return *errmsg.pointer++;
}
static void unfetch_string_char(int ch)
{
errmsg.pointer--;
IGNORE(ch);
}
#endif
static void sstart_string_char(char *s)
{
errmsg.height = 0;
errmsg.pointer = s;
errmsg.compressed = 0;
}
static void snprintf(char *b, msg_t errcode, ...)
{
va_list a;
#ifndef NLS
char s[80];
char *p = s;
start_string_char(msg_lookup(errcode));
/*
* Convert error code into a string so that it can be printed. I expect
* all strings used to be less than 80 characters long.
*/
while ((*p++ = fetch_string_char()) != 0) continue;
#endif
va_start(a, errcode);
#ifdef NLS
msg_vsprintf(b, errcode, a);
#else
vsprintf(b, s, a);
#endif
va_end(a);
}
static void SendErrorReport(backchat_Diagnostic *bd) {
if (errors == NULL)
backchat.send(backchat.handle, BC_DIAGMSG, bd);
else {
char const *msg = bd->msgtext;
unsigned line = bd->lineno;
char b[256];
cc_announce_error(b, bd->severity, bd->filename, line);
fputs(b, errors);
fputs(msg, errors);
}
}
void summarise(void)
{
char b[FILENAME_MAX+64]; /*mls xdevt thread 1682
*Space for message and filename, we hope.
*/
if (warncount != 0 || recovercount != 0 || errorcount != 0
|| (feature & FEATURE_VERBOSE))
{ /* The NLS here is very minimal. We only special case 0 or 1 errors
* (sufficient for most Western European languages). Generalising
* this to any language would require a reworking of the NLS system
* to allow some form of parameterised message. (bleugh)
*/
char *s = b;
#ifndef COMPILING_ON_MPW
switch (warncount) {
case 0: snprintf(s, misc_message_sum1_zero,curlex.fl.f); break;
case 1: snprintf(s, misc_message_sum1_sing,curlex.fl.f); break;
default:snprintf(s, misc_message_sum1(curlex.fl.f, (long)warncount)); break;
}
#else
switch (warncount) {
case 0: snprintf(s, misc_message_sum1_zero_mpw,curlex.fl.f); break;
case 1: snprintf(s, misc_message_sum1_sing_mpw,curlex.fl.f); break;
default:snprintf(s, misc_message_sum1_mpw(curlex.fl.f, (long)warncount)); break;
}
#endif
s += strlen(s);
if (xwarncount && !(feature & FEATURE_PCC)) {
snprintf(s, misc_message_sum2, (long)xwarncount);
s += strlen(s);
}
switch (recovercount) {
case 0: snprintf(s, misc_message_sum3_zero); break;
case 1: snprintf(s, misc_message_sum3_sing); break;
default: snprintf(s, misc_message_sum3,(long)recovercount); break;
}
s += strlen(s);
switch (errorcount) {
case 0: snprintf(s, misc_message_sum5_zero); break;
case 1: snprintf(s, misc_message_sum5_sing); break;
default: snprintf(s, misc_message_sum5,(long)errorcount); break;
}
{ backchat_Diagnostic bd;
bd.toolname = NULL;
bd.filename = NULL;
bd.msgtext = b;
bd.severity = BC_SEVERITY_INFO;
bd.column = (unsigned short)-1;
bd.lineno = (unsigned)-1;
bd.filepos = -1;
SendErrorReport(&bd);
}
}
}
static void check_error_buffer(size_t len)
{ /* don't rely on ANSI realloc(NULL, ..) semantics */
if (errbuf == NULL)
errbuf = (char *)PermAlloc((errbufn = 1024));
else if (errbufp + len > errbufn) {
char *old = errbuf;
errbuf = (char *)PermAlloc((errbufn += 1024));
memcpy(errbuf, old, errbufp);
}
}
void cc_announce_error(char *s, int severity, char const *file, int32 line)
{
const char *reason = "";
if (severity != BC_SEVERITY_NONE && severity != BC_SEVERITY_INFO)
{ msg_t msg_severity =
severity == BC_SEVERITY_WARN ? misc_message_warning :
severity == BC_SEVERITY_ERROR ? misc_message_error :
severity == BC_SEVERITY_SERIOUS ? misc_message_serious :
misc_message_fatal;
reason = msg_lookup(msg_severity);
}
if (file == NULL) {
snprintf(s, misc_message_nofile(reason));
} else if (line == -1) {
#ifndef TARGET_IS_UNIX
# ifndef COMPILING_ON_MPW
snprintf(s, misc_message_nolineno(file, reason));
# else
snprintf(s, misc_message_nolineno_mpw(file, reason));
# endif
#else
snprintf(s, misc_message_nolineno_unix(file, reason));
#endif
} else {
#ifndef TARGET_IS_UNIX
# ifndef COMPILING_ON_MPW
snprintf(s, misc_message_lineno(file, (long)line, reason));
# else
snprintf(s, misc_message_lineno_mpw(file, (long)line, reason));
# endif
#else
snprintf(s, misc_message_lineno_unix(file, (long)line, reason));
#endif
}
}
void listing_diagnostics(void)
{
#ifndef NO_LISTING_OUTPUT
if (listingstream && errsavep != 0)
{ fprintf(listingstream, "%s", errsaves);
errsavep = 0;
}
#endif
}
static void errprintf(char const *s, ...)
{
/* Takes a format, not a tag */
/* It has previously been checked that errbuf has enough space to contain */
/* the data to be written */
va_list a;
va_start(a, s);
vsprintf(&errbuf[errbufp], s, a);
errbufp += strlen(&errbuf[errbufp]);
}
static void qprints(char const *s, bool quoted)
{ /* used to print symbols (quoted) or syntactic categories */
if (!quoted || (s[0] == '<' && isalpha(s[1]))) errprintf("%s", s);
else errprintf("'%s'", s);
}
/* Export for more general use soon (e.g. asm.c). */
static void esccharname(char *s, int ctarget) /* s shall be char[>=5] */
{ int c;
switch (c = char_untranslation(ctarget))
{
default:
if (isprint(c)) s[0] = c, s[1] = 0;
else _sprintf(s, "\\x%.2x", ctarget);
return;
case '\\':
case '\'':
case '\"': break;
case '\a': c = 'a'; break;
case '\b': c = 'b'; break;
case '\f': c = 'f'; break;
case '\n': c = 'n'; break;
case '\r': c = 'r'; break;
case '\t': c = 't'; break;
case '\v': c = 'v'; break;
case 0: c = '0'; break;
}
s[0] = '\\', s[1] = c, s[2] = 0;
}
static void escstring(char *d, int32 dl, char const *s, int32 sl)
{ /* Used to print strings escaping chars as needed. */
/* Note that s==DUFF_ADDR is OK if sl==0. */
int32 si, di;
for (si = di = 0; si<sl && di<dl-8; si++)
{ esccharname(&d[di], s[si]);
di += strlen(&d[di]);
}
if (si<sl) strcpy(&d[di], "...");
}
/* separate functions for names of types and of storage classes,
since they now use distinct bitmaps.
*/
static const char *xstgbit_name(SET_BITMAP stg)
{ AEop s;
if (stg & bitofstg_(s_weak))
stg &= ~bitofstg_(s_extern);
for (s = s_auto; bitofstg_(s) & STGBITS; s++)
if (stg & bitofstg_(s)) return sym_name_table[s];
return "???";
}
static const char *xtypebit_name(SET_BITMAP typespec)
{ AEop s;
if (typespec & (bitoftype_(s_long)|bitoftype_(s_short)))
{ if (typespec & bitoftype_(s_int))
{ /* don't need to worry about bool since s_bool < s_int */
if (int_islonglong_(typespec))
typespec ^= ts_longlong^bitoftype_(s_longlong);
else
typespec &= ~bitoftype_(s_int); /* leave just short or long or longlong */
}
else if (typespec & bitoftype_(s_double))
{ if (typespec & bitoftype_(s_short))
typespec ^= ts_float^bitoftype_(s_float);
else
return msg_lookup(errname_longdouble); /* there is no s_longdouble */
}
}
for (s = s_bool; s < s_bool + NUM_OF_TYPES; s++)
if (typespec & bitoftype_(s)) return sym_name_table[s];
return "???";
}
static char const *xtype_name(char *v, TypeExpr const *e)
{ switch (h0_(e))
{ case s_typespec:
{ SET_BITMAP m = typespecmap_(e);
if (m & ENUMORCLASSBITS) {
TagBinder *tb = typespectagbind_(e);
if (isgensym(tagbindsym_(tb))
&& tb->typedefname != NULL && !isgensym(tb->typedefname))
return symname_(tb->typedefname);
sprintf(v, "%s %s", xtypebit_name(m),
symname_(tagbindsym_(tb)));
return v;
}
if (m & (bitoftype_(s_signed)|bitoftype_(s_unsigned))) {
sprintf(v, "%s %s", xtypebit_name(m & (bitoftype_(s_signed)|bitoftype_(s_unsigned))),
xtypebit_name(m & ~(bitoftype_(s_signed)|bitoftype_(s_unsigned))));
return v;
}
return xtypebit_name(m);
}
case t_ovld: return "<overloaded function>";
case t_fnap: return "<function>";
case t_content: return "<pointer>";
case t_subscript: return "<array>";
case t_ref: return "<reference>";
case t_unknown: return "<typevar>";
default: return "???";
}
}
#ifdef FOR_ACORN
#ifndef PASCAL
#ifndef FORTRAN
int cplusplus_flag;
#define input_from_cfront (cplusplus_flag != 0)
#endif
#endif
#endif
#define printsym(format, sym) \
printsym_with_class((format), (sym), NULL)
static void printsym_with_class(char const *format, Symstr const *sym,
TagBinder const *parent)
{ char const *name = sym == NULL ? "<no name>" : symname_(sym);
#ifdef input_from_cfront
if (input_from_cfront)
{ char sbuf[MAXDBUF];
demangle(name, sbuf);
errprintf(format, sbuf);
}
#else
if (LanguageIsCPlusPlus)
{ const char *classname = parent != NULL ? symname_(tagbindsym_(parent)) : NULL;
int classlen = classname != NULL ? strlen(classname) : 0;
char buf[256];
name = unmangle_with_class(name, classname, classlen, buf, sizeof(buf));
}
#endif
check_error_buffer(strlen(name));
errprintf(format, name);
}
static void printclasssym(char const *format, Symstr const *sym)
{ char const *name = sym == NULL ? "<no name>" : symname_(sym);
if (LanguageIsCPlusPlus)
{ char buf[256];
name = unmangle_class(name, buf, sizeof(buf));
}
check_error_buffer(strlen(name));
errprintf(format, name);
}
static void printparents(TagBinder const *b)
{ if (b == 0) return;
printparents(b->tagparent);
if (!isgensym(tagbindsym_(b))) {
check_error_buffer(strlen(symname_(tagbindsym_(b))));
errprintf("%s::", symname_(tagbindsym_(b)));
}
}
static void printbinder(Binder const *b, bool quote)
{ const TagBinder *parent = NULL;
if (b == 0) { errprintf("<nullbinder>"); return; }
if (quote)
errprintf("'");
if (h0_(b) == s_binder || h0_(b) == s_member) {
parent = bindparent_(b); /* for C, always NULL */
if (parent != NULL)
printparents(parent->tagparent);
printsym_with_class("%s", bindsym_(b), parent);
} else if (h0_(b) == s_tagbind) {
printparents(((TagBinder const *)b)->tagparent);
printclasssym("%s", bindsym_(b));
}
if (quote)
errprintf("'");
}
#ifdef NLS
/* This is a version of va2type that supports the Compiler's '$' specifiers.
* $<n>$<f> is supported, but never $<n>$<width etc.><f>
*/
static nls_type *va2type(const char *format,va_list args)
{
static nls_type result[9];
char fmt[9],type[9];
int i,arg;
const char *t,*s;
for (i=0;i<9;i++) type[i]='\0';
i=0;
t=strchr(format,'%'); s=strchr(format,'$');
while (t || s) {
if (s==NULL || (t && t<s)) {
t++;
if (*t!='\0' && *t!='%') {
int arg=-1;
if (t[1]=='$' && *t!='0' && isdigit(*t)) {
arg=*t-'1';
t+=2; /* <n>$ */
}
while (*t=='-' || *t=='+' || *t==' ' || *t=='#') t++;
if (*t=='*') {
t++;
if (t[1]=='$' && *t!='0' && isdigit(*t)) {
type[*t-'1']='*';
t+=2; /* *<n>$ */
} else type[i++]='*';
} else
while (isdigit(*t)) t++;
if (*t=='.') {
t++;
if (*t=='*') {
t++;
if (t[1]=='$' && *t!='0' && isdigit(*t)) {
type[*t-'1']='*';
t+=2; /* *<n>$ */
} else type[i++]='*';
} else
while (isdigit(*t)) t++;
}
/* t now points at the format argument, or a preceeding 'l' */
if (arg<0) arg=i++;
if (*t=='l') type[arg]=*t++; /* 'l' */
else type[arg]='%';
fmt[arg]=*t;
} else if (*t=='%') {
t++;
}
t=strchr(t+1,'%'); /* Goto next percent */
} else { /* s<t */
int j=i;
s++;
if (isdigit(*s) && *s!='0' && s[1]=='$') {
arg=s[0]-'1';
s+=2; /* <n>$ */
} else {
arg=i++; /* Doesn't allow $*<f> etc. */
}
if (s[0] == '#') ++s; /* Allow '$#<f>' */
switch (*s) {
case '\0': break;
case '$': case 'l': /* $l takes no argument */
default: /* really an error */
s++; i=j;
break;
case 's': case 'p': case 'r': case 'e':
case 'b': case 'c': case 't': case 'g': case 'k':
case 'm':
fmt[arg]=*s;
type[arg]='$';
break;
}
s=strchr(s+1,'$');
}
}
for (i=0;type[i] && i<9;i++) {
switch (type[i]) {
case 'l': /* long % */
switch (fmt[i]) {
case 'd': case 'i': case 'o': case 'u':
case 'x': case 'X':
result[i].cardinal=va_arg(args,long);
break;
case 'p': case 's': case 'n':
result[i].pointer=va_arg(args,void *);
break;
case 'f': case 'e': case 'E': case 'g':
case 'G':
result[i].floating=va_arg(args,double);
break;
case 'c':
result[i].cardinal=va_arg(args,int);
break;
}
break;
case '%':
switch (fmt[i]) {
case 'd': case 'i': case 'o': case 'u':
case 'x': case 'X': case 'c':
result[i].cardinal=va_arg(args,int);
break;
case 'p': case 's': case 'n':
result[i].pointer=va_arg(args,void *);
break;
case 'f': case 'e': case 'E': case 'g':
case 'G':
result[i].floating=va_arg(args,double);
break;
}
break;
case '$':
switch (fmt[i]) {
case 's':
result[i].cardinal=va_arg(args,AEop);
break;
case 'g': case 'm':
result[i].cardinal=va_arg(args,SET_BITMAP);
break;
case 'p': case 'r': case 'e': case 'b':
case 'c': case 't': case 'k':
result[i].pointer=va_arg(args,void *);
break;
}
break;
case '*':
result[i].cardinal=va_arg(args,int);
break;
}
}
return result;
}
#endif
struct FnApContext
{
struct FnApContext *cdr;
const Binder* b; /* the function */
int n; /* the argument number; 0 means 'this' */
};
static struct FnApContext* fnap_context;
void push_fnap_context(Binder* fn) /* NULL fn ok */
{
fnap_context = (struct FnApContext*)syn_list3(fnap_context, fn, 0);
}
void set_fnap_arg(int i)
{
if (fnap_context == NULL)
syserr("no fnap context");
else
fnap_context->n = i;
}
void pop_fnap_context(void)
{
if (fnap_context == NULL)
syserr("no fnap context");
fnap_context = (struct FnApContext*)discard3(fnap_context);
}
static void ssuperrprintf(va_list a, bool newlineterminate);
/* like cc_msg but takes a compressed string and can be used recursively
this is just about cc_msg_lookup and they should be unified */
static void cc_printf(msg_t errorcode, ...)
{
va_list a;
struct uncompression_record save = errmsg;
va_start(a, errorcode);
start_string_char(msg_lookup(errorcode));
ssuperrprintf(a, NO);
va_end(a);
errmsg = save;
}
static void ssuperrprintf(va_list a, bool newlineterminate)
{
/* This routine behaves like printf but also recognises escape chars of
* the form $<char> and acts upon them. It writes its output to
* stderr, and if listing-file!= NULL also to a buffer associated with
* the listing file.
*/
#ifdef NLS
nls_type *m=va2type(errmsg.pointer,a);
int cur_arg_n=0;
#endif
const TagBinder *parent = NULL;
for (;;)
{
#define no_arg_type 0
#define int_arg_type 2
#define ptr_arg_type 4
#define no_qualifier 0
#define long_qualifier 8
#define star_qualifier 16 /* indirection for field width (yuk) */
int arg_type = no_arg_type, w;
void *pnt;
long l_int;
#ifdef NLS
nls_type *cur_arg=NULL,*star_arg;
#endif
int ch;
char v[80+12]; /* Buffer for segment of the format string */
int n = 0; /* 0..91 */
/* Characters are moved to the buffer up as far as a $ or % escape */
while ((ch = fetch_string_char()) != 0 &&
ch != '$' &&
n != 80 && /* also break at char 80... */
ch != '%')
v[n++] = ch;
if (ch == '%')
{
/* It is assumed here that there will never be more than 11 characters in */
/* an escape sequence (e.g. %-20.20l#x has 10 chars in it and seems a */
/* bit excessive. The limit is because of overflow in the buffer v[] */
v[n++] = ch;
#ifdef NLS
if (isdigit(*errmsg.pointer) &&
errmsg.pointer[1]=='$') { /* nl_ extension */
cur_arg=&m[fetch_string_char()-'1'];
(void)fetch_string_char();
}
#endif
#ifdef NLS
# define ARG(TYPE,X) (TYPE)((cur_arg ? cur_arg : &m[cur_arg_n++])-> ## X)
#else
# define ARG(TYPE,X) va_arg(a,TYPE)
#endif
for (;;)
{ ch = fetch_string_char();
if (n == 91) syserr(syserr_bad_fmt_dir);
v[n++] = ch;
switch (safe_tolower(ch))
{
case 'l':
arg_type |= long_qualifier;
continue;
case '*':
arg_type |= star_qualifier;
#ifdef NLS
if (isdigit(*errmsg.pointer) &&
errmsg.pointer[1]=='$') {
star_arg=&m[fetch_string_char()-'1'];
(void)fetch_string_char();
} else {
star_arg=&m[cur_arg_n++];
}
#endif
continue;
/* Note that 'h' indicates that an int should be treated as a */
/* short value, but the va_arg() call still fetches an int. */
default: continue;
case '%': break;
case 'c': case 'd': case 'i': case 'o':
case 'u': case 'x':
arg_type |= int_arg_type;
break;
case 'p': case 's': case 'k':
arg_type |= ptr_arg_type;
break;
case 'e': case 'f': case 'g': /* disallow floating point here */
case 'n': case 0:
syserr(syserr_bad_fmt_dir);
}
break;
}
ch=fetch_string_char();
}
v[n] = 0; /* terminate format string */
check_error_buffer(200);
switch (arg_type)
{
default:
case no_arg_type:
errprintf("%s", v);
break;
case ptr_arg_type:
pnt = ARG(void *,pointer);
errprintf(v, pnt);
break;
/* At present I am only supporting '*' qualifiers for use with string */
/* printing (i.e. %.*s) - at the time of writing this code there is just */
/* one such format in errors.h - I might like to get rid of it by */
/* achieving the same result some other way so that this extra mess here */
/* wrt format decoding could be discarded. ACN */
case ptr_arg_type + star_qualifier:
#ifdef NLS
w = star_arg->cardinal;
#else
w = ARG(int,cardinal);
#endif
pnt = ARG(void *,pointer);
errprintf(v, w, pnt);
break;
case int_arg_type + long_qualifier:
l_int = ARG(long,cardinal);
errprintf(v, l_int);
break;
case int_arg_type:
w = ARG(int,cardinal);
errprintf(v, w);
break;
}
if (ch == 0)
{
if (syserr_behaviour==3) abort();
if (newlineterminate) errprintf("\n");
return; /* Message now complete */
}
if (ch != '$') unfetch_string_char(ch);
else {
bool alt = false;
ch=fetch_string_char();
#ifdef NLS
if (isdigit(ch) && *errmsg.pointer=='$') {
cur_arg=&m[ch-'1'];
(void)fetch_string_char();
ch = fetch_string_char();
}
#endif
if (ch == '#')
{ alt = true;
ch = fetch_string_char();
}
switch (ch) {
case 0:
if (newlineterminate) errprintf("\n");
return;
case 's': /* AEop */
{ AEop op = ARG(AEop,cardinal);
if (op == s_fnap && fnap_context != NULL)
{ if (fnap_context->n == 0)
{ if (fnap_context->b == 0)
cc_printf(misc_msg_fnarg_this_fnap);
else
cc_printf(misc_msg_fnarg_this_fnname, fnap_context->b);
}
else
{ if (fnap_context->b == 0)
cc_printf(misc_msg_fnarg_fnap, fnap_context->n);
else
cc_printf(misc_msg_fnarg_fnname, fnap_context->n, fnap_context->b);
}
}
else
qprints(sym_name_table[op & 255], !alt);
}
break;
case 'l': /* current lexeme -- curlex */
case 'k': /* supplied lexeme -- SymInfo* */
{
SymInfo *p = (ch == 'l') ? &curlex :
ARG(SymInfo *,pointer);
if (!alt)
errprintf("'");
switch (p->sym & 255)
{ case s_integer:
errprintf("%ld", (long)p->a1.i); break;
case s_floatcon:
errprintf("%s", p->a1.fc->floatstr); break;
case s_identifier:
case s_pseudoid:
printsym("%s", p->a1.sv);
break;
case s_string:
{ char e[80];
escstring(e, 20, p->a1.s, p->a2.len);
errprintf("\"%s\"", e);
}
break;
default:
qprints(sym_name_table[p->sym & 255], false);
break;
}
if (!alt)
errprintf("'");
}
break;
case 'p': /* set parent for $r */
parent = ARG(const TagBinder *,pointer);
break;
case 'r': /* Symstr* */
{ Symstr *r = ARG(Symstr *,pointer);
if (r==0 || h0_(r) != s_identifier)
{ if (r == 0) errprintf("<missing>");
else errprintf("<oddity>");
}
else
{ if (ch == 'r' && !alt)
errprintf("'");
if (parent != NULL)
printparents(parent->tagparent);
printsym_with_class(ch == 'r' && !alt ? "%s'" : "%s",
r, parent);
}
}
break;
case 'e': /* Expr* */
{ Expr *e = ARG(Expr *,pointer);
while (h0_(e) == s_invisible) e = arg1_(e);
if (h0_(e) != s_binder && h0_(e) != s_member)
{ AEop op = h0_(e);
if (!alt)
errprintf("'");
if (op == s_string
#ifdef EXTENSION_UNSIGNED_STRINGS
|| op == s_ustring || op == s_string
#endif
)
{ char s[80];
StringSegList *z = ((String *)e)->strseg;
escstring(s, 60, z->strsegbase, z->strseglen);
errprintf("'\"%s\"'", s);
}
else
{ const char *opname = sym_name_table[op & 255];
if (isdiad_(op))
errprintf("<expr> %s <expr>", opname);
else if (op >= s_binder)
errprintf("%s<expr>", opname);
else
errprintf("%s", opname);
}
if (!alt)
errprintf("'");
}
else
printbinder((Binder *)e, !alt);
}
break;
case 'b': /* ordinary binder, but works for tag binder too. */
printbinder(ARG(Binder *,pointer), !alt);
break;
case 'c': /* tag binder -- this will simplify many err msgs. */
{ TagBinder *b = ARG(TagBinder *,pointer);
if (b == 0) break;
if (isgensym(tagbindsym_(b))
&& b->typedefname != NULL && !isgensym(b->typedefname))
printsym(alt ? "%s" : "'%s'", b->typedefname);
else {
if (!alt)
errprintf("'");
if (tagbindbits_(b) & TB_TEMPLATE)
errprintf("%s ", sym_name_table[s_template]);
errprintf("%s ", sym_name_table[tagbindsort(b)]);
printbinder((Binder *)b, false);
if (!alt)
errprintf("'");
}
}
break;
case 't': /* TypeExpr* */
qprints(xtype_name(v, ARG(TypeExpr *,pointer)), !alt);
break;
case 'g': /* stgbits -- SET_BITMAP */
errprintf("'%s'", xstgbit_name(ARG(SET_BITMAP,cardinal)));
break;
case 'm': /* typebits -- SET_BITMAP */
errprintf("'%s'", xtypebit_name(ARG(SET_BITMAP,cardinal)));
break;
default:
errprintf("$%c", (int)ch); /* really an error */
break;
}
}
}
}
static void superrprintf(msg_t errorcode, va_list a)
{
start_string_char(msg_lookup(errorcode));
ssuperrprintf(a, YES);
}
static backchat_Diagnostic bd;
static void ReportError_1(int severity, const char *filename, int32 line)
{
bd.filename = filename;
bd.msgtext = errbuf;
bd.severity = (unsigned short)severity;
bd.column = (unsigned short)-1;
bd.lineno = (unsigned)line;
bd.filepos = -1;
SendErrorReport(&bd);
#ifndef NO_LISTING_OUTPUT
if (listing()) {
char b[256];
size_t blen;
cc_announce_error(b, severity, filename, line);
blen = strlen(b);
if (errsaves == NULL)
errsaves = (char *)PermAlloc((errsaven = 1024));
else if (errsavep + blen + errbufp + 1 >= errsaven) {
char *old = errsaves;
errsaves = (char *)PermAlloc((errsaven += 1024));
memcpy(errsaves, old, (size_t)errsavep);
}
if (errsaves == NULL)
{ fclose(listingstream);
listingstream = NULL;
cc_fatalerr(misc_fatalerr_space1);
}
memcpy(&errsaves[errsavep], b, blen);
memcpy(&errsaves[errsavep += blen], errbuf, (size_t)errbufp+1);
errsavep += errbufp+1;
}
#endif
errbufp = 0;
}
static void ReportError(int severity, int32 line)
{
ReportError_1(severity, (line == -1) ? NULL : curlex.fl.f, line);
}
static void ReportErrorContinuation(void)
{
bd.filename = NULL;
bd.lineno = (unsigned)-1;
bd.severity = BC_SEVERITY_NONE;
SendErrorReport(&bd);
#ifndef NO_LISTING_OUTPUT
if (listing()) {
if (errsaves == NULL)
errsaves = (char *)PermAlloc((errsaven = 1024));
else if (errsavep + errbufp + 1 >= errsaven) {
char *old = errsaves;
errsaves = (char *)PermAlloc((errsaven += 1024));
memcpy(errsaves, old, (size_t)errsavep);
}
if (errsaves == NULL)
{ fclose(listingstream);
listingstream = NULL;
cc_fatalerr(misc_fatalerr_space1);
}
memcpy(&errsaves[errsavep], errbuf, (size_t)errbufp+1);
errsavep += errbufp+1;
}
#endif
errbufp = 0;
}
struct NestedContext
{
struct NestedContext *cdr;
FileLine fl;
msg_t msg;
IPtr arg1;
IPtr arg2;
};
static struct NestedContext* nested_context;
void push_nested_context(msg_t errorcode, IPtr arg1, IPtr arg2)
{ struct NestedContext *c = NewBind(struct NestedContext);
cdr_(c) = nested_context;
c->fl = curlex.fl;
c->msg = errorcode;
c->arg1 = arg1;
c->arg2 = arg2;
nested_context = c;
}
void pop_nested_context(void)
{
if (nested_context == NULL)
syserr("no nested context");
nested_context = cdr_(nested_context);
}
static void Report1NestedContext(const char *filename, int line, msg_t s, ... /*IPtr arg, IPtr arg2*/)
{
va_list a;
va_start(a, s);
superrprintf(s, a);
ReportError_1(BC_SEVERITY_INFO, filename, line);
va_end(a);
}
static void ReportNestedContexts(void)
{ struct NestedContext *c = nested_context;
for (; c != NULL; c = cdr_(c))
Report1NestedContext(c->fl.f, c->fl.l, c->msg, c->arg1, c->arg2);
}
void cc_msg(char *s, ...)
{
va_list a;
va_start(a, s);
sstart_string_char(s); ssuperrprintf(a, NO);
if (errbuf[errbufp-1] == '\n')
ReportError(BC_SEVERITY_NONE, -1);
va_end(a);
}
#ifdef NLS
void cc_msg_lookup(msg_t s, ...)
{
va_list a;
va_start(a, s);
sstart_string_char(msg_lookup(s)); ssuperrprintf(a, NO);
ReportError(BC_SEVERITY_NONE, -1);
va_end(a);
}
#endif
void syserr(syserr_message_type errorcode, ...)
{
va_list a;
#ifdef NUMERIC_SYSERR_CODES /* Incompatible with NLS? */
char s[48];
/*
* syserr codes are listed in the file errors.h, and are just
* numeric to save space in the compiler. Furthermore at present the
* extra args are treated by printing two of them as hex values -
* if less than two args were passed this will display junk!
*/
sprintf(s, "maintainer-info(errors.h,%d,%%.8x,%%.8x)", errorcode);
#else
char *s = errorcode;
#endif
va_start(a, errorcode);
superrprintf(misc_message_internal, a);
va_end(a);
ReportError(BC_SEVERITY_FATAL, curlex.fl.l);
va_start(a, errorcode);
sstart_string_char(s); ssuperrprintf(a, YES);
ReportErrorContinuation();
va_end(a);
ReportNestedContexts();
switch (syserr_behaviour)
{ case 1: return; /* Try to go on with compilation */
case 2: abort(); /* hard stop - would like diagnostics */
break;
default: /* stop tolerably quietly and tidily */
#ifndef CALLABLE_COMPILER
va_start(a, errorcode);
superrprintf(misc_disaster_banner, a); /* no escapes */
ReportErrorContinuation();
va_end(a);
#endif
compile_abort(0);
break;
}
compiler_exit(EXIT_syserr);
}
void cc_fatalerr_l(int32 n, msg_t errorcode, va_list a)
{
superrprintf(errorcode, a);
ReportError(BC_SEVERITY_FATAL, n);
ReportNestedContexts();
errprintf(msg_lookup(misc_message_abandoned));
ReportErrorContinuation();
if (syserr_behaviour)
{ show_store_use();
syserr(syserr_syserr); /* rethink this msg if syserrs lack strings */
}
compile_abort(-1); /* (-1) is not a signal number used by signal() */
}
void cc_fatalerr(msg_t errorcode, ...)
{
va_list a;
va_start(a, errorcode);
cc_fatalerr_l(curlex.fl.l, errorcode, a);
va_end(a);
}
void cc_warn_l(int32 n, msg_t errorcode, va_list a)
{
if (!(feature & FEATURE_NOWARNINGS))
{ ++warncount;
superrprintf(errorcode, a);
ReportError(BC_SEVERITY_WARN, n);
ReportNestedContexts();
}
else
++xwarncount;
}
void cc_warn(msg_t errorcode, ...)
{
va_list a;
va_start(a, errorcode);
cc_warn_l(curlex.fl.l, errorcode, a);
va_end(a);
}
void cc_ansi_warn(msg_t errorcode, ...)
/* called to issue a warning that's suppressed in pcc mode */
{
va_list a;
if (feature & FEATURE_PCC) return;
va_start(a, errorcode);
cc_warn_l(curlex.fl.l, errorcode, a);
va_end(a);
}
void cc_pccwarn(msg_t errorcode, ...)
/* This counts as a warning in pcc mode, but a recoverable error in */
/* ANSI mode. Hence it should ONLY be called when the compiler */
/* can claim to repair the construct. In PCC mode ONLY the warning */
/* can be suppressed using the -w option on the command line. */
{
va_list a;
va_start(a, errorcode);
if (feature & FEATURE_PCC)
cc_warn_l(curlex.fl.l, errorcode, a);
else
cc_rerr_l(curlex.fl.l, errorcode, a);
va_end(a);
}
void cc_rerr_l(int32 n, msg_t errorcode, va_list a)
{
++recovercount;
superrprintf(errorcode, a);
ReportError(BC_SEVERITY_ERROR, n);
ReportNestedContexts();
}
void cc_rerr(msg_t errorcode, ...)
{
va_list a;
va_start(a, errorcode);
cc_rerr_l(curlex.fl.l, errorcode, a);
va_end(a);
}
void cc_ansi_rerr(msg_t errorcode, ...)
/* called to output an ANSI mode recoverable error mesage */
/* which is always suppressed in -pcc mode. */
{
va_list a;
if (feature & FEATURE_PCC) return;
va_start(a, errorcode);
cc_rerr_l(curlex.fl.l, errorcode, a);
va_end(a);
}
void cc_rerr_cppwarn(msg_t errorcode, ...)
{ /* recoverable error for C; warning for C++ */
va_list a;
va_start(a, errorcode);
if (!LanguageIsCPlusPlus)
cc_rerr_l(curlex.fl.l, errorcode, a);
else
cc_warn_l(curlex.fl.l, errorcode, a);
va_end(a);
}
void cc_rerr_cwarn(msg_t errorcode, ...)
{ /* recoverable error for C++; warning for C */
va_list a;
va_start(a, errorcode);
if (LanguageIsCPlusPlus)
cc_rerr_l(curlex.fl.l, errorcode, a);
else
/* what does PCC mode want here? Warn like most PCC's */
cc_warn_l(curlex.fl.l, errorcode, a); /* ANSI C says OK. */
va_end(a);
}
void cc_err_l(int32 n, msg_t errorcode, va_list a)
{
if (++errorcount > 100) cc_fatalerr(misc_fatalerr_toomanyerrs);
superrprintf(errorcode, a);
ReportError(BC_SEVERITY_SERIOUS, n);
ReportNestedContexts();
}
void cc_err(msg_t errorcode, ...)
{
va_list a;
va_start(a, errorcode);
cc_err_l(curlex.fl.l, errorcode, a);
va_end(a);
}
void flt_report_error(int failure) {
switch (failure) {
default: syserr("flt_report_error");
case flt_very_small: cc_warn(fp_rerr_very_small); break;
case flt_very_big: cc_rerr(fp_err_very_big); break;
case flt_big_single: cc_rerr(fp_err_big_single); break;
case flt_small_single: cc_warn(fp_rerr_small_single); break;
}
}
void errstate_perfileinit(void)
{
/* reset the following vars for each one of a many file compilation */
warncount=0, recovercount=0, errorcount=0;
xwarncount=0;
/* The next line is scrappy, but avoids printing the null string. */
curlex.fl.f = "<command line>", curlex.fl.l = 1;
fnap_context = NULL;
}
void errstate_initialise(void)
{
errbuf = NULL; errbufp = errbufn = 0;
#ifndef NO_LISTING_OUTPUT
errsaves = NULL;
errsaven = errsavep = 0;
#endif
errstate_perfileinit();
}
/* end of mip/misc.c */
|
stardot/ncc | tests/2162.c | <reponame>stardot/ncc
/*
* 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"
/********************* 2162 ***********************/
/* may syserr */
unsigned short cnt;
unsigned short min;
void t0_2162(void)
{
if(min>=cnt)
cnt = 0;
else
cnt--;
}
int t1_2162(void)
{ int t;
if(min>=cnt)
cnt = 0, t = 1;
else
cnt--, t = 2;
return t;
}
void t_2162(void)
{
cnt = 3;
min = 1;
t0_2162();
EQI(cnt, 2);
EQI(t1_2162(), 2);
EQI(cnt, 1);
}
int main(void)
{
BeginTest();
t_2162();
EndTest();
return 0;
}
|
stardot/ncc | mip/dump.c | /*
* dump.c: compiler state save and restore
* Copyright (C) 1996 Advanced RISC Machines Limited. All rights reserved.
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$ Codemist 0
* Checkin $Date$
* Revising $Author$
*/
#include <string.h>
#include <stdio.h>
#include "globals.h"
#include "defs.h"
#include "builtin.h"
#include "store.h"
#include "aeops.h"
#include "sem.h" /* isbitfield_type */
#include "errors.h"
#include "dump.h"
unsigned dump_state;
Dump_LoadState dump_loadstate;
#define TE_BASICMAX 11
static TypeExpr *te_basic[TE_BASICMAX+1];
static void TE_Basic_Init(void) {
te_basic[0] = NULL;
te_basic[1] = te_void;
te_basic[2] = te_int;
te_basic[3] = te_lint;
te_basic[4] = te_uint;
te_basic[5] = te_ulint;
te_basic[6] = te_float;
te_basic[7] = te_double;
te_basic[8] = te_ldble;
te_basic[9] = te_char;
te_basic[10] = te_ushort;
te_basic[11] = te_boolean;
}
uint32 Dump_BinderRef(Binder *b) {
if (b == NULL) return 0;
if ((IPtr)bindparent_(b) == 0) syserr("Dump_BinderRef %p", b);
return (uint32)(IPtr)bindparent_(b);
}
uint32 Dump_TagRef(TagBinder *b) {
if (b == NULL) return 0;
if ((IPtr)tagbindparent_(b) == 0) syserr("Dump_TagRef %p", b);
return (uint32)(IPtr)tagbindparent_(b);
}
uint32 Dump_TagOrBinderRef(Binder *b) {
return
b == NULL
? 0
: (h0_(b) == s_tagbind)
? Dump_TagRef((TagBinder *)b) | 0x80000000
: Dump_BinderRef(b);
}
uint32 Dump_SymRef(Symstr *sym) {
if (sym == NULL) return 0;
if ((IPtr)symlab_(sym) == 0) syserr("Dump_SymRef %p", sym);
return (uint32)(IPtr)symlab_(sym);
}
#define BINDLISTV_SEGSIZE 256
#define BINDLISTV_MAXSEGS 256
static BindList ***bindlists;
static uint32 nbindlistmax;
void Dump_SharedBindLists(FILE *f) {
uint32 i, n = dump_loadstate.nbindlist;
uint32 w[2];
for (i = 1; i < n; i++) {
uint32 segno = i / BINDLISTV_SEGSIZE,
segix = i % BINDLISTV_SEGSIZE;
BindList *bl = bindlists[segno][segix];
w[0] = Dump_NoteSharedBindList(bl->bindlistcdr);
w[1] = Dump_BinderRef(bl->bindlistcar);
fwrite(w, sizeof(uint32), 2, f);
}
}
uint32 Dump_NoteSharedBindList(BindList *bl) {
uint32 firsti = 0, i, segno, segix;
uint32 n = dump_loadstate.nbindlist;
for (; bl != NULL; bl = bl->bindlistcdr) {
for (i = 1; i < n; i++) {
segno = i / BINDLISTV_SEGSIZE;
segix = i % BINDLISTV_SEGSIZE;
if (bindlists[segno][segix] == bl) {
if (firsti == 0) firsti = i;
dump_loadstate.nbindlist = n;
return firsti;
}
}
segno = n / BINDLISTV_SEGSIZE;
segix = n % BINDLISTV_SEGSIZE;
if (n >= nbindlistmax) {
if (BINDLISTV_MAXSEGS <= segno)
syserr("Too many shared bindlists to dump");
bindlists[segno] = (BindList **)SynAlloc(sizeof(BindList *) * BINDLISTV_SEGSIZE);
nbindlistmax += BINDLISTV_SEGSIZE;
}
bindlists[segno][segix] = bl;
if (firsti == 0) firsti = n;
++n;
}
dump_loadstate.nbindlist = n;
return firsti;
}
void Dump_Sym(Symstr *sym, FILE *f) {
union { uint16 h[2]; uint32 w[3]; } x;
size_t len = strlen(symname_(sym));
x.h[0] = (uint16)len;
x.h[1] = (uint16)symtype_(sym);
fwrite(x.h, sizeof(uint16), 2, f);
x.w[0] = Dump_BinderRef(bind_global_(sym));
x.w[1] = Dump_TagRef(tag_global_(sym));
x.w[2] = Dump_SymRef(symfold_(sym));
fwrite(x.w, sizeof(uint32), 3, f);
fwrite(symname_(sym), 1, len, f);
}
void Dump_BindList(BindList *bl, FILE *f) {
/* (For unshared bindlists) */
uint32 w;
for (; bl != NULL; bl = bl->bindlistcdr) {
w = Dump_BinderRef(bl->bindlistcar);
fwrite(&w, sizeof(uint32), 1, f);
}
w = 0;
fwrite(&w, sizeof(uint32), 1, f);
}
void Dump_Friends(Friend *fr, FILE *f) {
/* /* this is nearly the same as Dump_BindList */
uint32 w;
for (; fr != NULL; fr = fr->friendcdr) {
w = Dump_TagOrBinderRef(fr->u.friendfn);
fwrite(&w, sizeof(uint32), 1, f);
}
w = 0;
fwrite(&w, sizeof(uint32), 1, f);
}
void Dump_StrSeg(StringSegList *s, FILE *f) {
uint32 w = (s == NULL) ? 0 : s->strseglen;
fwrite(&w, sizeof(uint32), 1, f);
if (s != NULL) {
fwrite(s->strsegbase, 1, (size_t)s->strseglen, f);
Dump_StrSeg(s->strsegcdr, f);
}
}
static void DumpExprList(ExprList *e, FILE *f) {
for (; e != NULL; e = cdr_(e))
Dump_Expr(exprcar_(e), f);
Dump_Expr(NULL, f);
}
void Dump_Expr(Expr *e, FILE *f) {
union { uint16 h[2]; uint32 w[5]; } x;
AEop op;
if (e == NULL) {
x.w[0] = 0;
fwrite(x.w, sizeof(uint32), 1, f);
return;
}
x.w[0] = op = h0_(e);
switch (op) {
case s_floatcon:
x.w[1] = ((FloatCon *)e)->floatlen;
x.w[2] = ((FloatCon *)e)->floatbin.irep[0];
x.w[3] = ((FloatCon *)e)->floatbin.irep[1];
x.w[4] = strlen(((FloatCon *)e)->floatstr);
fwrite(x.w, sizeof(uint32), 5, f);
fwrite(((FloatCon *)e)->floatstr, 1, (size_t)x.w[4], f);
return;
#ifdef EXTENSION_UNSIGNED_STRINGS
case s_ustring:
#endif
case s_wstring:
case s_string:
fwrite(x.w, sizeof(uint32), 1, f);
Dump_StrSeg(((String *)e)->strseg, f);
return;
case s_fnapstruct:
case s_fnap:
fwrite(x.w, sizeof(uint32), 1, f);
Dump_Type(type_(e), f);
Dump_Expr(arg1_(e), f);
DumpExprList(exprfnargs_(e), f);
return;
case s_let:
fwrite(x.w, sizeof(uint32), 1, f);
Dump_Type(type_(e), f);
Dump_BindList((BindList *)exprletbind_(e), f);
Dump_Expr(arg2_(e), f);
return;
case s_binder:
x.w[1] = Dump_BinderRef((Binder *)e);
fwrite(x.w, sizeof(uint32), 2, f);
return;
case s_integer:
x.w[1] = intval_(e);
fwrite(x.w, sizeof(uint32), 2, f);
Dump_Type(type_(e), f);
return;
case s_cond:
fwrite(x.w, sizeof(uint32), 1, f);
Dump_Type(type_(e), f);
Dump_Expr(arg1_(e), f);
Dump_Expr(arg2_(e), f);
Dump_Expr(arg3_(e), f);
return;
case s_qualdot:
case s_dot:
fwrite(x.w, sizeof(uint32), 1, f);
Dump_Type(type_(e), f);
Dump_Expr(arg1_(e), f);
x.w[0] = exprdotoff_(e);
if (!isbitfield_type(type_(e))) {
fwrite(x.w, sizeof(uint32), 1, f);
} else {
x.w[1] = exprbsize_(e);
x.w[2] = exprmsboff_(e);
fwrite(x.w, sizeof(uint32), 3, f);
}
return;
default:
fwrite(x.w, sizeof(uint32), 1, f);
Dump_Type(type_(e), f);
Dump_Expr(arg1_(e), f);
if (isdiad_(op) || op == s_init)
Dump_Expr(arg2_(e), f);
return;
}
}
void Dump_Type(TypeExpr *t, FILE *f) {
union { uint16 h[2]; uint32 w[3]; } x;
for (;;) {
if (t == NULL) {
x.w[0] = 0;
fwrite(x.w, sizeof(uint32), 1, f);
return;
}
x.w[0] = h0_(t);
switch (h0_(t)) {
case t_content:
case t_ref:
x.w[1] = typeptrmap_(t);
fwrite(x.w, sizeof(uint32), 2, f);
t = typearg_(t);
break;
case s_typespec:
{ size_t n = 3;
uint32 i;
for (i = 1; i <= TE_BASICMAX; i++)
if (t == te_basic[i]) {
x.w[0] = 0-i;
fwrite(x.w, sizeof(uint32), 1, f);
return;
}
x.w[1] = typespecmap_(t);
if (typespecmap_(t) & ENUMORCLASSBITS) {
x.w[2] = Dump_TagRef(typespectagbind_(t));
} else if (typespecmap_(t) & bitoftype_(s_typedefname)) {
x.w[2] = Dump_BinderRef(typespecbind_(t));
} else
n = 2;
fwrite(x.w, sizeof(uint32), n, f);
}
return;
case t_subscript:
fwrite(x.w, sizeof(uint32), 1, f);
Dump_Expr(typesubsize_(t), f);
t = typearg_(t);
break;
case t_fnap:
{ FormTypeList *ft = typefnargs_(t);
x.w[1] = length((List *)ft);
x.w[2] = typeptrmap_(t);
fwrite(x.w, sizeof(uint32), 3, f);
for (; ft != NULL; ft = ft->ftcdr) {
x.w[0] = Dump_SymRef(ft->ftname);
fwrite(x.w, sizeof(uint32), 1, f);
Dump_Type(ft->fttype, f);
Dump_Expr(ft->ftdefault, f);
}
fwrite(&typefnaux_(t), sizeof(TypeExprFnAux), 1, f);
t = typearg_(t);
break;
}
case t_coloncolon:
x.w[1] = Dump_TagRef(typespectagbind_(t));
fwrite(x.w, sizeof(uint32), 2, f);
t = typearg_(t);
break;
case t_ovld:
fwrite(x.w, sizeof(uint32), 1, f);
Dump_BindList(typeovldlist_(t), f);
return;
default:
fwrite(x.w, sizeof(uint32), 1, f);
syserr("Dump_Type %ld", (long)h0_(t));
return;
}
}
}
#define INDEX_SEGSIZE 1024
static Symstr ***symindex;
static BindList ***bindlistindex;
static Binder ***binderindex;
static TagBinder ***tagindex;
static uint32 symno;
Binder *Dump_LoadedBinder(uint32 i) {
uint32 segno = i / INDEX_SEGSIZE,
segix = i % INDEX_SEGSIZE;
return binderindex[segno][segix];
}
TagBinder *Dump_LoadedTag(uint32 i) {
uint32 segno = i / INDEX_SEGSIZE,
segix = i % INDEX_SEGSIZE;
return tagindex[segno][segix];
}
Binder *Dump_LoadedTagOrBinder(uint32 i) {
return (i & 0x80000000) ? (Binder *)Dump_LoadedTag(i & ~0x80000000)
: Dump_LoadedBinder(i);
}
Symstr *Dump_LoadedSym(uint32 i) {
uint32 segno = i / INDEX_SEGSIZE,
segix = i % INDEX_SEGSIZE;
return symindex[segno][segix];
}
BindList *Dump_LoadedSharedBindList(uint32 i) {
uint32 segno = i / INDEX_SEGSIZE,
segix = i % INDEX_SEGSIZE;
return bindlistindex[segno][segix];
}
void Dump_LoadString(char *p, size_t n, FILE *f) {
fread(p, 1, n, f);
p[n] = 0;
}
BindList *Dump_LoadBindList(FILE *f) {
BindList *bl;
BindList **blp = &bl;
uint32 w;
for (;;) {
BindList *p;
fread(&w, sizeof(uint32), 1, f);
if (w == 0) break;
p = (BindList *)GlobAlloc(SU_Bind, sizeof(BindList));
p->bindlistcar = Dump_LoadedBinder(w);
*blp = p;
blp = &p->bindlistcdr;
}
*blp = NULL;
return bl;
}
Friend *Dump_LoadFriends(FILE *f) {
/* this is nearly the same as Dump_LoadBindList */
Friend *fr;
Friend **frp = &fr;
uint32 w;
for (;;) {
Friend *p;
fread(&w, sizeof(uint32), 1, f);
if (w == 0) break;
p = (Friend *)GlobAlloc(SU_Other, sizeof(Friend));
p->u.friendfn = Dump_LoadedTagOrBinder(w);
*frp = p;
frp = &p->friendcdr;
}
*frp = NULL;
return fr;
}
StringSegList *Dump_LoadStrSeg(FILE *f) {
uint32 len;
fread(&len, sizeof(uint32), 1, f);
if (len == 0) return NULL;
{ StringSegList *s = (StringSegList *)GlobAlloc(SU_Inline, sizeof(StringSegList) + len);
s->strsegbase = (char *)(s+1);
s->strseglen = len;
fread(s->strsegbase, 1, (size_t)len, f);
s->strsegcdr= Dump_LoadStrSeg(f);
return s;
}
}
static ExprList *LoadExprList(FILE *f) {
ExprList *res = NULL;
for (;;) {
Expr *e = Dump_LoadExpr(f);
if (e == NULL)
return (ExprList *)dreverse((List *)res);
res = mkExprList(res, e);
}
}
Expr *Dump_LoadExpr(FILE *f) {
union { uint16 h[2]; uint32 w[4]; } x;
AEop op;
Expr *e;
fread(x.w, sizeof(uint32), 1, f);
if (x.w[0] == 0) return NULL;
op = x.w[0];
switch (op) {
case s_floatcon:
fread(x.w, sizeof(uint32), 4, f);
{ FloatCon *fc = (FloatCon *)GlobAlloc(SU_Other, sizeof(FloatCon) + x.w[3]);
h0_(fc) = op;
fc->floatlen = x.w[0];
fc->floatbin.irep[0] = x.w[1];
fc->floatbin.irep[1] = x.w[2];
Dump_LoadString(fc->floatstr, (size_t)x.w[3], f);
return (Expr *)fc;
}
#ifdef EXTENSION_UNSIGNED_STRINGS
case s_ustring:
#endif
case s_wstring:
case s_string:
{ String *s = (String *)global_cons2(SU_Other, op, 0);
s->strseg = Dump_LoadStrSeg(f);
return (Expr *)s;
}
case s_fnapstruct:
case s_fnap:
e = (Expr *)GlobAlloc(SU_Other, sizeof(IPtr[5]));
h0_(e) = op;
type_(e) = Dump_LoadType(f);
arg1_(e) = Dump_LoadExpr(f);
exprfnargs_(e) = LoadExprList(f);
return e;
case s_let:
e = (Expr *)GlobAlloc(SU_Other, sizeof(IPtr[5]));
h0_(e) = op;
type_(e) = Dump_LoadType(f);
exprletbind_(e) = (SynBindList *)Dump_LoadBindList(f);
arg2_(e) = Dump_LoadExpr(f);
return e;
case s_binder:
fread(x.w, sizeof(uint32), 1, f);
return (Expr *)Dump_LoadedBinder(x.w[0]);
case s_integer:
fread(x.w, sizeof(uint32), 1, f);
e = (Expr *)global_list5(SU_Other, op, 0, 0, x.w[0], 0);
type_(e) = Dump_LoadType(f);
return e;
case s_cond:
e = (Expr *)GlobAlloc(SU_Other, sizeof(IPtr[6]));
h0_(e) = op;
exprfileline_(e) = NULL;
type_(e) = Dump_LoadType(f);
arg1_(e) = Dump_LoadExpr(f);
arg2_(e) = Dump_LoadExpr(f);
arg3_(e) = Dump_LoadExpr(f);
return e;
case s_dot:
{ TypeExpr *t = Dump_LoadType(f);
e = (Expr *)GlobAlloc(SU_Other, isbitfield_type(t) ? sizeof(IPtr[7]) : sizeof(IPtr[5]));
h0_(e) = op;
type_(e) = t;
}
arg1_(e) = Dump_LoadExpr(f);
if (!isbitfield_type(type_(e))) {
fread(x.w, sizeof(uint32), 1, f);
exprdotoff_(e) = x.w[0];
} else {
fread(x.w, sizeof(uint32), 3, f);
exprdotoff_(e) = x.w[0];
exprbsize_(e) = x.w[1];
exprmsboff_(e) = x.w[2];
}
return e;
default:
e = (Expr *)GlobAlloc(SU_Other, (isdiad_(op) || op == s_init) ? sizeof(IPtr[5]) : sizeof(IPtr[4]));
h0_(e) = op;
type_(e) = Dump_LoadType(f);
arg1_(e) = Dump_LoadExpr(f);
if (isdiad_(op) || op == s_init)
arg2_(e) = Dump_LoadExpr(f);
return e;
}
}
TypeExpr *Dump_LoadType(FILE *f) {
union { uint16 h[2]; uint32 w[3]; } x;
TypeExpr *t;
uint32 op;
fread(x.w, sizeof(uint32), 1, f);
op = x.w[0];
if ((int32)op <= 0) return te_basic[0-op];
switch (op) {
case t_content:
case t_ref:
fread(x.w, sizeof(uint32), 1, f);
t = (TypeExpr *)global_list4(SU_Type, op, 0, x.w[0], 0);
typearg_(t) = Dump_LoadType(f);
return t;
case s_typespec:
fread(x.w, sizeof(uint32), 1, f);
t = (TypeExpr *)global_list4(SU_Type, op, x.w[0], 0, 0);
if (typespecmap_(t) & ENUMORCLASSBITS) {
fread(x.w, sizeof(uint32), 1, f);
typespecbind_(t) = (Binder *)Dump_LoadedTag(x.w[0]);
} else if (typespecmap_(t) & bitoftype_(s_typedefname)) {
fread(x.w, sizeof(uint32), 1, f);
typespecbind_(t) = Dump_LoadedBinder(x.w[0]);
}
return t;
case t_subscript:
t = (TypeExpr *)global_list4(SU_Type, op, 0, 0, 0);
typesubsize_(t) = Dump_LoadExpr(f);
typearg_(t) = Dump_LoadType(f);
return t;
case t_fnap:
fread(x.w, sizeof(uint32), 2, f);
t = (TypeExpr *)GlobAlloc(SU_Type, sizeof(TypeExpr));
h0_(t) = op;
typedbginfo_(t) = 0;
typeptrmap_(t) = x.w[1];
{ FormTypeList **ftp = &typefnargs_(t);
uint32 i, nft = x.w[0];
for (i = 0; i < nft; i++) {
FormTypeList *ft = (FormTypeList *)GlobAlloc(SU_Type, sizeof(FormTypeList));
fread(x.w, sizeof(uint32), 1, f);
ft->ftname = Dump_LoadedSym(x.w[0]);
ft->fttype = Dump_LoadType(f);
ft->ftdefault = Dump_LoadExpr(f);
*ftp = ft;
ftp = &ft->ftcdr;
}
*ftp = NULL;
fread(&typefnaux_(t), sizeof(TypeExprFnAux), 1, f);
typearg_(t) = Dump_LoadType(f);
return t;
}
case t_coloncolon:
fread(x.w, sizeof(uint32), 1, f);
t = (TypeExpr *)global_list4(SU_Type, op, 0, Dump_LoadedTag(x.w[0]), 0);
typearg_(t) = Dump_LoadType(f);
return t;
case t_ovld:
t = (TypeExpr *)global_list4(SU_Type, op, (TypeExpr*)DUFF_ADDR, 0, 0);
typeovldlist_(t) = Dump_LoadBindList(f);
return t;
default:
syserr("Dump_LoadType %ld", (long)op);
return NULL;
}
}
Symstr *Dump_LoadSym(size_t len, FILE *f) {
union { uint16 h[2]; uint32 w[3]; } x;
Symstr *sym = (Symstr *)GlobAlloc(SU_Sym, sizeof(Symstr) + (int32)len);
fread(x.h, sizeof(uint16), 1, f);
symtype_(sym) = x.h[0];
symlab_(sym) = NULL;
symext_(sym) = NULL;
fread(x.w, sizeof(uint32), 3, f);
bind_global_(sym) = Dump_LoadedBinder(x.w[0]);
tag_global_(sym) = Dump_LoadedTag(x.w[1]);
symfold_(sym) = (Symstr *)(IPtr)x.w[2];
Dump_LoadString(symname_(sym), len, f);
++symno;
symindex[symno/INDEX_SEGSIZE][symno%INDEX_SEGSIZE] = sym;
return sym;
}
static void *AllocIndex(uint32 isize, uint32 n) {
uint32 nix = (n + INDEX_SEGSIZE) / INDEX_SEGSIZE;
void **index = (void **)SynAlloc(nix * sizeof(void *));
while (nix > 0) index[--nix] = SynAlloc(isize * INDEX_SEGSIZE);
return index;
}
void Dump_Init(Dump_Sort action, FILE *f) {
TE_Basic_Init();
if (action == Dump_Load) {
uint32 i;
fread(&dump_loadstate, sizeof(uint32), 5, f);
dump_loadstate.nsym += dump_loadstate.ngensym;
symindex = (Symstr ***)AllocIndex(sizeof(Symstr *), dump_loadstate.nsym);
bindlistindex = (BindList ***)AllocIndex(sizeof(BindList *), dump_loadstate.nbindlist);
binderindex = (Binder ***)AllocIndex(sizeof(Binder *), dump_loadstate.nglobbind);
tagindex = (TagBinder ***)AllocIndex(sizeof(TagBinder *), dump_loadstate.nglobtag);
bindlistindex[0][0] = NULL;
binderindex[0][0] = NULL;
tagindex[0][0] = NULL;
symindex[0][0] = NULL;
symno = 0;
for (i = 1; i < dump_loadstate.nglobtag; i++)
tagindex[i/INDEX_SEGSIZE][i%INDEX_SEGSIZE] = (TagBinder *)GlobAlloc(SU_Bind, sizeof(TagBinder));
for (i = 1; i < dump_loadstate.nglobbind; i++)
binderindex[i/INDEX_SEGSIZE][i%INDEX_SEGSIZE] = (Binder *)GlobAlloc(SU_Bind, sizeof(Binder));
for (i = 1; i < dump_loadstate.nbindlist; i++)
bindlistindex[i/INDEX_SEGSIZE][i%INDEX_SEGSIZE] = (BindList *)GlobAlloc(SU_Inline, sizeof(BindList));
} else {
bindlists = (BindList ***)SynAlloc(sizeof(BindList **) * BINDLISTV_MAXSEGS);
dump_loadstate.nbindlist = 1; nbindlistmax = 0;
}
}
|
stardot/ncc | mip/bind.h | /*
* mip/bind.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 _bind_h
#define _bind_h
#ifndef _defs_LOADED
# include "defs.h"
#endif
/* The next three lines interface syn.c and bind.c: see syn.c for more. */
#define DUPL_OK 0x001
#define TOPLEVEL 0x002 /* Global lexical scope and global */
/* storage scope... */
#define GLOBALSTG 0x004 /* Not global lexical scope, but */
/* global storage scope for e.g. */
/* types defined in argument lists */
#define LOCALSCOPE 0x000 /* Local lexical and storage scope */
#define TEMPLATE 0x1000 /* OR-able (but only with TOPLEVEL)*/
/* (probably really a stg bit). */
#define SPECIALIZE 0x10000 /* template <> ... */
#define INSTANTIATE 0x20000 /* template struct ... */
#define INSTANCE 0x40000 /* template fn instance */
extern const char *sym_name_table[]; /* translation back to strings */
#define SYM_LOCAL 0
#define SYM_GLOBAL 1
extern Symstr *(sym_lookup)(char const *name, int glo);
extern Symstr *sym_insert(char const *name, AEop type);
extern Symstr *sym_insert_id(char const *name);
extern Symstr *gensymval(bool glo);
extern Symstr *gensymvalwithname(bool glo, char const *name);
extern bool isgensym(Symstr const *sym);
extern Binder *global_mk_binder(Binder *b, Symstr *c, SET_BITMAP d,
TypeExpr *e);
extern Binder *mk_binder(Symstr *c, SET_BITMAP d, TypeExpr *e);
extern TagBinder *global_mk_tagbinder(TagBinder *b, Symstr *c, AEop d);
extern TagBinder *mk_tagbinder(Symstr *c, AEop d);
extern TagBinder *clone_tagbinder(Symstr *newname, TagBinder *b);
extern LabBind *mk_labbind(LabBind *b, Symstr *c);
#define gentempbinderwithname(typ, name) \
mk_binder(gensymvalwithname(0, name), bitofstg_(s_auto), typ)
#define gentempbinder(typ) \
mk_binder(gensymval(0), bitofstg_(s_auto), typ)
#define genglobinder(typ) \
global_mk_binder(0, gensymval(1), bitofstg_(s_static), typ)
extern void add_toplevel_binder(Binder *b);
typedef enum {
TD_NotDef,
TD_ContentDef,
TD_Decl
} TagDefSort;
/* The distinction between TD_ContentDef and TD_Decl is to allow
struct a { int x; }; struct a;
but forbid
struct a { int x; }; struct a { anything };
@@@ AM: it may be subsumable into the TB_DEFD needed for C++ (q.v.)
*/
typedef enum {
Scope_Ord,
Scope_Args,
Scope_TemplateArgs,
Scope_TemplateDef
} ScopeSort;
typedef struct Scope Scope;
struct Scope {
Scope *prev;
Binder *scopemems; /* A scope either contains Binders */
/* and TagBinders (a local scope) */
/* and members too (class scope). */
/* (unused if class_tag != 0). */
TagBinder *class_tag;
ScopeSort kind;
};
extern int push_scope(TagBinder *class_tag, ScopeSort kind);
extern int push_var_scope(ScopeSaver init, ScopeSort kind);
#ifdef CALLABLE_COMPILER
extern void set_local_scope(Scope *scope);
#endif
extern ScopeSaver pop_scope(int);
extern ScopeSaver pop_scope_no_check(int);
#define FB_INHERIT 1
#define FB_LOCALS 2
#define FB_CLASSES 4
#define FB_GLOBAL 8
#define FB_FNBINDER 32 /* return a fn binder, not an exprdotmemfn */
#define FB_KEEPI 64 /* keep the top invisible node, if any */
#define FB_TYPENAME 128
#define FB_CLASSNAME 256
#define FB_CIV 512
#define FB_NOTYET 1024
#define FB_THISSCOPE 2048
#define LOCALSCOPES FB_LOCALS
#define ALLSCOPES (FB_LOCALS+FB_CLASSES+FB_GLOBAL+FB_INHERIT)
#define INDERIVATION FB_INHERIT
#define INCLASSONLY 0
extern ClassMember *curlex_member; /* @@@ Think about a better location */
/* for this decl, defined in syn.c... */
extern int derivation_level;
extern Expr *findpath(Symstr *sv, TagBinder *cl, int flags, TagBinder *inBase);
extern Binder *findbinding(Symstr *sv, TagBinder *cl, int flags);
extern Expr *path_to_member(ClassMember *member, TagBinder *cl, int flags);
extern TagBinder *findtagbinding(Symstr *sv, TagBinder *cl, int flags);
/*
* In the following, bindflg takes any combination of TOPLEVEL + GLOBALTAG.
*/
extern TagBinder *instate_tagbinding(Symstr *sv, AEop s, TagDefSort defining,
int bindflg, bool *newtag);
extern void instate_alias(Symstr *a, Binder *b);
extern Binder *instate_declaration(DeclRhsList *d, int declflag);
extern ClassMember *instate_member(DeclRhsList *d, int bindflg);
extern Binder *implicit_decl(Symstr *a, int32 fn);
extern void reset_vg_after_init_of_tentative_defn(void);
void save_vargen_state(TentativeDefn *td);
extern LabBind *label_define(Symstr *id);
extern LabBind *label_reference(Symstr *id);
extern void label_resolve(void);
extern void save_labels(LabBind **lc, LabBind **symlabs);
extern void restore_labels(LabBind *lc, LabBind **symlabs);
extern void bind_cleanup(void);
extern void bind_init(void);
#ifdef CPLUSPLUS
ClassMember *mk_member(TagBinder *basename, TypeExpr *t,
SET_BITMAP attributes, TagBinder *parent);
ClassMember *mk_core_part(TagBinder *cl, ClassMember *bases,
ClassMember *vbases);
extern int accessOK;
extern void check_access(ClassMember *m, TagBinder *privately_deriving_class);
extern int push_multi_scope(TagBinder *class_tag);
extern TypeExpr *memfn_realtype(TypeExpr *fntype, TagBinder *cl);
extern TypeExpr *add_delete_arg(TypeExpr *fntype, bool is_declaration);
extern Binder *instate_memfn(Symstr *fsv, TypeExpr *t);
extern TagBinder *current_member_scope(void);
extern TagBinder *set_access_context(TagBinder *cl, Binder *fn);
extern void mk_friend_class(TagBinder *classtag, TagBinder *ofclass);
extern void mk_friend_fn(Binder *bspecific, TagBinder *ofclass);
/* derived_from is logically 'bool' but returns the base ClassMember: */
extern ClassMember *derived_from(TagBinder *base, TagBinder *scope);
/* same class or derived_from */
extern bool derived_fromeq(TagBinder *base, TagBinder *scope);
/* The following provide for-style iterators for C++ classes which */
/* can steer round CB_CORE etc. */
typedef struct ClassMemo { struct ClassMember *outer, *core; } ClassMemo;
extern ClassMember *ClassMemo_next(ClassMemo *m);
extern ClassMember *ClassMemo_first(ClassMemo *m, ClassMember *p);
#define forClassMember(p,i,m) \
for (p = ClassMemo_first(m, i); p != 0; p = ClassMemo_next(m))
extern void push_exprtemp_scope(void); /* @@@ implemented in xsyn.c */
extern void pop_exprtemp_scope(void); /* @@@ implemented in xsyn.c */
extern Binder *genexprtemp(TypeExpr *t); /* ditto */
extern Expr *killexprtemp(void); /* @@@ ditto */
extern int killnexprtemp(Binder *);
extern Binder *genreftemp(TypeExpr *t); /* @@@ implemented in xsyn.c */
extern int killreftemp(Binder *b); /* @@@ implemented in xsyn.c */
/* declaration here avoids sem.c:syn.h dependency. */
extern Binder *instate_classname(DeclRhsList *d, TagBinder *tb);
extern bool is_two_arg_delete(Binder* delgeneric);
extern bool is_local_binder(Binder *b);
extern bool is_template_arg_binder(Expr *e);
extern bool has_template_arg_scope(void);
extern BindList *clone_bindlist(BindList * bl, bool glob);
extern ScopeSaver dup_template_scope(void);
extern bool no_access_context(void);
extern void check_access_1(ClassMember *l, TagBinder *scope);
extern void push_saved_temps(int32 scopeid);
extern SynBindList *pop_saved_temps(SynBindList *bl);
extern void syn_note_generated_fn(TopDecl *d);
extern int32 base_vtable_sz(TagBinder *b);
extern TagBindList *rootOfPath;
#else
#define current_member_scope() ((TagBinder *)0)
#define derived_from(b, s) ((ClassMember *)0)
#define path_to_base_member(m, t, f, v, pdc) 0
#define path_to_member_2(m, b, f, l, pdc) 0
#define instate_member_cpp(d, b) 0
#define instate_declaration_cpp(d, f) 0
#define genreftemp(t) ((Binder *)0)
#define killreftemp(b) 0
#define genexprtemp(t) ((Binder *)0)
#define killexprtemp() 0
#define push_exprtemp_scope() ((void)0)
#define pop_exprtemp_scope() ((void)0)
#define push_saved_temps(id) ((void)0)
#define pop_saved_temps(bl) (bl)
#define syn_note_generated_fn(a) ((void)0)
#define mk_friend_class(a, b) (void)0
#define is_local_binder(a) (bool)0
#define is_template_arg_binder(a) (bool)0
#define has_template_arg_scope() (bool)0
#define dup_template_scope() (ScopeSaver)0
#define clone_bindlist(a,b) (BindList *)a
#endif
#endif
/* end of mip/bind.h */
|
stardot/ncc | mip/dw_int.h | /*
* C compiler file mip/dw_int.h
* Copyright: (C) 1995, Advanced RISC Machines Limited. All rights reserved.
* Interface between main DWARF debug formatter and table writers.
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
/* Private tag values used to mark DbgList items. They don't make it out */
/* into the debug tables. */
#define DW_TAG_endproc (DW_TAG_lo_user)
#define DW_TAG_end_lexical_block (DW_TAG_lo_user+1)
#define DW_TAG_proctype_formal (DW_TAG_lo_user+2)
#define DW_TAG_fref (DW_TAG_lo_user+3)
#define DW_TAG_ignore (DW_TAG_lo_user+4)
#define DW_TAG_array_bound (DW_TAG_lo_user+5)
#define DW_TAG_procdecl (DW_TAG_lo_user+6)
extern Symstr *dw_debug_sym, *dw_lineinfo_sym;
extern Symstr *dw_macro_sym, *dw_abbrev_sym, *dw_location_sym;
#define Dwarf1DebugAreaName ".debug"
#define Dwarf1LineInfoAreaName ".line"
#define Dwarf2DebugAreaName ".debug_info"
#define Dwarf2LineInfoAreaName ".debug_line"
#define DebugAreaName (dw_version == 2 ? Dwarf2DebugAreaName : Dwarf1DebugAreaName)
#define LineInfoAreaName (dw_version == 2 ? Dwarf2LineInfoAreaName : Dwarf1LineInfoAreaName)
#define NameIndexAreaName ".debug_pubnames"
#define RangeIndexAreaName ".debug_arange"
/* The following in DWARF version 2 only */
#define MacroAreaName ".debug_macinfo"
#define AbbrevAreaName ".debug_abbrev"
#define LocationAreaName ".debug_loc"
typedef struct Dw_ItemList Dw_TypeRep;
typedef struct Dbg_Structelt Dbg_Structelt;
typedef struct Dbg_Enumelt Dbg_Enumelt;
typedef struct Dbg_Return Dbg_Return;
/* The following is the *internal* data structure in which debug info. */
/* is buffered. */
typedef struct Dw_ItemList Dw_ItemList;
typedef enum {
Stg_Reg,
Stg_Auto,
Stg_Static,
Stg_Extern,
Stg_ArgReg,
Stg_ArgAuto
} StgClass;
typedef struct {
Symstr *sym;
RealRegister r;
} SymOrReg;
struct Dw_ItemList {
Dw_ItemList *cdr;
int debsort;
Dw_ItemList *sibling;
uint32 dbgloc;
union
{ struct { Dw_ItemList *children;
char const *name;
Symstr *codeseg;
int32 codesize;
} DEB_SECTION;
struct { Dw_ItemList *children;
Dw_TypeRep *type;
int32 entryaddr, bodyaddr; /* see dbg_bodyproc */
Dw_ItemList *endproc;
int global;
char const *name;
Symstr *codeseg;
bool variadic;
SET_BITMAP stgbits; /* StgClass inadequate! */
Dw_TypeRep *parent;
Dw_ItemList *decl;
} DEB_PROC;
struct { Dw_ItemList *children;
Dw_TypeRep *type;
int global;
char const *name;
bool variadic;
int32 voffset;
SET_BITMAP stgbits; /* StgClass inadequate! */
Dw_TypeRep *parent;
} DEB_PROCDECL;
struct { Dw_ItemList *qualtypes;
Dw_ItemList *children;
Dw_TypeRep *type;
} DEB_PROCTYPE;
struct { Dw_ItemList *qualtypes;
Dw_TypeRep *container;
Dw_TypeRep *type;
} DEB_PTRTOMEMTYPE;
struct { Symstr *name;
Dw_TypeRep *type;
Expr *defltexpr;
Dw_ItemList *defltfn;
bool invented;
} DEB_FORMAL;
struct { int32 dummy;
} DEB_REST;
struct { int32 endaddr;
} DEB_ENDPROC;
struct { Dw_TypeRep *type;
StgClass stgclass;
int32 location;
Symstr *sym;
SymOrReg base;
} DEB_VAR;
struct { Dw_ItemList *qualtypes;
char *name;
Dw_TypeRep *type;
TypeExpr *typex;
} DEB_TYPE;
struct { Dw_ItemList *qualtypes;
Dw_ItemList *nextbasetype;
int typecode;
} DEB_BASETYPE;
struct { Dw_TypeRep *type;
Dw_TypeRep *nextqual; /* chain through qualified types of the same base */
Dw_TypeRep *basetype; /* all qualifiers stripped */
Dw_TypeRep *qualifiedtype; /* type with this qualifier removed */
int n;
uint8 *qualmap;
} DEB_QUALTYPE;
struct { Dw_ItemList *qualtypes;
char const *name;
Dw_ItemList *children;
Dw_TypeRep *container;
char size;
} DEB_ENUM;
struct { char *name;
int32 val;
} DEB_ENUMERATOR;
struct { Dw_ItemList *qualtypes;
Dw_ItemList *children;
int32 size;
int32 open;
Dw_TypeRep *basetype;
int32 lowerbound;
int32 upperbound;
} DEB_ARRAY;
struct { int32 open;
int32 upperbound;
} DEB_ARRAYBOUND;
struct { Dw_ItemList *qualtypes;
char const *name;
Dw_ItemList *children;
int undefsort;
/* A not-yet-defined (but referenced) struct, class or */
/* union is given sort TAG_fref, and its real sort is */
/* stored in undefsort. */
int32 size;
Friend *friends;
} DEB_STRUCT;
struct { char const *name; /* source form */
int32 offset;
Dw_TypeRep *type;
uint8 bsize, boffset;
} DEB_MEMBER;
struct { Dw_TypeRep *type;
int32 offset;
uint8 virt;
} DEB_INHERIT;
struct { union { Dw_ItemList *next;
int32 codeaddr;
} s;
Dw_ItemList *children;
Dw_ItemList *end;
Symstr *codeseg;
} DEB_STARTSCOPE;
struct { union { Dw_ItemList *next;
int32 codeaddr;
} s;
} DEB_ENDSCOPE;
struct { Dw_ItemList **parent;
} DEB_NULL;
} car;
};
#define debsort_(p) ((p)->debsort)
#define sibling_(p) ((p)->sibling)
#define dbgloc_(p) ((p)->dbgloc)
#define sect_children_(p) ((p)->car.DEB_SECTION.children)
#define sect_name_(p) ((p)->car.DEB_SECTION.name)
#define sect_codeseg_(p) ((p)->car.DEB_SECTION.codeseg)
#define sect_codesize_(p) ((p)->car.DEB_SECTION.codesize)
#define proc_children_(p) ((p)->car.DEB_PROC.children)
#define proc_type_(p) ((p)->car.DEB_PROC.type)
#define proc_entry_(p) ((p)->car.DEB_PROC.entryaddr)
#define proc_body_(p) ((p)->car.DEB_PROC.bodyaddr)
#define proc_endproc_(p) ((p)->car.DEB_PROC.endproc)
#define proc_global_(p) ((p)->car.DEB_PROC.global)
#define proc_name_(p) ((p)->car.DEB_PROC.name)
#define proc_codeseg_(p) ((p)->car.DEB_PROC.codeseg)
#define proc_variadic_(p) ((p)->car.DEB_PROC.variadic)
#define proc_stg_(p) ((p)->car.DEB_PROC.stgbits)
#define proc_parent_(p) ((p)->car.DEB_PROC.parent)
#define proc_decl_(p) ((p)->car.DEB_PROC.decl)
#define procdecl_children_(p) ((p)->car.DEB_PROCDECL.children)
#define procdecl_type_(p) ((p)->car.DEB_PROCDECL.type)
#define procdecl_global_(p) ((p)->car.DEB_PROCDECL.global)
#define procdecl_name_(p) ((p)->car.DEB_PROCDECL.name)
#define procdecl_variadic_(p) ((p)->car.DEB_PROCDECL.variadic)
#define procdecl_voffset_(p) ((p)->car.DEB_PROCDECL.voffset)
#define procdecl_stg_(p) ((p)->car.DEB_PROCDECL.stgbits)
#define procdecl_parent_(p) ((p)->car.DEB_PROCDECL.parent)
#define proctype_qual_(p) ((p)->car.DEB_PROCTYPE.qualtypes)
#define proctype_children_(p) ((p)->car.DEB_PROCTYPE.children)
#define proctype_type_(p) ((p)->car.DEB_PROCTYPE.type)
#define ptrtomem_container_(p) ((p)->car.DEB_PTRTOMEMTYPE.type)
#define ptrtomem_qual_(p) ((p)->car.DEB_PTRTOMEMTYPE.qualtypes)
#define ptrtomem_type_(p) ((p)->car.DEB_PTRTOMEMTYPE.container)
#define formal_name_(p) ((p)->car.DEB_FORMAL.name)
#define formal_type_(p) ((p)->car.DEB_FORMAL.type)
#define formal_defltexpr_(p) ((p)->car.DEB_FORMAL.defltexpr)
#define formal_defltfn_(p) ((p)->car.DEB_FORMAL.defltfn)
#define formal_invented_(p) ((p)->car.DEB_FORMAL.invented)
#define endproc_endaddr_(p) ((p)->car.DEB_ENDPROC.endaddr)
#define var_type_(p) ((p)->car.DEB_VAR.type)
#define var_stgclass_(p) ((p)->car.DEB_VAR.stgclass)
#define var_loc_(p) ((p)->car.DEB_VAR.location)
#define var_sym_(p) ((p)->car.DEB_VAR.sym)
#define var_base_(p) ((p)->car.DEB_VAR.base)
#define type_qual_(p) ((p)->car.DEB_TYPE.qualtypes)
#define type_name_(p) ((p)->car.DEB_TYPE.name)
#define type_type_(p) ((p)->car.DEB_TYPE.type)
#define type_typex_(p) ((p)->car.DEB_TYPE.typex)
#define basetype_qual_(p) ((p)->car.DEB_BASETYPE.qualtypes)
#define basetype_typecode_(p) ((p)->car.DEB_BASETYPE.typecode)
#define basetype_next_(p) ((p)->car.DEB_BASETYPE.nextbasetype)
#define qualtype_type_(p) ((p)->car.DEB_QUALTYPE.type)
#define qualtype_next_(p) ((p)->car.DEB_QUALTYPE.nextqual)
#define qualtype_basetype_(p) ((p)->car.DEB_QUALTYPE.basetype)
#define qualtype_qualifiedtype_(p) ((p)->car.DEB_QUALTYPE.qualifiedtype)
#define qualtype_n_(p) ((p)->car.DEB_QUALTYPE.n)
#define qualtype_map_(p) ((p)->car.DEB_QUALTYPE.qualmap)
#define enum_qual_(p) ((p)->car.DEB_ENUM.qualtypes)
#define enum_name_(p) ((p)->car.DEB_ENUM.name)
#define enum_children_(p) ((p)->car.DEB_ENUM.children)
#define enum_container_(p) ((p)->car.DEB_ENUM.container)
#define enum_size_(p) ((p)->car.DEB_ENUM.size)
#define enumerator_name_(p) ((p)->car.DEB_ENUMERATOR.name)
#define enumerator_val_(p) ((p)->car.DEB_ENUMERATOR.val)
#define array_qual_(p) ((p)->car.DEB_ARRAY.qualtypes)
#define array_children_(p) ((p)->car.DEB_ARRAY.children)
#define array_size_(p) ((p)->car.DEB_ARRAY.size)
#define array_open_(p) ((p)->car.DEB_ARRAY.open)
#define array_basetype_(p) ((p)->car.DEB_ARRAY.basetype)
#define array_lowerbound_(p) ((p)->car.DEB_ARRAY.lowerbound)
#define array_upperbound_(p) ((p)->car.DEB_ARRAY.upperbound)
#define arraybound_open_(p) ((p)->car.DEB_ARRAYBOUND.open)
#define arraybound_upperbound_(p) ((p)->car.DEB_ARRAYBOUND.upperbound)
#define struct_qual_(p) ((p)->car.DEB_STRUCT.qualtypes)
#define struct_name_(p) ((p)->car.DEB_STRUCT.name)
#define struct_children_(p) ((p)->car.DEB_STRUCT.children)
#define struct_undefsort_(p) ((p)->car.DEB_STRUCT.undefsort)
#define struct_size_(p) ((p)->car.DEB_STRUCT.size)
#define struct_friends_(p) ((p)->car.DEB_STRUCT.friends)
#define member_name_(p) ((p)->car.DEB_MEMBER.name)
#define member_offset_(p) ((p)->car.DEB_MEMBER.offset)
#define member_type_(p) ((p)->car.DEB_MEMBER.type)
#define member_bsize_(p) ((p)->car.DEB_MEMBER.bsize)
#define member_boffset_(p) ((p)->car.DEB_MEMBER.boffset)
#define inherit_type_(p) ((p)->car.DEB_INHERIT.type)
#define inherit_offset_(p) ((p)->car.DEB_INHERIT.offset)
#define inherit_virt_(p) ((p)->car.DEB_INHERIT.virt)
#define startscope_next_(p) ((p)->car.DEB_STARTSCOPE.s.next)
#define startscope_codeaddr_(p) ((p)->car.DEB_STARTSCOPE.s.codeaddr)
#define startscope_children_(p) ((p)->car.DEB_STARTSCOPE.children)
#define startscope_end_(p) ((p)->car.DEB_STARTSCOPE.end)
#define startscope_codeseg_(p) ((p)->car.DEB_STARTSCOPE.codeseg)
#define endscope_next_(p) ((p)->car.DEB_ENDSCOPE.s.next)
#define endscope_codeaddr_(p) ((p)->car.DEB_ENDSCOPE.s.codeaddr)
#define null_parent_(p) ((p)->car.DEB_NULL.parent)
#define is_void_type_(t) \
(debsort_(t) == DW_TAG_base_type && basetype_typecode_(t) == FT_void)
#define high_pc_(p) endproc_endaddr_(proc_endproc_(p))
extern Dw_ItemList *dw_list, *dw_listproc;
extern Dw_ItemList *dw_basetypes;
typedef struct {
Uint index; /* of the file in filelist */
uint16 l;
uint16 column;
} Dw_FileLine;
typedef struct Dw_MacroList Dw_MacroList;
struct Dw_MacroList {
Dw_MacroList *cdr;
int sort;
Dw_FileLine fl;
union {
char const *s;
Uint i;
} data;
};
extern Dw_MacroList *dw_macrolist;
typedef struct Dw_LocList Dw_LocList;
struct Dw_LocList
{ Dw_LocList *cdr;
Binder *name;
int32 pos;
int32 size;
Dw_TypeRep *typeref;
};
extern Dw_LocList *dw_loclist;
/* Structs for buffering file/line co-ordinates. */
/* 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 Dw_FileCoord Dw_FileCoord;
typedef struct Dw_FileList Dw_FileList;
typedef struct Dw_PathList Dw_PathList;
struct Dw_PathList {
Dw_PathList *cdr;
Uint index;
size_t len;
char name[1];
};
struct Dw_FileList {
Dw_FileList *cdr;
char const *filename;
Uint index;
Uint lastline;
Dw_FileCoord *linelist;
Dw_PathList *dir;
uint32 timestamp;
uint32 filelength;
};
struct Dw_FileCoord {
Dw_FileCoord *cdr;
Dw_FileList *file; Dw_FileCoord *nextinfile;
uint16 line, col;
int32 codeaddr;
Symstr *codeseg;
};
extern struct Dw_BaseSeg {
Symstr *sym;
int32 len;
} dw_baseseg;
extern Dw_FileList *dw_filelist;
extern Dw_PathList *dw_pathlist;
/* The next two vars are (code order) list & tail pointer */
extern Dw_FileCoord *dw_coord_p, **dw_coord_q;
extern Dw_FileCoord dw_coord_sentinel;
extern int32 dw_mapped_codebase, dw_mapped_codep;
uint32 Dw_WriteInlineString(char const *s, uint32 offset);
uint32 Dw_WriteB(Uint u, uint32 offset);
uint32 Dw_WriteH(uint32 u, uint32 offset);
uint32 Dw_WriteW(uint32 u, uint32 offset);
uint32 Dw_WriteL(uint32 const *d, uint32 offset);
uint32 Dw_WriteBN(uint8 const *p, int32 n, uint32 offset);
extern DataXref *dw_xrefs;
DataXref *Dw_Relocate(DataXref *xrefs, int32 where, Symstr const *sym);
uint32 Dw_WriteW_Relocated(uint32 u, Symstr const *sym, uint32 offset);
char const *Dw_Unmangle(char const *s);
void Dw_1_WriteInfo(void);
void Dw_1_WriteLineinfo(void);
void Dw_2_WriteMacros(void);
void Dw_2_WriteInfo(void);
void Dw_2_WriteAbbrevs(void);
void Dw_2_WriteLineinfo(void);
|
stardot/ncc | tests/mathtest.h | /* 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$
*/
#ifndef mathtest_h
#define mathtest_h
typedef union double_ints
{
struct {long se_hi; unsigned long lo;} i;
double f;
} double_ints;
typedef union float_int
{
long sem;
float f;
} float_int;
#define EQFI(x, y) EQI((x).sem, (y).sem)
/* Bits to make up a NaN - set to anything non-zero */
extern unsigned long dnan_low, dnan_high, fnan;
extern void dset_to_qnan(double_ints *x);
extern void dset_to_snan(double_ints *x);
extern unsigned int disnan(double_ints *x);
extern void dset_to_inf(double_ints *x);
extern unsigned int disinf(double_ints *x);
extern void dset_to_one(double_ints *x);
extern void dset_to_mone(double_ints *x);
extern void dsucc(double_ints *a);
extern void dpred(double_ints *a);
extern void dneg(double_ints *a);
extern void fset_to_qnan(float_int *x);
extern void fset_to_snan(float_int *x);
extern unsigned int fisnan(float_int *x);
extern void fset_to_inf(float_int *x);
extern unsigned int fisinf(float_int *x);
extern void fset_to_one(float_int *x);
extern void fset_to_mone(float_int *x);
extern void fsucc(float_int *a);
extern void fpred(float_int *a);
extern void fneg(float_int *a);
/* return TRUE if there's been an IVO, and clear the flag */
extern unsigned int ivo(void);
/* Check for errno errors */
extern int get_errno(void);
#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif
#endif
|
stardot/ncc | armthumb/arminst.c | /*
* armthumb/arminst.c
* 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 "globals.h"
#include "armops.h"
#include "arminst.h"
#define ROR(x, n) (((x)<<(32-(n))) | ((((uint32)x)>>(n)) & ((1L<<(32-(n)))-1L)))
int32 Arm_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);
}
/* This is the ACN second attempt to produce sensible code to load */
/* integer values into ARM registers. */
/* /* There are too many different ways below to break up an integer into*/
/* 8-bit chunks. Rationalisation needed. */
int32 Arm_SplitForAdd(RealRegister r, int32 n, int32 *op) {
int32 tail = 0x3, mask = 0xff;
while ((n & tail)==0) tail = tail << 2, mask = mask << 2;
tail <<= 8;
if (r != R_SP && (n & mask) != mask) {
int32 bitsabove = (n & tail) == tail ? tail : 0;
int32 mask1 = mask, tail1 = tail;
for (; ; tail1 >>= 2, mask1 = ROR(mask1, 2)) {
bitsabove >>= 2;
if ((n & (tail1 >> 2)) != bitsabove) break;
}
if ((n & mask1 & 0xff000000) != 0)
mask = mask1, tail = tail1;
}
/*
* If the destination register is the stack pointer I decide on using
* an ADD or a SUB based on the sign of n. The effect should be to ensure
* that the stack pointer moves in a monotonic way, which is necessary if
* code is to be secure against asynchronous interrupts. For other
* destination registers it will sometimes be possible to generate
* tighter code by (e.g.) treating a + 0x1fffffff as a - 1 + 0x20000000.
*/
if ((r == R_SP && n < 0) ||
(r != R_SP && (n & tail) == tail)) {
*op = OP_SUBN;
return mask & -n;
} else {
*op = OP_ADDN;
return mask & n;
}
}
int32 *arm_add_integer(
RealRegister r1, RealRegister r2, int32 n, int32 scc,
RegisterContaining *cachelookup,
int32 *v)
{ /* Generate code for r1 = r2 + n. */
int32 packed;
if (n==0 && scc == 0) {
if (r1 != r2)
*v++ = (OP_MOVR | scc | F_RD(r1) | r2);
return v;
}
packed = Arm_EightBits(n);
if (packed >= 0)
{ *v++ = (OP_ADDN | scc | F_RD(r1) | F_RN(r2) | packed);
return v;
}
packed = Arm_EightBits(-n);
if (packed >= 0)
{ *v++ = (OP_SUBN | scc | F_RD(r1) | F_RN(r2) | packed);
return v;
}
if (cachelookup != NULL)
{ ValueDesc vd;
int rc = cachelookup(n, V_Negated+V_AnyShift, &vd);
if (rc != 0) {
int32 w = F_RD(r1) | F_RN(r2) | scc | vd.r | vd.op3.shift;
if (rc == V_Negated)
w |= OP_SUBR;
else
w |= OP_ADDR;
*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 arm_add_integer(r1, r1, n, scc, cachelookup, v);
}
}
/* End of armthumb/arminst.c */
|
stardot/ncc | util/datenow.c | <filename>util/datenow.c<gh_stars>0
/*
* Copyright (C) Advanced Risc Machines Ltd., 1991
* SPDX-Licence-Identifier: Apache-2.0
*/
#include <stdio.h>
#include <time.h>
int main(argc, argv)
int argc;
char *argv[];
{
char buf[32];
time_t now;
char *ct;
time(&now);
ct = ctime(&now);
sprintf(buf, "%.3s %.2s %.4s", ct+4, ct+8, ct+20);
if (argc ==2)
{ char *arg = argv[1];
if (arg[0] == '-')
{ if (arg[1] == 'h' || arg[1] == 'H')
{ printf("#define __DATE__ \"%s\"\n", buf);
printf("#define __TIME__ \"%.8s\"\n", ct+11);
}
else if (arg[1] == 0)
fputs(buf, stdout);
else
goto defolt;
return 0;
}
}
defolt:
printf("CurrentDate SETS \"%s\"\n", buf);
printf(" END\n");
return 0;
}
|
stardot/ncc | thumb/thmbpriv.h | /*
* C compiler file mcdpriv.h, version 1
* (Private interfaces within machine-dependent back end).
* Copyright (C) Acorn Computers Ltd., 1988, Codemist Ltd 1994
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
#ifndef __mcdpriv_h
#define __mcdpriv_h 1
#include "mcdep.h"
#ifndef JOPCODEDEF_ONLY
#include "codebuf.h"
#endif
#define P_RET 1
#define P_CMPZ 2
#define P_PRE 4 /* Used for pre-auto-index */
#define P_POST 8 /* Used for post-auto-index */
/* $$$$$ things definitely inapplicable to thumb removed */
#define P_BASEALIGNED 0x800
#define _a_read_r1 0x1
#define _a_read_r2 0x2
#define _a_read_r3 0x4
#define _a_read_r4 0x8
#define _a_set_r1 0x10
#define _a_set_r2 0x20
#define _a_modify_mem 0x40
#define _a_call 0x80
#define _a_regmask_r1 0x100
#define _a_regmask_r3 0x200
#define _a_gap_r1 0x400
#define _a_gap_r2 0x800
#define _a_read_mem 0x1000
extern struct JopTable a_joptable[];
#ifdef DEFINE_A_JOPTABLE
# if defined ENABLE_CG || defined ENABLE_REGS || defined ENABLE_CSE
# define a_with_bits(n, b) {n, b},
# else
# define a_with_bits(n, b) { b },
# endif
struct JopTable a_joptable[] = {
#else
# define a_with_bits(n, b)
#endif
#define a_attributes(op) (a_joptable[(op-J_LAST_JOPCODE-1) & J_TABLE_BITS].bits)
#ifndef THUMB_INLINE_ASSEMBLER
#define J_BICR (J_LAST_JOPCODE+1L)
a_with_bits("BICR", _a_read_r3+_a_read_r2+_a_set_r1)
#define J_LAST_A_JOPCODE J_BICR
#else
#define J_LAST_A_JOPCODE J_LAST_JOPCODE
#endif
#ifdef DEFINE_A_JOPTABLE
0
};
#endif
#ifndef JOPCODEDEF_ONLY
typedef struct { /* like struct Icode but with RealReg's and a peep field */
Icode ic;
int32 peep; /* opcode extension */
int32 dataflow;
int32 cond;
} PendingOp;
extern bool gen_pass;
extern int32 current_procnum;
extern List3 *label_values, *label_references;
void a_pr_jopcode(PendingOp *p);
extern char frameregnames[(16-9)*2];
/* register number -> name for sb (or v6), ip, fp, sl, sp
* (variable because dependent on calling standard
* in force). Also does lr and pc for simplicity.
*/
extern void setcallingstandard(char);
/* One of 'A', 'R', 'U', 'M', default set by compiler
* build, value alterable by configuration option.
*/
extern int32 pcs_flags;
/* Beware: these values are also written in the config tool */
#define PCS_CALLCHANGESPSR 1
#define PCS_FPE3 2
#define PCS_NOSTACKCHECK 4
#define PCS_REENTRANT 8
#define PCS_FPREGARGS 16 /* never in pcs_flags, only a pcs config value */
/* but mustn't overlap with pcs_flags bits */
#define PCS_NOFP 32
#define PCS_SOFTFP 64
#define PCS_INTERWORK 128
#define PCS_ACCESS_CONSTDATA_WITH_ADR 256
#define PCS_ZH_MASK 0xff /* options passed from driver via -zh argument */
/* excludes access_constdata_with_adr */
#ifndef PCS_DEFAULTS
# define PCS_DEFAULTS 0
#endif
#define localcg_debug(n) (debugging(DEBUG_LOCALCG) && (localcg_debugcount & (n)))
#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 MOVC_LOOP_THRESHOLD 24
extern int32 movc_workregs(const PendingOp *const p);
extern bool movc_preserving_r1r2(PendingOp *p, bool dead_r2);
extern int32 a_loads_r1(const PendingOp * const p);
extern int32 a_uses_r1(const PendingOp * const p);
extern int32 a_reads_r1(const PendingOp * const p);
extern int32 a_loads_r2(const PendingOp * const p);
extern int32 a_uses_r2(const PendingOp * const p);
extern int32 a_reads_r2(const PendingOp * const p);
extern int32 a_uses_r3(const PendingOp * const p);
extern int32 a_uses_r4(const PendingOp * const p);
extern int32 a_modifies_mem(const PendingOp * const p);
extern int32 a_uses_mem(const PendingOp * const p);
extern bool a_corrupts_r1(PendingOp const* p);
extern bool a_corrupts_r2(PendingOp const* p);
extern bool setspsr(const Icode * const ic);
typedef struct
{
uint32 use, def, corrupt, dead;
} RegisterUsage;
#define regs_in(u) ((u)->use)
#define regs_out(u) ((u)->def)
#define regs_corrupt(u) ((u)->corrupt)
#define regs_dead(u) ((u)->dead)
#define regs_read(u) ((u)->use)
#define regs_written(u) ((u)->def | (u)->corrupt)
#define regs_free(u) ((u)->corrupt | (u)->dead)
#define regs_used(u) ((u)->use | (u)->def | (u)->corrupt)
/* returns the complete register usage of c */
extern GetRegisterUsage(const PendingOp *c, RegisterUsage *u);
extern char *CheckJopcodeP(const PendingOp *p, CheckJopcode_flags flags);
extern int32 power_of_two(int32 n);
extern int32 regofregbit(int32 m);
extern void show_inst_direct(PendingOp *p);
extern void peephole_op(PendingOp *p, bool flush);
extern void peephole_reinit(void);
extern void peephole_init(void);
extern void peephole_tidy(void);
#ifdef TARGET_HAS_AOF
#define aof_fpreg xr_objflg1 /* fn passes FP args in FP registers */
#define aof_usessb xr_objflg2 /* defined fn 'uses' sb */
#define aof_leaf xr_objflg3 /* defined fn is a leaf */
extern Symstr *data_sym, *bss_sym, *adcon_sym;
typedef struct CommonDef {
struct CommonDef *next;
DataDesc data;
Symstr *name;
int index;
int32 refsize;
int32 stringpos;
} CommonDef;
extern CommonDef *commondefs;
#else
#define aof_fpreg 0 /* fn passes FP args in FP registers */
#define aof_usessb 0 /* defined fn 'uses' sb */
#define aof_leaf 0 /* defined fn is a leaf */
#endif
extern DataDesc adconpool;
extern Symstr *adconpool_lab;
extern int adconpool_find(int32 w, int32 flavour, Symstr *sym);
extern void adconpool_flush(void);
extern void adconpool_init(void);
void localcg_endcode(void);
extern int integer_load_max;
extern int ldm_regs_max;
void target_lib_variant(char *b);
#endif /* JOPCODEDEDEF_ONLY */
#endif
/* end of thumb/mcdpriv.h */
|
stardot/ncc | cfe/pp.h | /*
* C pre-processor, cfe/pp.h:
* 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$
* Checkin $Date$
* Revising $Author$
*/
#ifndef _pp_h
#define _pp_h
#ifndef _defs_LOADED
# include "defs.h"
#endif
/*
* Joint C/Pascal/F77 pre-processor.
* The pre-processor is essentially to ANSI Draft Standard for C, but
* with pcc (cpp) compatibility which can be turned on at run-time.
* Language specifics are configured in pp.c and are in flux. Note that
* in pcc-C, Pascal, and Fortran, pre-processing directives are recognised
* only if the '#' is in column 1. Currently, no macro-replacement is
* done in Pascal or Fortran.
*/
/* @@@ L_QUOT is not used in C and it is far from clear that pp.h ought */
/* to be exporting it anyway! */
#ifdef PASCAL /*ECN*/
#define L_QUOT '\''
#else
#define L_QUOT '\"'
#endif
extern int pp_inhashif; /* 0 => not evaluating a #if <const-expr> */
/* 1 => evaluating such 'for real' */
/* 2 => evaluating such in skipped text */
#ifndef NO_LISTING_OUTPUT
/*
* @@@ LDS. Currently this stuff defies explanation. HELP please!
*/
extern bool list_this_file;
extern bool map_init(FILE *mapstream);
#endif
#define PP_EOF (-256) /* Can't be confused with a signed/unsigned char */
extern int pp_nextchar(void);
/*
* Return the next character from the input, after processing #includes,
* #ifxxxs, macro-replacements and (other than for Fortran) comment removal.
* Return PP_EOF at end of file.
*/
extern void pp_predefine(char *s);
/*
* Define the pre-processor symbol 's' to be 1.
*/
extern void pp_preundefine(char *s);
/*
* Remove any built-in definition of pre-processor symbol 's'.
*/
extern void pp_tidyup(void);
/*
* A finalisation procedure for the pre-processor.
* If feature PP_NOUSE is enabled then unused pre-processor macros are
* reported on. If listing output is enabled and there is an open listing
* file then the listing file is finalised (but not closed). If pre-processor
* debugging is enabled (ENABLE_PP) then summary statistics are output.
*/
extern void pp_init(FileLine *fl);
/*
* Initialise the preprocessor, which has to be done AFTER initialising the
* storage manager. The builtinn pre-defines are manufactured at this instant
* too (e.g. __DATE__ and __TIME__). Effectively, this is called once for each
* file named on the compiler's command line.
*/
extern void pp_notesource(char const *filename, FILE *stream, bool preinclude);
/*
* Called before processing a pre-included file or
* before each top-level file.
*/
extern void pp_push_include(char const *fname, int lquote, FileLine fl);
/*
* Support for other languages such as F77. 'fname' is the name of a file
* to continue reading from; lquote is assumed to be one of <, " or '.
* The matching rquote is computes as lquote == '<' ? '>' : lquote.
*/
typedef struct pp_uncompression_record pp_uncompression_record;
#ifndef NO_INSTORE_FILES
extern FILE *open_builtin_header(const char *name,
pp_uncompression_record **urp);
/*
* Return a stream to a builtin header file and whether the file was opened
* as a system file or not.
*/
#endif
/*
* The following functions are defined by pp but are implemented elsewhere -
* currently in mip/compiler.c. Thus they are part of pp's interface.
*/
extern FILE *pp_inclopen(char const *name, bool is_system,
pp_uncompression_record **urp, char const **filename, FileLine fl);
/*
* Open the file called 'name'; is_system is true if the source form is
* <file> rather than "file".
* Returns: the opened file;
* system = is_system && file found on the system search path;
* filename = the host name of the opened file.
*/
extern void pp_inclclose(FileLine fl);
/*
* Close and adjust the search path.
*/
FILE *new_compressed_header(FILE *f, pp_uncompression_record **urp);
#ifdef FORTRAN
extern void pp_pop_include(void);
#endif
typedef struct PragmaSpelling
{
char const *name;
short int code;
#ifdef FORTRAN
int32 value; /* see values below */
#else
short int value;
#endif
} PragmaSpelling;
PragmaSpelling const *keyword_pragma(char const *name, bool *negp);
void pp_copy(void);
#endif
/* end of cfe/pp.h */
|
stardot/ncc | cppfe/overload.c | <filename>cppfe/overload.c
/*
* overload.c: semantic analysis phase of C++ compiler
* Copyright (C) Codemist Ltd, 1991
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$ Codemist 11
* Checkin $Date$
* Revising $Author$
*/
/* The file is logically part of sem.c, and imported by it and syn.c */
/* It is (intended to be) only used by C++ extensions of C. */
#include <string.h> /* for strncpy */
#include <ctype.h> /* for isdigit */
#include <stdlib.h> /* for atoi */
#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 "simplify.h"
/* the following avoids warning for AEops being 'long' (why are they?) */
/* ... probably to guarantee storage layout if sizeof(int)==2. */
#define E3(a,b,c) { a, (int)b, (int)c}
#define E2(a,b) { a, (int)b, 0}
static struct { char name[6]; unsigned char op,op2; } opnametab[] =
{ /* ordering matches aeops.h, not [ES] random(?) order */
E2( "__aa", s_andand ),
E2( "__cm", s_comma ),
E2( "__oo", s_oror ),
E2( "__eq", s_equalequal ),
E2( "__ne", s_notequal ),
E2( "__gt", s_greater ),
E2( "__ge", s_greaterequal ),
E2( "__lt", s_less ),
E2( "__le", s_lessequal ),
E3( "__ad", s_and, s_addrof ), /* type disambiguates */
E3( "__ml", s_times, s_content ), /* type disambiguates */
E3( "__pl", s_plus, s_monplus ), /* type disambiguates */
E3( "__mi", s_minus, s_neg ), /* type disambiguates */
E2( "__dv", s_div ),
E2( "__ls", s_leftshift ),
E2( "__or", s_or ),
E2( "__md", s_rem ),
E2( "__rs", s_rightshift ),
E2( "__er", s_xor ),
E2( "__aad", s_andequal ),
E2( "__aml", s_timesequal ),
E2( "__apl", s_plusequal ),
E2( "__ami", s_minusequal ),
E2( "__adv", s_divequal ),
E2( "__als", s_leftshiftequal ),
E2( "__aor", s_orequal ),
E2( "__amd", s_remequal ),
E2( "__ars", s_rightshiftequal ),
E2( "__aer", s_xorequal ),
E2( "__as", s_assign ),
E2( "__co", s_bitnot ),
E2( "__nt", s_boolnot ),
E3( "__pp", s_plusplus, s_postinc ), /* type disambiguates */
E3( "__mm", s_minusminus, s_postdec ), /* type disambiguates */
E2( "__rf", s_arrow ),
E2( "__rm", s_arrowstar ),
/* now the specials, not fully done... */
E2( "__cl", s_fnap ),
E2( "__vc", s_subscript ),
E2( "__ct", s_ctor ),
E2( "__dt", s_dtor ),
E2( "__nw", s_new ),
E2( "__dl", s_delete ),
E2( "__op", /* s_typespec */0 )
};
Symstr *operator_name(AEop op)
{ /* Linear search suffices (hmm) since operator is rare? */
/* Similarly look up in hash table as if name read each time. */
/* Maybe add to bind.c(sym_name_table) */
unsigned int i;
for (i = 0; i < sizeof(opnametab)/sizeof(opnametab[0]); i++)
if (op == opnametab[i].op || op == opnametab[i].op2)
return sym_insert_id(opnametab[i].name);
cc_err(syn_err_illegal_operator, op);
return sym_insert_id("__bad_operator_name");
}
bool is_operator_name(Symstr *opname)
{ unsigned int i;
for (i = 0; i < sizeof(opnametab)/sizeof(opnametab[0]); i++)
if (strcmp(symname_(opname), opnametab[i].name) == 0)
return YES;
return NO;
}
static char *spr_int(int32 n, char *p, char *q)
{ char v[20], *s;
sprintf(v, "%ld", (long)n);
if (v[0] == '-') v[0] = 'n'; /* that's what cfront does */
for (s = v; p != q && *s;) *p++ = *s++;
return p;
}
#define stuffsig_(ch) { if (p != q) *p++ = (ch); }
static char *spr_class(TagBinder *b, unsigned n, char *p, char *q)
{ if (n > 9) syserr("10 nested classes/loop");
else if (b == 0)
{ if (n > 1)
{ stuffsig_('Q')
stuffsig_(n + '0')
}
}
else
{ char *s = symname_(bindsym_(b));
/* Print parents out ancestor-first. */
p = spr_class(b->tagparent, n+1, p, q);
p = spr_int((int32)strlen(s), p, q);
while (p != q && *s) *p++ = *s++;
}
return p;
}
static char *spr_binder(Binder *b, char *p, char *q)
{ char *s = symname_(bindsym_(b));
while (p != q && *s) *p++ = *s++;
return p;
}
static char *type_pos[256];
static int type_pos_index;
static bool isPtrToFn(TypeExpr *t)
{
t = princtype(t);
return h0_(t) == s_content && isfntype(typearg_(t));
}
/* still to do qualifiers const/vol/signed/unsigned */
static char *type_signature1(TypeExpr *t, char *p, char *q, bool skiptop)
{ SET_BITMAP m;
int a_type_declarator = 0;
Binder *unknown_tag = NULL;
SET_BITMAP quals_unknown = 0;
for (; ; t = typearg_(t)) {
if (type_pos_index == 255) syserr("type_pos out of bound");
/* a_type_declarator is possibly a misnomer, it's used to indicate
whether or not the following type pos should be remembered.
*/
if (skiptop == 0 && !a_type_declarator) type_pos[type_pos_index++] = p;
if (h0_(t) == s_typespec &&
typespecmap_(t) & bitoftype_(s_typedefname) && istypevar(t))
{ unknown_tag = typespecbind_(t);
quals_unknown = typespecmap_(t);
}
switch (t = prunetype(t), h0_(t))
{
case s_typespec:
a_type_declarator = 0;
m = typespecmap_(t);
/* N.B. perhaps we should omit const/volatile for fn args, since */
/* int f(int) and int f(const int) are compatible. */
/* (I.e. const/volatile in args is not part of the fn type.) */
/* BUT!!! [ES, p122] contradicts this (accidentally?). */
if (m & bitoftype_(s_const)) stuffsig_('C')
/* remember 'signed int' == 'int', so omit for int (but not char). */
if (m & bitoftype_(s_signed) &&
m & bitoftype_(s_char)) stuffsig_('S')
if (m & bitoftype_(s_unsigned)) stuffsig_('U')
if (m & bitoftype_(s_volatile)) stuffsig_('V')
switch (m & -m)
{
case bitoftype_(s_bool):
stuffsig_('b'); break;
case bitoftype_(s_char):
stuffsig_('c'); break;
case bitoftype_(s_int):
stuffsig_(int_islonglong_(m) ? 'x' :
m & bitoftype_(s_short) ? 's' :
m & bitoftype_(s_long) ? 'l' : 'i'); break;
case bitoftype_(s_double):
stuffsig_(m & bitoftype_(s_short) ? 'f' :
m & bitoftype_(s_long) ? 'r' : 'd'); break;
case bitoftype_(s_void):
stuffsig_('v'); break;
case bitoftype_(s_struct):
case bitoftype_(s_class):
case bitoftype_(s_union):
case bitoftype_(s_enum):
p = spr_class(typespectagbind_(t), 0, p, q);
break;
default: goto defolt;
}
return p;
default:
defolt: stuffsig_('!');
return p;
case t_unknown:
if (!unknown_tag) syserr("Unknown type id!!");
if (quals_unknown)
{ if (quals_unknown & bitoftype_(s_const)) stuffsig_('C');
if (quals_unknown & bitoftype_(s_volatile)) stuffsig_('V');
}
p = spr_int((int32)strlen(symname_(bindsym_(unknown_tag))), p, q);
p = spr_binder(unknown_tag, p, q);
a_type_declarator = 0;
return p;
case t_subscript:
{ Expr *subsz = typesubsize_(t);
stuffsig_('A');
/* Hmmm, can't use is_template_arg_binder() here. Wrong scope. */
p = spr_int((subsz == 0 || h0_(subsz) == s_binder ||
(h0_(subsz) == s_cast && h0_(arg1_(subsz)) == s_binder)) ? 0 :
evaluate(subsz), p, q);
stuffsig_('_');
a_type_declarator = 1;
break;
}
case t_content:
if (typeptrmap_(t) & bitoftype_(s_const)) stuffsig_('C')
if (typeptrmap_(t) & bitoftype_(s_volatile)) stuffsig_('V')
if (h0_(typearg_(t)) == t_coloncolon)
{ t = typearg_(t);
stuffsig_('M');
p = spr_class(typespectagbind_(t), 0, p, q);
}
else
stuffsig_('P');
a_type_declarator = 1;
break;
case t_ref:
stuffsig_('R');
a_type_declarator = 1;
break;
case t_fnap:
/* We prefix a function type with its qualifiers so that */
/* "int f() const;" becomes f__CFv. This is compatible with [ES] but */
/* not defined there. Such a scheme is vital for member fns [ES,p321]. */
/* Maybe put on the implicit 'this' type on b_impl implementations? */
if (typeptrmap_(t) & bitoftype_(s_const)) stuffsig_('C')
if (typeptrmap_(t) & bitoftype_(s_volatile)) stuffsig_('V')
stuffsig_('F');
{ FormTypeList *l = typefnargs_(t);
/* [ES] ambiguity: does f(...) map to f__Fe or f__Fve? Former here. */
if (l == NULL && !fntypeisvariadic(t))
{ type_pos[type_pos_index++] = p;
stuffsig_('v')
}
else for (; l != NULL; l = cdr_(l))
p = type_signature1(l->fttype, p, q, 0);
if (fntypeisvariadic(t)) stuffsig_('e');
}
if (skiptop) return p;
stuffsig_('_');
a_type_declarator = (isPtrToFn(typearg_(t))) ? 0 : 1;
break;
}
}
}
typedef struct {int m, w; const unsigned char *cptr;} TT;
static TT folds(const unsigned char *rptr)
{
TT tt;
char tmp[2];
int n1;
tmp[1] = '\0';
tmp[0] = *rptr++;
n1 = atoi(tmp);
tt.m = 1;
tt.w = n1;
tt.cptr = rptr;
while (*rptr == 'T' && isdigit(*(rptr + 1)))
{ int n2;
tmp[0] = *++rptr;
n2 = atoi(tmp);
if (n1 == n2)
{ tt.m++;
tt.cptr = ++rptr;
} else
break;
}
return tt;
}
static int isPFtype(char *t)
{ int ptr = 0;
while (*t == 'P') (ptr++, t++);
/* PPF is considered a PF type */
return (*t == 'F' && ptr) ? (ptr - 1) : -1;
}
static int type_len(int index, int upb, char *begin, char *end, char *tp[])
{ int res = ((index + 1 != upb) ? tp[index + 1] : end) - begin;
return res;
}
struct PFtypes {
char *type_pos[256];
int type_pos_index;
struct PFtypes *next;
};
typedef struct PFtypes PFtypes;
static PFtypes *pftypes;
/* This can only be called in a PF in PF context */
static int pf_upb(int i, char *tp[], int upb)
{
char *t = tp[i++];
char *res = strchr(t, '_');
int start = i;
while (i < upb && tp[i] < res) ++i;
return i - start;
}
/* remove all PF relative types, returns adjusted upper bound */
static int PF_reduction(int upb, char*tp[])
{ int i = 0;
while (i < upb)
{ char *cur_type = tp[i];
if (isPFtype(cur_type) >= 0)
{ int where, displacement, w;
char *res = strchr(cur_type, '_'); /* warning: just a hint */
PFtypes *pft = (PFtypes *)SynAlloc(sizeof(PFtypes));
if (pftypes == 0)
pftypes = pft;
else
{ PFtypes *pptr = pftypes;
while (pptr->next != 0) pptr = pptr->next;
pptr->next = pft;
}
w = where = ++i;
pft->next = (PFtypes *)0;
pft->type_pos_index = 0;
while (i < upb && tp[i] < res)
{ char *t = tp[i];
if (pft->type_pos_index == 255) syserr("type_pos out of bound");
pft->type_pos[pft->type_pos_index++] = t;
if (isPFtype(t) >= 0)
{ int lupb = pf_upb(i, tp, upb), tmp;
tmp = PF_reduction(lupb + 1, &tp[i]);
i += lupb + 1;
/* re-adjust res */
res = strchr(tp[i], '_');
} else
i++;
}
displacement = i - where;
for(; i < upb;) tp[where++] = tp[i++];
upb -= displacement;
i = w;
}
else
++i;
}
return upb;
}
#define stuff_buf_(t, l) {int _tmp = l; char *_tmpt = t; \
while (_tmp-- && (buf < end)) *buf++ = *_tmpt++; *buf=0;}
#define stuff_buf_T_(n) {int _tmp = n; *buf++ = 'T'; \
buf = spr_int(_tmp, buf, end); *buf=0;}
static char *N_reduction(const unsigned char*, char*, char*, char*);
static char *T_reduction(int upb, char *tp[], char* tend, char *buf, char *end)
{
int i = 0;
while (i < upb)
{ int j = 0, done = 0, len, nptrs;
char *cur_type = tp[i], *t;
len = type_len(i, upb, cur_type, tend, tp);
while ((t = tp[j]) < cur_type && !done && j < 9)
{ int tlen = type_len(j++, upb, t, tend, tp);
if (strncmp(t, cur_type, tlen) == 0)
{ int res_len = len - tlen;
stuff_buf_T_(j);
if (res_len > 0)
{ cur_type += tlen;
stuff_buf_(cur_type, res_len);
}
done = 1;
}
}
if (!done)
{ if ((nptrs = isPFtype(cur_type)) >= 0)
{ char *PF = "PF", *P = "P";
char lbuffer[256], *lbuf;
PFtypes *lpft;
while (nptrs--) stuff_buf_(P, 1);
stuff_buf_(PF, 2)
if (!pftypes) syserr("T_reduction: empty pftyes");
lpft = pftypes; pftypes = pftypes->next;
lbuf = T_reduction(lpft->type_pos_index, lpft->type_pos,
(i + 1 != upb) ? tp[i+1] : tend,
lbuffer, lbuffer + sizeof lbuffer);
buf = N_reduction((const unsigned char *)lbuffer, lbuf, buf, end);
}
else
stuff_buf_(cur_type, len);
}
++i;
}
return buf;
}
static char *N_reduction(const unsigned char *rptr, char *buf, char *wptr, char *end)
{
while (rptr < (const unsigned char *)buf)
{ if (*rptr == 'T' && isdigit(*(rptr + 1)))
{ TT t = folds(rptr + 1);
if (t.m > 1)
{ int m = t.m;
while (m > 9)
{ *wptr++ = 'N';
wptr = spr_int(9, wptr, end);
wptr = spr_int(t.w, wptr, end);
m -= 9;
}
if (m != 0)
{ *wptr++ = (m == 1) ? 'T' : 'N';
if (m != 1) wptr = spr_int(m, wptr, end);
wptr = spr_int(t.w, wptr, end);
rptr = t.cptr;
}
} else
{ *wptr++ = 'T';
wptr = spr_int(t.w, wptr, end);
rptr = t.cptr;
}
} else
*wptr++ = *rptr++;
}
return wptr;
}
static char *type_signature(TypeExpr *t, char *p, char *q, bool skiptop)
{ type_pos_index = 0;
p = type_signature1(t, p, q, skiptop);
if (type_pos_index <= 1)
return p;
else
{ char T_buffer[256], *buf;
pftypes = 0;
type_pos_index = PF_reduction(type_pos_index, type_pos);
if (!type_pos_index) return p;
buf = T_reduction(type_pos_index, type_pos, p,
T_buffer, T_buffer + sizeof T_buffer);
return N_reduction((const unsigned char *)T_buffer, buf, type_pos[0], q);
}
}
static char *value_signature(Expr *e, char *p, char *q)
{ if (h0_(e) == s_cast) e = arg1_(e);
stuffsig_('X');
/* cfront adds the type of the parameter here (why?). */
/* (and it uses a different encoding of values). */
switch (h0_(e)) {
case s_integer:
p = spr_int(intval_(e), p, q); /* use evaluate(e)? */
break;
case s_content:
case s_addrof:
e = arg1_(e);
/* @@@ fix the next line */
if (h0_(e) != s_binder)
goto defolt;
case s_binder:
{ Binder *b = exb_(e);
p = spr_binder(b, p, q); /*/* what if binder contains a 'Y'?*/
break;
}
defolt:
default:
stuffsig_('?');
}
stuffsig_('Y');
return p;
}
static const char tmpt_encoding[] = "__t";
#define tmpt_encoding_length 3
static const char tmpt_fn_encoding[] = "__tF";
#define tmpt_fn_encoding_length 4
static const char tmpt_fn_targs_encoding[] = "_<";
#define tmpt_fn_targs_encoding_length 2
#define OVLD_TEMP_FUNC_NAME_SIZE 128
Symstr *ovld_function_template_name(Symstr *sv, TypeExpr *t)
{ char v[OVLD_TEMP_FUNC_NAME_SIZE*2], *p, *q; /* RW uses very long param names */
size_t namelen = strlen(symname_(sv));
if (!isfntype(t)) syserr("Fn type expected, $t instead", t);
if (sizeof(v) - tmpt_encoding_length - 1 < namelen)
syserr("name is too long to encode template args: '%s'", symname_(sv));
strcpy(v, symname_(sv)); strcpy(v + namelen, tmpt_encoding);
p = v+namelen+tmpt_encoding_length; q = v+sizeof(v)-1;
p = type_signature(t, p, q, 1);
/* DWP Oct95 required return type as well */
if (p < q)
*p++ = '_';
p = type_signature(typearg_(t), p, q, 0);
*p = 0;
return sym_insert_id(v);
}
Symstr *ovld_tmptfn_instance_name(Symstr *sv, ScopeSaver f)
{ char v[OVLD_TEMP_FUNC_NAME_SIZE], *p, *q;
size_t namelen = strlen(symname_(sv));
if (sizeof(v) - tmpt_fn_targs_encoding_length - 2 < namelen)
syserr("name is too long to encode template args: '%s'", symname_(sv));
strcpy(v, symname_(sv)); strcpy(v + namelen, tmpt_fn_targs_encoding);
p = v+namelen+tmpt_fn_targs_encoding_length; q = v+sizeof(v)-2;
for (; f != NULL; f = bindcdr_(f))
if (bindconst_(f) != NULL)
p = value_signature(bindconst_(f), p, q);
else
p = type_signature(h0_(bindtype_(f)) == t_unknown ?
primtype2_(bitoftype_(s_typedefname), f) : princtype(bindtype_(f)),
p, q, 0);
*p++ = '>', *p = 0;
return sym_insert_id(v);
}
Symstr *specialized_name_of(TagBinder *tmptb)
{ ScopeSaver f = tagformals_(tmptb);
char v[128], *p, *q;
size_t namelen = strlen(symname_(bindsym_(tmptb)));
if (sizeof(v) - tmpt_encoding_length - 1 < namelen)
syserr("name is too long to specialize: '%s'", symname_(bindsym_(tmptb)));
strcpy(v, symname_(bindsym_(tmptb))); strcpy(v + namelen, tmpt_encoding);
p = v+namelen+tmpt_encoding_length; q = v+sizeof(v)-1;
for(; f != NULL; f = bindcdr_(f))
{ if (h0_(bindtype_(f)) == t_unknown)
p = type_signature(primtype2_(bitoftype_(s_typedefname), f), p, q, 0);
else
p = value_signature((Expr *)f, p, q);
}
*p = 0;
return sym_insert_id(v);
}
Symstr *ovld_template_app(Symstr *sv, ScopeSaver f, ExprList *a)
{ char v[128], *p, *q;
Binder *tactualp = NULL, *tactualq = NULL;
int template_paras = env_size(f), template_args = 0;
strcpy(v, symname_(sv)); strcat(v, tmpt_encoding);
p = v+strlen(v); q = v+sizeof(v)-1;
for (; f != NULL; f = bindcdr_(f))
{ Expr *e = (a && exprcar_(a)) ? exprcar_(a) : bindconst_(f);
Binder *temp;
/* Note use of s_typespec for a 'type' template actual. */
if (!e) {
cc_err(sem_err_type_arg_expected);
/* should return a qualified sv to suppress further diagnostics. */
return sv;
}
temp = mk_binder(bindsym_(f), bindstg_(f), bindtype_(f));
if (!tactualp)
tactualp = tactualq = temp;
else
bindcdr_(tactualq) = temp, tactualq = temp;
if (h0_(bindtype_(f)) == t_unknown)
{
if (h0_(e) != s_typespec ||
(typespecmap_(bindtype_(f)) && !istypevar(type_(e)) &&
!(typespecmap_(bindtype_(f)) &
typespecmap_(princtype(type_(e))))))
{ cc_err(sem_err_typeclash_1, typespecmap_(bindtype_(f)),
typespecmap_(princtype(typeofexpr(e))));
/* @@@ return a qualified sv to suppress further diagnostics */
return sv;
}
if (h0_(type_(e)) == t_unknown)
syserr("ovld_template_app: bare t_unknown");
if (istypevar(type_(e)) &&
bindsym_(f) == bindsym_(typespecbind_(type_(e))))
{ template_args++;
binduses_(typespecbind_(type_(e))) |= u_referenced;
}
bindtype_(temp) = type_(e);
if (e && h0_(e) == s_typespec && e == bindconst_(f) &&
istypevar(bindtype_(temp)))
{ bindtype_(temp) = clone_typeexpr(bindtype_(temp));
fixup_template_arg_type(bindtype_(temp), tactualp);
}
p = type_signature(bindtype_(temp), p, q, 0);
} else if (isclasstype_(bindtype_(f)) &&
tagbindbits_(typespectagbind_(bindtype_(f))) & TB_TEMPLATE)
{ TypeExpr *argtype = princtype(type_(e));
TagBinder *arg = NULL;
if (h0_(e) != s_typespec ||
!isclasstype_(argtype) ||
!(tagbindbits_(arg = typespectagbind_(princtype(type_(e)))) & TB_TEMPLATE) ||
!comparable_templates(typespectagbind_(bindtype_(f)), arg))
{ if (h0_(e) != s_typespec)
cc_err(sem_err_typeclash_2, e);
else
cc_err(sem_err_typeclash_3, argtype);
return sv;
}
bindtype_(temp) = type_(e);
p = type_signature(bindtype_(temp), p, q, 0);
} else {
if (h0_(princtype(bindtype_(f))) == t_ref && !issimplelvalue(e))
{ cc_err(sem_err_lvalue_needed);
return sv;
}
bindtype_(temp) = clone_typeexpr(bindtype_(f));
fixup_template_arg_type(bindtype_(temp), tactualp);
/* The reason for the next line: consider,
template <class T, T x> struct X {};
X<double, 1> x;
*/
if (isprimtypein_(princtype(bindtype_(temp)),
bitoftype_(s_double)|bitoftype_(s_float)))
{ cc_err(sem_err_temp_type_float);
return sv;
}
e = mkcast(s_template, e, widen_formaltype(bindtype_(temp)));
if (h0_(e) == s_error || h0_(e) == s_typespec)
return sv;
e = optimise0(e);
if ((p = value_signature(e, p, q)) == 0) return sv;
if (h0_(e) == s_binder && bindsym_(f) == bindsym_(exb_(e)))
{ template_args++;
binduses_(exb_(e)) |= u_referenced;
}
if (a)
exprcar_(a) = e;
#if NEVER
else
bindconst_(f) = e;
#endif
}
if (a) a = cdr_(a);
}
*p = 0;
if (a)
cc_warn(syn_rerr_extra_template_actuals);
return (template_paras == template_args) ? sv : sym_insert_id(v);
}
Symstr *conversion_name(TypeExpr *t)
{ char v[128];
strcpy(v, "__op");
*type_signature(t, v+4, v+127, 0) = 0;
return sym_insert_id(v);
}
String *exception_name(TypeExpr *t)
{ StringSegList *s;
char v[128], *p = v, *q = type_signature(t, v, v+127, 0);
*q = 0;
if (*p == 'C') p++;
if (*p == 'V') p++; /* lose const/volatile */
if (*p == 'R') p++; /* *then* lose t_ref */
/* We maybe should also save the strings corresponding to base classes */
/* for the implicit coercions. */
{ size_t n = q - p;
/* See syn.c(rd_ANSIstring) for the following comment. */
/* Note that the list of string segments must last longer than most */
/* other parts of the parse tree, hence use binder_list3() here. */
char *w = (char *)BindAlloc(n);
if (n != 0) memcpy(w, p, n);
s = (StringSegList *)binder_list3(0, w, n);
}
return (String *)syn_list2(s_string, s);
}
Symstr *ovld_add_memclass(Symstr *sv, TagBinder *scope, bool staticfn)
{ char v[128], *p = v, *q = v+127;
const char *s = symname_(sv);
/* This function is a hack to add type scope to top-level forms of */
/* member functions which have already been overload-disambiguated */
/* but only within class scopes. E.g. f -> f__v -> f__3FOOv. */
/* (It is nasty in case user names have '__' within.) */
/* ^^^No more!!! */
/* It also turns class A { static int x; } into x__1A. */
char *x;
for (; *s == '_'; s++) stuffsig_(*s) /* copy leading '_'s */
for (x = strstr(s, tmpt_fn_encoding);
x != NULL;
x = strstr(x, tmpt_fn_encoding))
{ x += tmpt_fn_encoding_length;
for (; s < x; s++) stuffsig_(*s)
}
for (; *s != 0; s++)
{ if (s[0] == '_' && s[1] == '_') { s += 2; break; }
stuffsig_(*s)
}
/* syserr here if *s = '\0' ? */
stuffsig_('_')
stuffsig_('_')
p = spr_class(scope, 0, p, q);
/* The next line attempts to interpolate between [ES] and CFront: */
/* class A { static int x, f(); int g(); }; */
/* x__1A, f__1ASFv, g__1AFv. */
/* Although [ES] don't use 'S' here, it clearly adds to safety. */
if (staticfn) stuffsig_('S')
for (; *s != 0; s++) stuffsig_(*s)
*p = 0;
return sym_insert_id(v);
}
Symstr *ovld_instance_name_1(const char *name, TypeExpr *t)
{ char v[1024], *p;
/* @@@ Nasty hack: class member fns get the arg types added to their */
/* names for overload resolution within classes. It is convenient to */
/* add their class-name also (since this will give the external name). */
/* However, this must be up for review w.r.t. */
/* typedef { int f(),f(int); } t; */
/* which is a curio (possibly unreasonably so) in which we don't know */
/* the class-name until after the overloaded def has been made. */
/* We should probably also beware (at top-level) */
/* T::typedefname f(); */
/* i.e. check the scope of T. */
/* @@@ the above comment is suspended! */
/* TagBinder *scope = current_member_scope(); */
size_t namelen = strlen(name);
if (sizeof(v) - 3 < namelen)
syserr("name too long to mangle: '%s'", name);
strcpy(v, name); strcpy(v + namelen, "__");
p = v+namelen+2;
/* if (scope) p = spr_class(scope, p, v+127); */
/* @@@ remember here things like "int f() const {}"... */
*type_signature(t, p, v+sizeof(v)-1, 1) = 0;
{ Symstr *sv = sym_insert_id(v);
return sv;
}
}
Symstr *ovld_instance_name(Symstr *sv, TypeExpr *t)
{ Symstr *sv2 = ovld_instance_name_1(symname_(sv), t);
if (sv == sv2) syserr("ovld_instance_name");
return sv2;
}
static void chk_ovld_access(Binder *bm)
{ if (bindparent_(bm) != 0)
{ accessOK &= ~1;
check_access((ClassMember *)bm, 0);
if (accessOK == 0)
diagnose_access(bindsym_(bm), bindparent_(bm));
}
}
/* This needs merging with a more-general mechanism for "t p = &f;". */
Expr *ovld_picknullary(Binder *bgeneric)
{ TypeExpr *t = bindtype_(bgeneric);
BindList *bl;
if (h0_(t) != t_ovld) syserr("ovld_picktype");
for (bl = typeovldlist_(t); bl; bl = cdr_(bl))
{ Binder *b = bl->bindlistcar;
TypeExpr *t = princtype(bindtype_(b));
if (h0_(t) == t_fnap && typefnargs_(t) == NULL)
{ chk_ovld_access(b);
if (bindstg_(b) & b_impl) b = realbinder_(b);
return mkunary(s_addrof, (Expr *)b);
}
}
return 0;
}
typedef struct TypeList TypeList;
struct TypeList {
TypeList *cdr;
TypeExpr *tltype;
};
/* add a type to a list of unique types... really a set of types */
static TypeList *mk_typelist(TypeList *tlp, TypeExpr *tltype)
{ TypeList *l;
for (l = tlp; l != 0; l = cdr_(l))
if (equivtype(tltype, l->tltype)) return tlp;
return (TypeList *)syn_cons2(tlp, tltype);
}
/* here we just find the set of all convfn types... filter later */
/* assume t has been princtype'd by the caller... */
static TypeList *convtypes_of_class(TypeExpr *t, TypeList *tl)
{ TagBinder *b = typespectagbind_(t);
ClassMember *l;
for (l = tagbindmems_(b); l != 0; l = memcdr_(l))
{ if (attributes_(l) & (CB_CORE|CB_BASE|CB_VBASE))
tl = convtypes_of_class(memtype_(l), tl);
else if ((attributes_(l) & CB_TCONV) && (bindstg_(l) && b_impl))
/* Assert: h0_(bindype_(l)) is t_fnap... */
tl = mk_typelist(tl, typearg_(bindtype_(l)));
}
return tl;
}
Expr *allowable_boolean_conversion(Expr *e)
{
TypeExpr *cvntype = NULL, *t = princtype(typeofexpr(e));
TypeList *convtypes = convtypes_of_class(t, NULL);
TagBinder *cla = typespectagbind_(t);
int conv_nmatch = 0;
for (; convtypes != NULL;
convtypes = (TypeList *)discard2(convtypes))
{ t = convtypes->tltype;
if (isprimtype_(t, s_bool)) {conv_nmatch = 1; cvntype = t; break;}
if (h0_(t) == t_content || (h0_(t) == s_typespec &&
!(typespecmap_(t) & bitoftype_(s_void)) &&
!(typespecmap_(t) & ENUMORCLASSBITS)))
{ conv_nmatch++;
cvntype = t;
}
}
if (conv_nmatch > 1)
{ cc_rerr(syn_rerr_multi_convfn_bool, conv_nmatch, cla);
return errornode;
}
else if (cvntype != NULL)
{ Binder *b = class_has_conversion(cla, cvntype, YES);
return mkfnap(mkfieldselector(s_dot, e, b), 0);
}
return e;
}
/* assume t has been princtype'd by the caller... */
static TypeList *convtypes_of_type(TypeExpr *t)
{ if (isclasstype_(t))
return convtypes_of_class(t, NULL);
else
return mk_typelist(NULL, t);
}
typedef struct OvldCandidate {
Binder *binder;
FormTypeList *fnarg;
} OvldCandidate;
#define candidate_(l) ((OvldCandidate *)car_(l))
static OvldCandidate *mk_candidate(Binder *b, FormTypeList *ft)
{ return (OvldCandidate *)syn_list3(b, ft, 0);
}
static List *ocl_cons(List *l, OvldCandidate *c)
{ return (List *)syn_cons2(l, c);
}
static List *ocl_discard(List *member)
{ discard3(candidate_(member));
return (List *)discard2(member);
}
List *mk_candidates(BindList *alternatives,
int nargs, int adjust_for_static_memfn, List *ocl)
{ BindList *p;
for (p = alternatives; p != NULL; p = cdr_(p))
{ Binder *btry = p->bindlistcar;
TypeExpr *ttry = princtype(bindtype_(
(bindstg_(btry) & (b_memfna|b_memfns)) ? realbinder_(btry) : btry));
int n = (bindstg_(btry) & b_memfns) && adjust_for_static_memfn ?
nargs-1 : nargs;
if (h0_(ttry) != t_fnap)
syserr("overload::mk_candidates(nonfn %ld)", h0_(ttry));
if (minargs_(ttry) <= n && n <= maxargs_(ttry))
ocl = ocl_cons(ocl, mk_candidate(btry, typefnargs_(ttry)));
}
return ocl;
}
static Binder *operator_candidate(AEop op, TypeExpr *t1, TypeExpr *t2)
{ return (Binder *) syn_list3(op, t1, t2);
}
static FormTypeList *binop_fnargs(TypeExpr *t1, TypeExpr *t2)
{ /* Keep in step with FormTypeList... */
return (FormTypeList *) syn_list3(syn_list3(0, 0, t2), 0, t1);
}
static FormTypeList *unop_fnargs(TypeExpr *t1)
{ /* Keep in step with FormTypeList... */
return (FormTypeList *) syn_list3(0, 0, t1);
}
static TypeExpr *builtin_formaltype(TypeExpr *t)
{ t = prunetype(promoted_formaltype(t));
if (h0_(t) == s_typespec &&
(typespecmap_(t) & bitoftype_(s_enum)))
t = te_int;
return t;
}
static bool binop_exists(AEop op, TypeExpr *t1, TypeExpr *t2,
TypeExpr **t1p, TypeExpr **t2p)
{
bool result = NO;
t1 = princtype(t1);
t2 = princtype(t2);
/*/* this is just a small part of over.builtin */
switch (op) {
case s_rem:
case s_and:
case s_xor:
case s_or:
case s_leftshift:
case s_rightshift:
if (h0_(t1) == t_ref)
t1 = princtype(typearg_(t1));
if (isintegraltype_(t1))
{
if (h0_(t2) == t_ref)
t2 = princtype(typearg_(t2));
result = isintegraltype_(t2);
}
break;
default:
result = YES; /*/* builtin operators, optimistic for now */
break;
}
if (result)
{ *t1p = builtin_formaltype(t1);
*t2p = builtin_formaltype(t2);
}
if (var_cc_private_flags & 16384)
cc_msg("binop_exists: $s($t,$t) => %s\n", op, t1, t2, result ? "YES" : "NO");
return result;
}
static bool unop_exists(AEop op, TypeExpr *t, TypeExpr **tp)
{
bool result = NO;
t = princtype(t);
/*/* this is just a part of over.builtin */
switch (op) {
case s_bitnot:
if (h0_(t) == t_ref)
t = princtype(typearg_(t));
result = isintegraltype_(t);
break;
case s_minus:
if (h0_(t) == t_ref)
t = princtype(typearg_(t));
result = isarithtype_(t);
break;
case s_plus:
if (h0_(t) == t_ref)
t = princtype(typearg_(t));
result = h0_(t) == t_content || h0_(t) == t_fnap || isarithtype_(t);
break;
default:
/*/* other builtin operators, optimistic for now */
result = !isclasstype_(t);
break;
}
if (result)
*tp = builtin_formaltype(t);
if (var_cc_private_flags & 16384)
cc_msg("unop_exists: $s($t) => %s\n", op, t, result ? "YES" : "NO");
return result;
}
static List *mk_binop_candidates(AEop op,TypeExpr *t1, TypeExpr *t2, List *ocl)
{
TypeList *tl1 = (op == s_assign) ?
mk_typelist(0, t1) : convtypes_of_type(princtype(t1));
TypeList *tl2 = convtypes_of_type(princtype(t2)), *l;
for (; tl1 != 0; tl1 = (TypeList *)discard2(tl1))
{ for (l = tl2; l != 0; l = cdr_(l))
{ TypeExpr *t1p, *t2p;
if (binop_exists(op, tl1->tltype, l->tltype, &t1p, &t2p))
ocl = ocl_cons(ocl, mk_candidate(
operator_candidate(op, tl1->tltype, l->tltype),
binop_fnargs(t1p, t2p)));
}
}
for (; tl2 != 0; tl2 = (TypeList *)discard2(tl2));
return ocl;
}
static List *mk_unop_candidates(AEop op, TypeExpr *t1, List *ocl)
{
TypeList *tl1 = convtypes_of_type(princtype(t1));
for (; tl1 != 0; tl1 = (TypeList *)discard2(tl1))
{ TypeExpr *tp;
if (unop_exists(op, tl1->tltype, &tp))
ocl = ocl_cons(ocl, mk_candidate(
operator_candidate(op, tl1->tltype, 0),
unop_fnargs(tp)));
}
return ocl;
}
List *mk_operator_candidates(AEop op, TypeExpr *t1, TypeExpr *t2, List *ocl)
{ TagBinder *b = isclassenumorref_type(t1);
if (b != 0) t1 = tagbindtype_(b);
if (t2 != 0)
{ b = isclassenumorref_type(t2);
if (b != 0) t2 = tagbindtype_(b);
return mk_binop_candidates(op, t1, t2, ocl);
}
else
return mk_unop_candidates(op, t1, ocl);
}
static int compute_match_value(OvldCandidate *c, TypeExpr *t, const Expr *e,
int arg_is_this, int convfn_is_OK, int is_lvalue);
#define DISTINCT_DLEVELS 100
#define MLevels 8
#define MATCH_THIS (24+(MLevels*DISTINCT_DLEVELS)+1)
/* match value returned for match of 'this' with static member fn. */
/* NOTE: MUST be greater than the greatest match value returnable. */
#define MATCH_TYPEVAR (0+((MLevels-7)*DISTINCT_DLEVELS)+1)
#define MATCH_VARIADIC (4+((MLevels-7)*DISTINCT_DLEVELS))
#define MATCH_4 ( 8+((MLevels-6)*DISTINCT_DLEVELS)+1)
#define MATCH_3_V (10+((MLevels-5)*DISTINCT_DLEVELS)+1)
#define MATCH_3 (12+((MLevels-4)*DISTINCT_DLEVELS)+1)
#define MATCH_2_B (14+((MLevels-3)*DISTINCT_DLEVELS)+1)
#define MATCH_2 (16+((MLevels-2)*DISTINCT_DLEVELS)+1)
#define MATCH_1 (20+((MLevels-1)*DISTINCT_DLEVELS)+1)
#define SLIGHTLY_WORSE_THAN(x) ((x) & ~1)
#define NO_MATCH 0
static int conv_matchval, conv_nmatch;
static Binder *class_has_convfn(TagBinder *cl, TypeExpr *t, int pick_best)
{ ClassMember *m, *vbases = 0;
OvldCandidate cc;
FormTypeList ft;
int best_match = NO_MATCH, nmatch = 0;
Binder *best = 0;
cc.fnarg = &ft;
ft.cdr = 0;
ft.fttype = t;
m = tagbindmems_(cl);
if (m != 0 && attributes_(m) & CB_CORE)
{ vbases = memcdr_(m);
cl = typespectagbind_(memtype_(m));
}
/* first look for suitable conversion functions in the CORE class... */
for (m = tagbindmems_(cl); m != 0; m = memcdr_(m))
{ if (attributes_(m) & CB_TCONV)
{ TypeExpr *mt = memtype_(m), *res = typearg_(mt);
Binder *b = (Binder *)m;
int matchval;
mt = bindtype_(b);
cc.binder = b;
matchval = compute_match_value(&cc, res, NULL, NO, NO,
h0_(prunetype(res)) == t_ref);
if (var_cc_private_flags & 16384)
cc_msg("$t has conversion to $t sees $t -> %d\n",
tagbindtype_(cl), t, typearg_(mt), matchval);
if (matchval > best_match)
{ best = b;
best_match = matchval;
nmatch = 1;
if (!pick_best) break;
}
else if (matchval == best_match)
++nmatch;
}
}
/* if found none, then look for inherited conversion functions... */
if (best_match == NO_MATCH)
{ for (m = tagbindmems_(cl); m != 0;)
{ if (attributes_(m) & (CB_BASE|CB_VBASE))
{ Binder *b;
conv_matchval = conv_nmatch = 0;
b = class_has_conversion(
typespectagbind_(memtype_(m)), t, pick_best);
if (conv_matchval > best_match)
{ best = b;
best_match = conv_matchval;
nmatch = conv_nmatch;
if (!pick_best) break;
}
else if (conv_matchval == best_match)
++nmatch;
}
else
{ m = vbases;
vbases = 0;
continue;
}
m = memcdr_(m);
}
}
conv_matchval = best_match;
conv_nmatch = nmatch;
return best;
}
Binder *class_has_conversion(TagBinder *cl, TypeExpr *t, int pick_best)
{ Binder *best;
conv_matchval = conv_nmatch = 0;
best = class_has_convfn(cl, t, pick_best);
if (conv_matchval > 0 && conv_nmatch > 1)
cc_err(syn_err_multi_convfn_ovld, conv_nmatch, cl, t);
else if (pick_best && best != 0)
best = findbinding(bindsym_(best), cl, INDERIVATION);
if (best != NULL) chk_ovld_access(best);
return best;
}
Binder *class_has_ctor_1(TagBinder *cl, TypeExpr *t, const Expr *e, int pick_best, bool silent)
{ OvldCandidate cc;
FormTypeList ft;
int best_match, nmatch;
Binder *best, *ct;
BindList *bl;
if (!(tagbindbits_(cl) & TB_NEEDSCTOR))
return 0;
ct = findbinding(ctorsym, cl, INCLASSONLY);
t = modify_actualtype(t, e);
cc.fnarg = &ft;
ft.cdr = 0;
best_match = nmatch = 0;
best = NULL;
for (bl = typeovldlist_(bindtype_(ct)); bl != 0; bl = cdr_(bl))
{ Binder *b = bl->bindlistcar;
TypeExpr *bt = bindtype_(b);
int matchval;
if (h0_(bt) != t_fnap) continue;
if (minargs_(bt) > 1 || maxargs_(bt) == 0) continue;
cc.binder = b;
/* FW: Gauged the orig intention from the value assigned. */
#if 0
if (minargs_(bt) == 0)
#else
if (fntypeisvariadic(bt))
#endif
matchval = MATCH_VARIADIC;
else
{ ft.fttype = typefnargs_(bt)->fttype;
matchval = compute_match_value(&cc, t, e, NO, NO, YES);
}
if (var_cc_private_flags & 16384)
cc_msg("$t has ctor from $t%s sees $t -> %d\n",
tagbindtype_(cl), t, isnullptrconst(e) ? "(null ptr const)" : "",
ft.fttype, matchval);
if (matchval > best_match)
{ best = b;
best_match = matchval;
nmatch = 1;
if (!pick_best) break;
}
else if (matchval == best_match)
++nmatch;
}
if (best_match > 0 && nmatch > 1 && !silent)
cc_err(syn_err_multi_ctor_ovld, nmatch, t, cl);
if (best != NULL && pick_best) chk_ovld_access(best);
return best;
}
Binder *class_has_ctor(TagBinder *cl, TypeExpr *t, const Expr *e, int pick_best)
{ return class_has_ctor_1(cl, t, e, pick_best, NO);
}
static int compute_match_value(OvldCandidate *c, TypeExpr *t, const Expr *e,
int arg_is_this, int convfn_is_OK, int is_lvalue)
{ Binder *btry = c->binder;
if (c->fnarg == 0)
/* and anything matches a '...', but only very weakly... */
return MATCH_VARIADIC;
else
{ TypeExpr *f = prunetype(c->fnarg->fttype);
t = prunetype(t);
if (arg_is_this && (bindstg_(btry) & b_memfna))
{ if (h0_(f) != t_content)
syserr("overload: what sort of 'this' is this?");
/* make an X& actual 'this' overload-match an (X *) formal 'this'. */
/* also make an X actual '*this' overload macth an (X *) formal... */
if (h0_(t) == t_ref || isclasstype_(t)) f = typearg_(f);
}
/* function types (in arg lists) either match exactly or not at all. */
if (h0_(t) == t_ovld)
{ BindList *p;
if (h0_(f) == t_content) f = typearg_(f);
for (p = typeovldlist_(t); p != NULL; p = cdr_(p))
if (equivtype(f, bindtype_(p->bindlistcar))) break;
if (p != 0) return MATCH_1;
else if (istypevar(f)) return MATCH_TYPEVAR;
}
/* conversion of T& <-> T does not affect the match value... */
/* Note that there are no refs to functions so delaying to here is OK. */
if (h0_(f) == t_ref)
{ /* Throw out cases where reference init. is impossible */
if (!(qualifiersoftype(typearg_(f)) & bitoftype_(s_const)) &&
!is_lvalue) return NO_MATCH;
f = prunetype(typearg_(f));
}
if (h0_(t) == t_ref) t = prunetype(typearg_(t));
/* Exact match - some trivial conversions make is slightly worse. */
{ SET_BITMAP qt = qualifiersoftype(t);
SET_BITMAP qf = qualifiersoftype(f);
TypeExpr *tt = princtype(t);
TypeExpr *ff = princtype(f);
if (h0_(tt) == t_content && h0_(ff) == t_content)
{ tt = typearg_(tt); qt = qualifiersoftype(tt);
ff = typearg_(ff); qf = qualifiersoftype(ff);
/* The following line is needed - e.g. in typedef struct S {f()} T; */
/* T t; return T->f() - we need equality between T* and S*... */
tt = princtype(tt); ff = princtype(ff);
}
if (qualfree_equivtype(tt, ff))
return (qt == qf) ? MATCH_1 : SLIGHTLY_WORSE_THAN(MATCH_1);
else if (istypevar(tt) || istypevar(ff))
return MATCH_TYPEVAR;
}
/* Match with promotions - integral promotions, float->double and */
/* trivial conversions are best... */
{ TypeExpr *ff = princtype(promoted_formaltype(f));
TypeExpr *tt = princtype(promoted_formaltype(t));
if (h0_(ff) == s_typespec && h0_(tt) == s_typespec)
{ SET_BITMAP fm = typespecmap_(ff) & ~CVBITS;
SET_BITMAP em = typespecmap_(tt) & ~CVBITS;
if (fm == em && typespectagbind_(f) == typespectagbind_(t) ||
!(fm & ENUMORCLASSBITS) && !(em & CLASSBITS))
{ /* exact or arithmetic conversion */
return MATCH_2;
}
/* now match with conversions, a subtle distinction for arithmetic vals */
if ((fm & (bitoftype_(s_int)|bitoftype_(s_double))) &&
(em & (bitoftype_(s_int)|bitoftype_(s_double)))
||
(fm & CLASSBITS) && (em && CLASSBITS) &&
(derivation_level = 0, type_derived_from(f, t)))
return MATCH_2_B - derivation_level;
}
}
/* now match with conversions for pointer types... */
if (h0_(f) == t_content && h0_(t) == t_content)
{ SET_BITMAP qt, qf;
int match = NO_MATCH;
f = typearg_(f); qf = qualifiersoftype(f);
t = typearg_(t); qt = qualifiersoftype(t);
if ((h0_(f) == s_coloncolon) && (h0_(t) == s_coloncolon) &&
qualfree_equivtype(princtype(typearg_(f)), princtype(typearg_(t))))
{ TypeExpr *tmp = t;
t = tagbindtype_(typespectagbind_(f)),
f = tagbindtype_(typespectagbind_(tmp));
}
if ((derivation_level = 0, type_derived_from(f, t)))
match = MATCH_3 - (2*derivation_level);
else if (qualfree_equivtype(f, te_void) ||
(feature & FEATURE_CFRONT) &&
cfront_allows_pointercast(t, f))
match = MATCH_3_V;
else if (istypevar(t) || istypevar(f))
match = MATCH_TYPEVAR;
return (qt == qf) ? match : SLIGHTLY_WORSE_THAN(match);
}
else if (h0_(f) == t_content && e != NULL && isnullptrconst(e))
return MATCH_3;
else if (arg_is_this)
{ if (isclasstype_(t) && isclasstype_(f) &&
typespectagbind_(t) == core_class(typespectagbind_(f)))
return MATCH_1;
}
else if (convfn_is_OK /* && !arg_is_this */)
/* finally, match with user-defined conversions - but never via 'this' */
/* or if invoked recursively via class_has_{conversion,ctor}. */
{ if (isclasstype_(t) &&
class_has_conversion(typespectagbind_(t),
prunetype(c->fnarg->fttype), NO))
{ /* a direct match is always better than others */
return (conv_matchval == MATCH_1) ? MATCH_4 : SLIGHTLY_WORSE_THAN(MATCH_4);
}
if (isclasstype_(f) &&
class_has_ctor(typespectagbind_(f), t, e, NO))
return MATCH_4;
}
if (istypevar(t) || istypevar(f))
return MATCH_TYPEVAR;
else
return NO_MATCH;
}
}
#define is_derived_match_(i) (i<=MATCH_3 && MATCH_4<i)
#define MAX_NO_ARGS 32
Binder *ovld_reduce(Binder *b, List *candidates, ExprList *l, ExprList *ll)
{ /* if there is only one candidate we take it as the best match even though
it may not match -- this gives us better error messages */
if (cdr_(candidates) != 0 || h0_(b) == s_init)
{ List *c, *prev, *next;
ExprList *p;
int best_match_vec[MAX_NO_ARGS];
TypeExpr *type_arg_vec[MAX_NO_ARGS];
bool is_lvtype_vec[MAX_NO_ARGS];
int max_arg_info = -1;
for (prev = 0, c = candidates; c != 0; c = next)
{ int candidate_match_vec[MAX_NO_ARGS];
bool better = NO, worse = NO, failed_match = NO;
OvldCandidate *x = candidate_(c);
FormTypeList *btryfnargs = x->fnarg;
int nargs = 0;
for (p = ll; p != 0; p = cdr_(p), ++nargs)
{ Expr *e = exprcar_(p);
Binder *btry = x->binder;
int arg_is_this = (p == ll) && (l != ll);
TypeExpr *etype;
int is_lvt;
int matchval;
if (nargs > MAX_NO_ARGS)
{ cc_rerr(sem_rerr_too_many_args_ovld);
cdr_(ll) = 0;
break;
}
/* builtin and global operators have no 'this' pointer... unconditionally. */
if (h0_(btry) != s_binder || !(bindstg_(btry) & (b_memfna|b_memfns)))
arg_is_this = 0;
if (max_arg_info < nargs)
{ best_match_vec[nargs] = (nargs == 0 && ll != l) ?
MATCH_VARIADIC : NO_MATCH;
etype = type_arg_vec[nargs] =
modify_actualtype(typeofexpr(e), e);
is_lvt = is_lvtype_vec[nargs] = lvalue_type(e) != NULL;
++max_arg_info;
if (max_arg_info != nargs)
syserr("ovld_reduce: %d, %d", max_arg_info, nargs);
}
else
{ etype = type_arg_vec[nargs];
is_lvt = is_lvtype_vec[nargs];
}
/* static member functions match 'this' is a special way... */
if (arg_is_this && (bindstg_(btry) & b_memfns))
matchval = MATCH_THIS;
else
matchval = compute_match_value(x, etype, e, arg_is_this,
YES, is_lvt);
if (matchval == NO_MATCH)
{ failed_match = YES;
if (var_cc_private_flags & 16384)
cc_msg("$b arg %d failed match\n",
candidate_(c)->binder, nargs+1);
break;
}
candidate_match_vec[nargs] = matchval;
if (matchval != MATCH_THIS && x->fnarg != 0)
x->fnarg = cdr_(x->fnarg);
}
x->fnarg = btryfnargs;
if (!failed_match)
{ FormTypeList *bestfnargs = (prev) ? candidate_(prev)->fnarg : 0;
int i = 0, len;
len = length(ll);
for (; i < len; ++i)
{
if (bestfnargs && btryfnargs)
{ TypeExpr *t1 = btryfnargs->fttype,
*t2 = bestfnargs->fttype;
bestfnargs = cdr_(bestfnargs);
btryfnargs = cdr_(btryfnargs);
if (is_derived_match_(candidate_match_vec[i]) &&
is_derived_match_(best_match_vec[i]) &&
h0_(t1) == h0_(t2) && (h0_(t1) == t_content ||
h0_(t1) == t_ref) &&
!(t1 = typearg_(t1), t2 = typearg_(t2),
isvoidtype(t1) || isvoidtype(t2) ||
qualfree_equivtype(t1, t2) ||
type_derived_from(t1, t2) ||
type_derived_from(t2, t1)))
{ if (var_cc_private_flags & 16384)
cc_msg("$b arg %d not comparable to current best's\n",
x->binder, i+1);
continue;
}
}
/* Can there be MATCH_THIS other than i == 0? Over-zealous. */
if (i == 0 && candidate_match_vec[i] == MATCH_THIS)
{ if (var_cc_private_flags & 16384)
cc_msg("skipped 'this' pointer for static fn $b\n",
candidate_(c)->binder);
continue;
}
if (var_cc_private_flags & 16384)
cc_msg("$b arg %d match value = %3d vs. %3d",
candidate_(c)->binder, i+1, candidate_match_vec[i],
best_match_vec[i]);
if (candidate_match_vec[i] > best_match_vec[i])
{ better = YES;
if (var_cc_private_flags & 16384) cc_msg(" -> better");
}
else if (candidate_match_vec[i] < best_match_vec[i])
{ worse = YES;
if (var_cc_private_flags & 16384) cc_msg(" -> worse");
}
if (var_cc_private_flags & 16384) cc_msg("\n");
}
}
/* elimination phrase: the best match candidates, if any, are always
at the top of the list */
if (failed_match || (!better && worse))
{ /* discarded */
if (var_cc_private_flags & 16384)
cc_msg(" dropped $b\n", candidate_(c)->binder);
if (h0_(candidate_(c)->binder) != s_binder)
(void) discard3(candidate_(c)->binder);
next = ocl_discard(c);
if (prev != 0) cdr_(prev) = next; else candidates = next;
}
else if (better && !worse)
{ /* displaced (the lot) */
int i = 0;
for (; i < length(ll); ++i)
best_match_vec[i] = candidate_match_vec[i];
if (var_cc_private_flags & 16384)
cc_msg(" best so far is $b\n", candidate_(c)->binder);
candidates = c;
prev = c;
next = cdr_(c);
}
else
{ /* retained */
if (var_cc_private_flags & 16384)
cc_msg(" retaining $b\n", candidate_(c)->binder);
prev = c;
next = cdr_(c);
}
}
for (c = candidates; c != 0; c = cdr_(c))
{ OvldCandidate *x = candidate_(c);
if (h0_(x->binder) != s_binder)
while (x->fnarg) x->fnarg = (FormTypeList *)discard3(x->fnarg);
}
}
{ Binder *bmatch = (Binder *)errornode;
/* inhibit cascade errors */
if (candidates == 0)
{ if (h0_(b) == s_binder)
cc_err(syn_err_incomp_arg_ovld, b);
else
bmatch = 0; /* allowable failure */
}
else
{ /* Prefers the non-template version */
if (length(candidates) == 2 && h0_(b) == s_binder &&
(bindenv_(candidate_(candidates)->binder) ||
bindenv_(candidate_(cdr_(candidates))->binder)))
{ if (bindenv_(candidate_(candidates)->binder) == NULL)
{ (void)ocl_discard(cdr_(candidates));
cdr_(candidates) = NULL;
} else
candidates = ocl_discard(candidates);
}
if (cdr_(candidates) != 0 &&
(bindparent_(b) == NULL ||
!(tagbindbits_(bindparent_(b)) & TB_TEMPLATE)))
{ int n = length(candidates);
if (h0_(b) == s_binder)
cc_err(syn_err_multi_overload_call, n, b);
else
cc_err(syn_err_multi_operator_ovld, n, h0_(b));
}
else
{ bmatch = candidate_(candidates)->binder;
/* beware pseudo-fns for builtin operators... */
if (h0_(bmatch) == s_binder) chk_ovld_access(bmatch);
}
}
/* clean up any remaining detritus... */
while (candidates) candidates = ocl_discard(candidates);
return bmatch;
}
}
Binder *ovld_resolve(Binder *b, BindList *alternatives,
ExprList *l, ExprList *ll, bool silent)
{ int nargs;
List *candidates;
/* Don't even try for overload resolution if previous (hard) error. */
{ ExprList *p = ll; /* always contains all of 'l'. */
for (nargs = 0; p != 0; nargs++, p = cdr_(p))
if (h0_(exprcar_(p)) == s_error) return (Binder *)errornode;
}
if ((candidates = mk_candidates(alternatives, nargs, (l != ll), 0)) == 0)
{ Binder *b = (Binder *)errornode;
if (!silent)
{ if (alternatives != NULL && cdr_(alternatives) == NULL)
b = alternatives->bindlistcar; /* wrong # args reported by sem */
else if (!silent)
cc_err(syn_err_wrong_args_ovld, b);
}
return b;
}
return ovld_reduce(b, candidates, l, ll);
}
/* End of cfe/overload.c */
|
stardot/ncc | clbcomp/options.h | /*
* 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 CALLABLE_COMPILER 1
#define CPLUSPLUS 1
#define USE_PP
#define NO_LISTING_OUTPUT 1
#define NO_OBJECT_OUTPUT 1
#define NO_DEBUGGER 1
#define NO_ASSEMBLER_OUTPUT 1
#define NO_CONFIG 1
#define NO_DUMP_STATE 1
#define NO_INSTORE_FILES 1
#define HOST_CANNOT_INVOKE_LINKER 1
#define HOST_CANNOT_INVOKE_ASSEMBLER 1
#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 DISABLE_ERRORS 1 /* -- to enable -Exyz... error suppression */
#define EXTENSION_SYSV 1 /* -- to allow #ident ... */
#ifndef __acorn
# 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. */
# define PCS_DEFAULTS (PCS_CALLCHANGESPSR + PCS_NOSTACKCHECK)
# else /* NOT TARGET_IS_NEWTON */
/* usual cross-development case... */
# define TARGET_SYSTEM ""
# define TARGET_IS_RISC_OS 1
# define TARGET_DEFAULT_BIGENDIAN 0
# define PCS_DEFAULTS (PCS_CALLCHANGESPSR | PCS_FPE3 | PCS_SOFTFP)
/* | PCS_NOSTACKCHECK */
/* | PCS_REENTRANT */
/* | PCS_FPREGARGS */
# endif
# define HOST_WANTS_NO_BANNER 1
# ifndef DRIVER_OPTIONS
/* -D__arm done by TARGET_PREDEFINES */
# define DRIVER_OPTIONS {NULL}
# endif
#else /* __acorn is defined */
# ifdef __unix
# define TARGET_SYSTEM "RISCiX"
# define TARGET_IS_UNIX 1
# define NO_INSTORE_FILES 1 /* no in-store headers under Unix. */
# define HOST_WANTS_NO_BANNER 1
/* #define TARGET_HAS_DIVREM_FUNCTION 1 -- divide fn also returns remainder.*/
/* #define TARGET_HAS_DIV_10_FUNCTION 1 -- fast divide by 10 */
/* but not under ARM Unix... */
# ifndef DRIVER_OPTIONS
/* -D__arm done by TARGET_PREDEFINES */
# define DRIVER_OPTIONS {"-zps1", "-D__unix", "-D__acorn", NULL}
# endif
# endif
# ifdef __riscos
# define TARGET_SYSTEM "RISC OS"
# 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. */
# ifndef DRIVER_OPTIONS
/* -D__arm done by TARGET_PREDEFINES */
# define DRIVER_OPTIONS {"-D__riscos", "-D__acorn", NULL}
# endif
# endif
#endif /* defined(__acorn) */
#ifndef TARGET_IS_NEWTON
# define PROFILE_COUNTS_INLINE 1
/* to avoid conflict with host compilers */
# define C_INC_VAR "ARMINC"
# define C_LIB_VAR "ARMLIB"
#else
# define PROFILE_DISABLES_TAILCALL 1
# define C_INC_VAR "ARMCIncludes"
# define C_LIB_VAR NULL
#endif
/* #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 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
#ifdef applec
/* work-around for MPW C */
# define NO_STATIC_BANNER 1
#endif
pascal void SpinCursor(short increment); /* copied from CursorCtl.h */
# define ExecuteOnSourceBufferFill() SpinCursor(1)
#else /* NOT macintosh */
# ifdef UNIX_TIME_LIMIT
# define TIME_LIMIT UNIX_TIME_LIMIT
# endif
#endif
#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_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
#ifdef MAKE_WCHAR_T_UNSIGNED_SHORT
/* make wchar_t be unsigned short */
/* maybe this should be cfe somewhere */
# define sizeof_wchar sizeof_short
# define te_wchar te_ushort /* for sem.c */
# define NUM_WCHAR (NUM_INT|NUM_SHORT|NUM_UNSIGN) /* for lex.c */
#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 "npp.a" /* used to load correct NLS message file */
#endif
/* end of clbcomp/options.h */
|
stardot/ncc | cppfe/xbind.c | /*
* xbind.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, 1994
* SPDX-Licence-Identifier: Apache-2.0
* All rights reserved
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
#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 "syn.h" /* for add_pendingfn */
#include "store.h"
#include "vargen.h" /* for initstaticvar()... */
#include "xrefs.h" /* for LIT_LABEL */
#include "errors.h"
#include "aeops.h"
#define _BIND_H
static void set_linkage(Binder *b, SET_BITMAP linkage, Binder *m);
static Expr *path_to_member_2(ClassMember *mem, TagBinder *b, int flags,
ClassMember *vbases, TagBinder *privately_deriving_class);
static Expr *path_to_base_member(ClassMember *mem, TagBinder *b, int flags,
ClassMember *vbases, TagBinder *privately_deriving_class);
static ClassMember *instate_member_cpp(DeclRhsList *d, int bindflg);
static Binder *instate_member_binder(DeclRhsList *d /*, int bindflg*/);
static Binder *instate_declaration_cpp(DeclRhsList *d, int declflag);
static Binder *implicit_decl_cpp(Symstr*);
static int merge_default_arguments(TypeExpr *bt, TypeExpr *dt)
{ FormTypeList *bft, *dft;
int msg = 0, musthavedefault = 0, minargs = 0, argno = 1;
bt = princtype(bt);
dt = princtype(dt);
if (h0_(bt) != t_fnap || h0_(dt) != t_fnap)
syserr("merge_default_arguments(%ld, %ld)", h0_(bt), h0_(dt));
bft = typefnargs_(bt);
dft = typefnargs_(dt);
/* Called with bt == dt to check that default arguments on a first decl */
/* of this function are at the end of the argument list. */
while (bft != 0 && dft != 0)
{ if (dft->ftdefault != 0)
{ /* the new declaration has a default argument value... */
if (dft != bft && bft->ftdefault != 0)
{ cc_err(sem_err_dupl_default_value,
argno, bft->ftname != 0 ? bft->ftname : dft->ftname);
msg = 1;
}
else
{ bft->ftdefault = dft->ftdefault;
musthavedefault = 1;
}
}
else if (bft->ftdefault == 0)
{ if (musthavedefault)
{ cc_err(sem_err_missing_default_value,
argno, bft->ftname != 0 ? bft->ftname : dft->ftname);
msg = 1;
}
else
++minargs;
}
/* template fns need the following line */
bft->ftname = dft->ftname;
if (bft->ftname != thissym) ++argno;
bft = bft->ftcdr; dft = dft->ftcdr;
}
minargs_(bt) = minargs_(dt) = minargs;
if (msg) return 0;
if (bt == dt) return 2;
return equivtype(bt, dt);
}
static Expr *nullbinder(TagBinder *cl)
{
return (Expr *)mk_binder(0, u_referenced, tagbindtype_(cl));
}
static Symstr *hiddenmembername(char pfx, Symstr *sv)
{ char name[128];
sprintf(name, "__%c_%s", pfx, symname_(sv));
return sym_insert_id(name);
}
#include "bind.c"
#include "mcdep.h"
ClassMember *mk_member(TagBinder *basename, TypeExpr *t,
SET_BITMAP attributes, TagBinder *parent)
{ ClassMember *mem =
(ClassMember *)GlobAlloc(SU_Other, (int32)SIZEOF_CLASSMEMBER);
h0_(mem) = s_member;
memcdr_(mem) = NULL;
memsv_(mem) = hiddenmembername(attributes & CB_VBASE ? 'V' :
attributes & CB_BASE ? 'B' :
attributes & CB_CORE ? 'C' : 'P',
bindsym_(basename));
/* AM: I have chosen to globalise 't' here -- this parallels */
/* instate_member &c. It also allows the possibility of an */
/* 'attributes' flag to alter this dynamically. */
/* Caching in globalize() will mean that this does not cost store. */
memtype_(mem) = globalize_typeexpr(t);
bindparent_(mem) = parent;
attributes_(mem) = attributes & ~A_LOCALSTORE | A_GLOBALSTORE;
bindstg_(mem) = 0; /* b_member? */ /* @@@ share this forgery code! */
return RecordGlobalBinder(mem);
}
/* mk_core_part has to forge a struct definition and hence to */
/* globalise types in its members. */
/* Can this code be shared with instate_tagbinding &c? */
ClassMember *mk_core_part(TagBinder *cl, ClassMember *bases,
ClassMember *vbases)
{ ClassMember *m = bases;
if (vbases)
{ Symstr *corename = hiddenmembername('K', bindsym_(cl));
TagBinder *b = clone_tagbinder(corename, cl);
tagbindbits_(b) |= TB_CORE|TB_BEINGDEFD;
tagbindmems_(b) = bases;
b->tagparent = cl;
m = mk_member(cl, tagbindtype_(b), bitofaccess_(s_public)|CB_CORE, cl);
memcdr_(m) = vbases;
}
return m;
}
/* used for C++ 'core' members. */
TagBinder *clone_tagbinder(Symstr *newname, TagBinder *b)
{ SET_BITMAP bits = tagbindbits_(b) & ENUMORCLASSBITS;
TagBinder *p = global_mk_tagbinder(NULL, newname, s_struct);
tagbindbits_(p) = bits | TB_CORE;
tagbindtype_(p) =
globalize_typeexpr(primtype2_(bits, p)); /* or tagbindtype_(b)? */
tagbindparent_(p) = tagbindparent_(b);
return p;
}
#define CHECK_INHERITED_VIRTUAL FB_CIV
/* memfn_realtype performs the mapping (e.g.) */
/* 'int cl::f() volatile' => 'int f(volatile cl *const)' */
/* fntype is presumed already prunetype()d. */
extern TypeExpr *memfn_realtype(TypeExpr *fntype, TagBinder *cl)
{ /* now in local store -- users (or instate_declaration) globalize. */
/* @@@ soon add extra arg for __ct if TagBinder has a virt. base. */
TypeExprFnAux s;
TypeExpr *thistype = mk_typeexpr1(t_content,
mkqualifiedtype(tagbindtype_(cl), typeptrmap_(fntype)),
(Expr *)bitoftype_(s_const));
/* Next line allocates a DeclRhsList for use by memfn_fixtype (q.v.) */
/* when, for this code, a FormTypeList would suffice. */
DeclRhsList *d = mkDeclRhsList(thissym, thistype, bitofstg_(s_auto));
d->declcdr = typefnargs1_(fntype);
return mkTypeExprfn(t_fnap, typearg_(fntype), 0, (FormTypeList *)d,
packTypeExprFnAux(s, minargs_(fntype) + 1,
maxargs_(fntype) + (maxargs_(fntype)<999 ? 1:0),
0, /* special_variad */
0, /* syn_oldeformals */
0)); /* flags - e.g. no side effects */
}
extern TypeExpr *add_delete_arg(TypeExpr *fntype, bool is_declaration)
{ TypeExprFnAux s;
DeclRhsList *d = mkDeclRhsList(deletesym, te_int, bitofstg_(s_auto));
d->declcdr = typefnargs1_(fntype);
if (is_declaration)
declinit_(d) = lit_zero;
return mkTypeExprfn(t_fnap, typearg_(fntype), 0, (FormTypeList *)d,
packTypeExprFnAux(s, minargs_(fntype) + 1,
maxargs_(fntype) + (maxargs_(fntype)<999 ? 1:0),
0, /* special_variad */
0, /* syn_oldeformals */
0)); /* flags - e.g. no side effects */
}
static void set_linkage(Binder *b, SET_BITMAP linkage, Binder *m)
/* b may also be a TagBinder *... */
{ SET_BITMAP a = attributes_(b) & (A_NOLINKAGE+A_INTERN+A_EXTERN);
if (a == 0)
attributes_(b) |= linkage;
else if (a != linkage)
{ if (a & A_NOLINKAGE)
cc_rerr(bind_rerr_linkage_disagreement_2, b, m);
else
cc_rerr(bind_rerr_linkage_disagreement_3, b, m);
}
}
int32 base_vtable_sz(TagBinder *b)
{ ClassMember *m;
int32 sz = 0;
for (m = tagbindmems_(b); m != NULL; m = memcdr_(m))
{ if (attributes_(m) & (CB_CORE|CB_BASE|CB_VBASE))
sz += base_vtable_sz(typespectagbind_(princtype(memtype_(m))));
else if (attributes_(m) & CB_VTAB)
sz += memvtablesize_(m);
}
return sz;
}
static ClassMember *lmost_vtable0(TagBinder *b)
{ ClassMember *m = tagbindmems_(b), *vtab;
if ((m != NULL) && (attributes_(m) & (CB_CORE|CB_BASE)))
{ vtab = lmost_vtable0(typespectagbind_(princtype(memtype_(m))));
if (vtab) return vtab;
}
for (; m != NULL; m = memcdr_(m))
if (is_datamember_(m) && (attributes_(m) & CB_VTAB))
return m;
return NULL;
}
static ClassMember *lmost_vtable(TagBinder *b)
{ ClassMember *m = tagbindmems_(b);
if ((m != NULL) && (attributes_(m) & (CB_CORE|CB_BASE)))
return lmost_vtable0(typespectagbind_(princtype(memtype_(m))));
return NULL;
}
static int32 lmost_vtable_sz0(TagBinder *b)
{ ClassMember *m;
int32 sz = 0;
bool seen_lmost = NO;
for (m = tagbindmems_(b); m != NULL; m = memcdr_(m))
{ if (attributes_(m) & (CB_VBASE|CB_BASE))
{ if (!seen_lmost)
{ sz = lmost_vtable_sz0(typespectagbind_(princtype(memtype_(m))));
seen_lmost = YES;
} else
sz += base_vtable_sz(typespectagbind_(princtype(memtype_(m))));
}
if (attributes_(m) & CB_VTAB)
sz += memvtablesize_(m);
}
return sz;
}
static int32 lmost_vtable_sz(TagBinder *b)
{ ClassMember *m = tagbindmems_(core_class(b));
if ((m != NULL) && (attributes_(m) & CB_BASE))
return lmost_vtable_sz0(typespectagbind_(princtype(memtype_(m))));
return 0;
}
static ClassMember *add_vtable_pointer(void)
{ ClassMember *m;
ClassMember *vtab, *p, **pp = &tagbindmems_(local_scope->class_tag);
if ((vtab = lmost_vtable(local_scope->class_tag)) != NULL)
{ /* we'll share the __VTABLE slot with our left-most base class */
/* but we add a typedef __VTABLE member to remember the number */
/* of virtual functions in this class that are not also in the */
/* left-most base class. Being a typedef it will take no */
/* storage. */
/* type for vtab points to the parent class to look for the */
/* actual vtab. */
DeclRhsList *d = mkDeclRhsList(vtabsym,
ptrtotype_(tagbindtype_(bindparent_(vtab))), bitofstg_(s_typedef));
m = instate_member_binder(d /*, LOCALSCOPE*/);
attributes_(m) = bitofaccess_(s_public) | CB_VTAB;
return m;
}
m = (ClassMember *)GlobAlloc(SU_Bind, SIZEOF_CLASSMEMBER);
h0_(m) = s_member;
memsv_(m) = vtabsym;
memtype_(m) = globalize_typeexpr(ptrtotype_(te_ulint));
memwoff_(m) = OFFSET_UNSET; memboff_(m) = 0; membits_(m) = 0;
memvtablesize_(m) = 0;
attributes_(m) = bitofaccess_(s_public) | CB_VTAB;
bindstg_(m) = 0;
bindparent_(m) = local_scope->class_tag;
again:
for (p = *pp; p != 0; pp = &memcdr_(p), p = *pp)
{ if (attributes_(p) & CB_CORE)
{ pp = &tagbindmems_(typespectagbind_(memtype_(p)));
goto again;
}
if (!(attributes_(p) & (CB_BASE|CB_VBPTR))) break;
}
*pp = m;
memcdr_(m) = p;
return RecordGlobalBinder(m);
}
static bool is_leftmost_derivation(TagBinder *tb, TagBinder *parent)
{ ClassMember *m = tagbindmems_(parent);
if (attributes_(m) & (CB_CORE|CB_BASE))
{ TypeExpr *t = princtype(memtype_(m));
TagBinder *base;
if ((base = typespectagbind_(t)) == tb) return YES;
return is_leftmost_derivation(tb, base);
}
return NO;
}
/* This function creates the skeleton of a 'core' function for generated */
/* ctors, dtors, operator=() and for user-defined ctors and dtors, for */
/* classes which have virtual bases. The core function contains the body */
/* of the user-written code and deals with non-virtual bases. The top */
/* level function handles virtual bases, vtable pointers and calls the */
/* core function. The core function is not a class member. The type of */
/* the core function is similar to that of the top-level function, save */
/* that class-valued arguments are replaced by ref-to-class arguments. */
static Binder *add_core_binder_to(Binder *b)
{ char corename[128];
Symstr *sv;
TypeExpr *fntype = bindtype_(b);
FormTypeList *ft, *ftp = 0, *ftq = 0;
/* inherit inline/static/extern from the top-level binder... */
SET_BITMAP stg = (bindstg_(b) &
(bitofstg_(s_inline)|bitofstg_(s_static)|bitofstg_(s_extern))) |
b_generated | b_fnconst;
/* The name of the core function is foo__C... */
strcpy(corename, bindsym_(b)->symname);
strcat(corename, "__C");
sv = sym_insert_id(corename);
/* Clone the function's type - class-type args become ref-type args... */
for (ft = typefnargs_(fntype); ft != 0; ft = ft->ftcdr)
{ TypeExpr *t = princtype(ft->fttype);
FormTypeList *f = mkFormTypeList(0, ft->ftname,
isclasstype_(t) ? mk_typeexpr1(t_ref, t, 0) : ft->fttype, 0);
if (ftp == 0)
ftp = (ftq = f);
else
ftq = (ftq->ftcdr = f);
}
fntype = mkTypeExprfn(t_fnap, typearg_(fntype),
typeptrmap_(fntype), ftp, &typefnaux_(fntype));
attributes_(b) |= CB_HASCOREFN; /* used by mkfnap_cpp() */
return realbinder_(b) =
global_mk_binder(0, sv, stg, globalize_typeexpr(fntype));
}
static Binder *instate_member_binder(DeclRhsList *d /*, int bindflg*/)
{ Binder *b, *btop;
/* 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. */
TypeExpr *t = d->decltype;
SET_BITMAP stg = killstgacc_(d->declstg);
SET_BITMAP access = attribofstgacc_(d->declstg);
TagBinder *parent = local_scope->class_tag;
Binder *inheritb = NULL;
if (parent == NULL)
{ /* this happens when member is a function template, and local_scope is
the formal template type scope.
*/
parent = local_scope->prev->class_tag;
}
t = globalize_typeexpr(t);
if (isfntype(t) && !(stg & bitofstg_(s_typedef)))
{ inheritb = findbinding(d->declname, parent,
INDERIVATION+CHECK_INHERITED_VIRTUAL);
/* @@@ See [ES, p209], but there is a nasty ambiguity in the following: */
/* class A { virtual int f(); }; class B { int f(); }; */
/* class C:A,B { int f(); }. Is C::f virtual or not? */
if (inheritb && bindstg_(inheritb) & bitofstg_(s_virtual))
{ if (!equivtype(t, bindtype_(inheritb)))
cc_rerr(xbind_rerr_inherited_type_differs, inheritb);
if (!(stg & (bitofstg_(s_virtual)|b_generated))
&& !(suppress & D_IMPLICITVIRTUAL))
cc_warn(xbind_warn_implicit_virtual, parent, d->declname);
stg |= bitofstg_(s_virtual);
/* Conspire with syn.c(MEMFNBITS) to suppress 'unused this' warnings: */
d->declstg |= bitofstg_(s_virtual);
}
else
inheritb = 0;
}
/* always globalise member fns for C++ (local structs!). */
b = global_mk_binder(NULL, d->declname, stg, t);
bindparent_(b) = parent;
/* @@@ Fix the next line? (E.g.) generate a top-level extern struct */
/* with bit field entry. Also such padding (sv=0) bit fields. */
if (declbits_(d)) syserr("static member bit field");
attributes_(b) |= access;
if (strncmp(symname_(bindsym_(b)), "__op", 4) == 0)
attributes_(b) |= CB_TCONV;
{ Scope *saved_scope = local_scope;
while (local_scope->kind == Scope_Args ||
local_scope->kind == Scope_TemplateArgs)
local_scope = local_scope->prev;
add_local_binder(b);
local_scope = saved_scope;
}
t = princtype(t);
if (h0_(t) == t_fnap && !(stg & bitofstg_(s_typedef)) ||
(stg & bitofstg_(s_static)))
{ DeclRhsList decl; /* @@@ forgery! */
ClassMember *vtable = NULL;
if (h0_(t) == t_fnap)
{ stg |= b_fnconst;
if (stg & bitofstg_(s_virtual))
{ vtable = findbinding(vtabsym, parent, INCLASSONLY);
if (vtable == NULL) vtable = add_vtable_pointer();
tagbindbits_(parent) |= TB_HASVTABLE;
}
if (!(stg & bitofstg_(s_inline)))
{ /* and not inline => maybe inline... */
/*/* The DRAFT in section 7.1.2 agrees with the A.R.M. but contradicts */
/* the DRAFT section 3.4, which implies member fns have EXTERN linkage */
/* or NO LINKAGE, following the linkage of the containing class. They */
/* cannot have INTERNAL linkage, which is what b_maybeinline manages. */
/* stg |= b_maybeinline; <<<<<<<<<<<<<<<<<<<<<<<<<<<<< */
/* a member function not explicitly inline gives this */
/* class external linkage. (DRAFT std section 3.4). */
set_linkage((Binder *)parent, A_EXTERN, b);
}
if (stg & bitofstg_(s_static))
stg |= b_memfns;
else
{ /* a MEMBER function, not static or friend... */
if (strncmp(symname_(d->declname), "__dt", 4) == 0)
t = add_delete_arg(t, YES);
t = memfn_realtype(t, parent);
stg |= b_memfna;
}
}
else
{ /* a static data member gives this class external linkage */
/* (DRAFT std section 3.4). */
set_linkage((Binder *)parent, A_EXTERN, b);
}
decl.declname = ovld_add_memclass(d->declname, parent,
(stg & b_memfns) != 0);
/* We are declaring a member function or static member. Linkage */
/* is in fact external unless we have an in-line function in a */
/* NOLINKAGE (local) class. */
if ((stg & bitofstg_(s_inline)) && (attributes_(parent) & A_NOLINKAGE))
stg = (stg & ~bitofstg_(s_extern)) | bitofstg_(s_static);
else
stg = (stg & ~bitofstg_(s_static)) | bitofstg_(s_extern);
#if WANTS_BAD_TYPE_DISAGREEMENT_BUG
decl.decltype = t;
#else
/* princtype() removes qualifiers from the typedef type. This
is BAD news for "typedef int Int; struct X { static const Int x; };"
*/
decl.decltype = (h0_(t) == t_fnap) ? t : d->decltype;
#endif
decl.declstg = stg | b_undef; /* no stgaccof_() bits! */
d->declstg = stg;
/* In case of inline fn defn..., because rd_decl() saves it */
/* when the fn body is read... later used by instate_decl() */
btop = instate_declaration_cpp(&decl, TOPLEVEL);
realbinder_(b) = btop;
#if 0
/* See if there is a defn in the primary template */
if (bindstg_(btop) & bitofstg_(s_extern)
&& !(qualifiersoftype(t) & bitoftype_(s_const))
&& h0_(t) != t_fnap
&& tagprimary_(local_scope->class_tag) != NULL)
{ TagBinder *tb = local_scope->class_tag;
Binder *b1 = findbinding(bindsym_(b), tagprimary_(tb),
FB_LOCALS|FB_THISSCOPE);
if (!b1 || !realbinder_(b1))
syserr("Lost static member $b in $c", b, tb);
if (bindconst_(realbinder_(b1)) != NULL)
{ DeclRhsList *d;
Expr *einit = bindconst_(realbinder_(b1));
push_exprtemp_scope();
einit = mkcast(s_init, einit, bindtype_(btop));
if (h0_(einit) != s_error)
{ einit = cpp_mkbinaryorop(s_init, (Expr *)btop, einit);
bindstg_(btop) &= ~b_undef;
d = mkDeclRhsList(bindsym_(btop), bindtype_(btop), bindstg_(btop));
d->declbind = btop;
(void) genstaticparts(d, YES, typehasctor(bindtype_(btop)), einit);
}
if (killexprtemp() != NULL) syserr("extra temps leaked");;
}
}
#endif
/* @@@ AM wants to revisit the b_pseudonym code. Maybe more should */
/* be done by simplify or cg? */
bindstg_(b) = stg;
bindstg_(b) |= stg & (b_memfna|b_memfns) ? b_impl : b_pseudonym;
if (vtable != NULL)
{ if (inheritb && var_cc_private_flags & 4194304)
cc_msg("Override $b @%2d\n", realbinder_(inheritb),
bindxx_(realbinder_(inheritb)));
if (inheritb != NULL)
{ TagBinder *tb = core_class(bindparent_(inheritb));
if (is_leftmost_derivation(tb, parent) == NO)
inheritb = 0;
}
if (inheritb && h0_(inheritb) != s_error)
bindxx_(btop) = bindxx_(realbinder_(inheritb));
else
{ bindxx_(btop) = lmost_vtable_sz(parent) + memvtablesize_(vtable);
++memvtablesize_(vtable);
}
if (!inheritb && var_cc_private_flags & 4194304)
cc_msg("Final override $b @%2d\n", btop, bindxx_(btop));
}
if (h0_(t) == t_fnap && symname_(bindsym_(b))[0] == '_')
{ /* tagbindbits_(parent) & TB_HASVBASE is not setup until end_strdecl */
ClassMember *firstmem = tagbindmems_(parent);
if (firstmem != 0 && (attributes_(firstmem) & CB_CORE))
{ /* /* probably we should have attributes bits CB_CTOR, etc. */
const char* name = symname_(bindsym_(b));
if (strncmp(name, "__ct", 4) ||
strncmp(name, "__dt", 4) ||
strncmp(name, "__as", 4))
add_core_binder_to(btop);
}
}
}
else if (stg & bitofstg_(s_typedef))
{ /* class-local typedef... */
TypeExpr *pt = princtype(d->decltype);
if (usrdbg(DBG_PROC))
/* /* Err... what's the real intention here? */
dbg_type(ovld_add_memclass(bindsym_(b), parent, 0),
bindtype_(b), d->fileline);
/* a member type with EXTERNAL linkage gives this class extern */
/* linkage (DRAFT std section 3.4). */
if (isclasstype_(pt) && (attributes_(typespectagbind_(pt)) & A_EXTERN))
set_linkage((Binder *)parent, A_EXTERN, b);
}
return b;
}
/* overloading parts: unify with instate_declaration. */
static ClassMember *instate_member_cpp(DeclRhsList *d, int bindflg)
{ Symstr *sv = d->declname;
TypeExpr *dt = d->decltype;
d->declbind = 0;
if (sv == NULL || !isfntype(dt) || (d->declstg & bitofstg_(s_typedef)))
{ /* bitfield padding, not a function, or a typedef */
/*/* class-scope ENUMs not properly handled yet... */
if (sv != 0 && (d->declstg & STGBITS))
/* non-function static member or typedef */
return instate_member_binder(d /*, bindflg*/);
else
return instate_member_1(d, bindflg);
}
else if (d->declstg & bitofstg_(s_friend))
{ TagBinder *parent = local_scope->class_tag;
Binder *btop;
SET_BITMAP stg = killstgacc_(d->declstg);
int flags = /*(tagbindbits_(parent) & TB_TEMPLATE || tagprimary_(parent)) ?
LOCALSCOPE|GLOBALSTG :*/ TOPLEVEL;
/* CD #2 11.4 disallows storage classes in friend decls */
/* 'extern' is already disallowed for all member decls */
/* catch 'static', 'mutable', etc, here */
if (stg & (PRINCSTGBITS /* | bitofstg_(s_mutable) */))
cc_rerr("storage class not allowed for friends -- ignored");
stg = (stg & ~(PRINCSTGBITS /* | bitofstg_(s_mutable)*/)) |
bitofstg_(s_extern); /* 'extern' if no previus decl */
/* We need to set undef in case never defined... and unset it */
/* if defined inline. Side effects back in rd_declrhslist(). */
d->declstg = stg | b_undef;
if (is_dependent_type(d->decltype) || bindflg & TEMPLATE)
flags |= TEMPLATE;
if (tagprimary_(parent) != NULL &&
(tagbindbits_(tagprimary_(parent)) & TB_TEMPLATE))
flags |= SPECIALIZE;
btop = instate_declaration_cpp(d, flags);
mk_friend_fn(btop, parent);
if (bindparent_(btop)) syserr("odd friend parent $b", btop);
return btop;
}
else
{ Binder *bgeneric = findbinding(sv, local_scope->class_tag, INCLASSONLY);
if (bgeneric == NULL)
{ /* always global for now (not for ever!). */
bgeneric = global_mk_binder(NULL, d->declname, b_fnconst,
(TypeExpr *)global_list4(SU_Type, t_ovld,
(TypeExpr*)DUFF_ADDR, 0, 0));
/* The t_ovld pseudo is marked to have the most access of any instance. */
/* @@@ However, instances then need checking (and aren't currently). */
/* @@@ global_mk_binder etc need an attributes arg too! */
attributes_(bgeneric) |= bitofaccess_(s_private);
bindparent_(bgeneric) = local_scope->class_tag;
add_local_binder(bgeneric);
}
/* If not the expected t_ovld, then show error and gen up a name */
if (h0_(bgeneric) != s_binder ||
h0_(bindtype_(bgeneric)) != t_ovld)
{ cc_rerr(xbind_rerr_ovld_non_fn, bgeneric);
d->declname = sv = gensymval(1);
bgeneric = global_mk_binder(NULL, d->declname, b_fnconst,
(TypeExpr *)global_list4(SU_Type, t_ovld,
(TypeExpr*)DUFF_ADDR, 0, 0));
/* The t_ovld pseudo is marked to have the most access of any instance. */
/* @@@ However, instances then need checking (and aren't currently). */
/* @@@ global_mk_binder etc need an attributes arg too! */
attributes_(bgeneric) |= bitofaccess_(s_private);
bindparent_(bgeneric) = local_scope->class_tag;
add_local_binder(bgeneric);
}
{ Binder *bspecific;
TypeExpr *bt = bindtype_(bgeneric);
BindList *bl = typeovldlist_(bt);
/* 'operator new()' and 'operator delete()' are always static (12.5) */
/* @@@ this needs to be extended to 'operator new[]()' and 'operator delete[]()' */
bool is_operator_new = strcmp(sv->symname, "__nw") == 0;
bool is_operator_delete = strcmp(sv->symname, "__dl") == 0;
if (is_operator_new || is_operator_delete)
d->declstg |= bitofstg_(s_static);
d->declname = sv = (bindflg & TEMPLATE) ? ovld_function_template_name(sv, dt) :
ovld_instance_name(sv, dt);
if (is_operator_delete)
{ if (bl != NULL)
cc_rerr(xbind_rerr_dl_cant_be_overloaded);
else
{ FormTypeList *f = typefnargs_(dt);
if (!isvoidtype(typearg_(dt)) ||
f == NULL || !isptrtovoidtype(f->fttype) ||
f->ftcdr != NULL && !equivtype(f->ftcdr->fttype, te_size_t))
cc_rerr(xbind_rerr_bad_dl_type, bgeneric);
}
}
else
{ if (is_operator_new)
{ FormTypeList *f = typefnargs_(dt);
if (!isptrtovoidtype(typearg_(dt)) ||
f == NULL || !equivtype(f->fttype, te_size_t))
cc_rerr(xbind_rerr_bad_nw_type, bgeneric);
}
/* check for duplicates */
for (; bl != NULL; bl = bl->bindlistcdr)
{ if (bindsym_(bl->bindlistcar) == sv)
{ cc_rerr(syn_rerr_duplicate_member2(local_scope->class_tag, sv));
break;
}
}
}
if (debugging(DEBUG_BIND)) cc_msg("overload member $r\n", sv);
/* Assert: sv != NULL && isfntype(dt) && */
/* !(d->declstg & (bitofstg_(s_typedef)|bitofstg_(s_friend))) */
/* Now set minargs_(d->decltype) and check that default args trail... */
merge_default_arguments(dt, dt);
bspecific = instate_member_binder(d /*, bindflg*/);
if (h0_(bspecific) != s_binder) syserr("instate_member_overload");
if (bindflg & TEMPLATE)
{ /*bindstg_(bspecific) &= ~bitofstg_(s_inline);*/
bindftlist_(bgeneric) = (BindList *)
global_cons2(SU_Bind, bindftlist_(bgeneric), bspecific);
}
else
typeovldlist_(bt) =
(BindList *)global_cons2(SU_Type, typeovldlist_(bt), bspecific);
if ((attributes_(bspecific) & ACCESSBITS) >
(attributes_(bgeneric) & ACCESSBITS))
attributes_(bgeneric) = (attributes_(bgeneric) & ~ACCESSBITS) |
(attributes_(bspecific) & ACCESSBITS);
return bspecific;
}
}
}
static Scope *enclosing_non_class_scope(void)
{ Scope *scope = local_scope;
while (scope && (scope->class_tag != NULL ||
scope->kind == Scope_TemplateDef ||
scope->kind == Scope_TemplateArgs))
scope = scope->prev;
return scope;
}
/* should declflag here be in d->declstg? */
static Binder *instate_declaration_cpp(DeclRhsList *d, int declflag)
{ Symstr *sv = d->declname;
SET_BITMAP stg = d->declstg;
if (debugging(DEBUG_BIND))
cc_msg("instate_declaration_cpp(%x,%lx): $r\n", declflag,(long)stg,sv);
if (!(declflag & INSTANCE) &&
(h0_(princtype(d->decltype)) == t_fnap) &&
sv != mainsym && /* static overloaded main forbidden! */
/* not top-level impl. of memfn or typedef */
!(stg & b_memfna+b_memfns+bitofstg_(s_typedef)))
{ Scope* save_scope = local_scope;
Binder *bgeneric, *bspecific;
TagBinder *parent = current_member_scope();
if (stg & bitofstg_(s_friend) /*&& !(declflag & TEMPLATE)*/)
local_scope = enclosing_non_class_scope();
bgeneric = findbinding(sv, NULL, FB_LOCALS|FB_THISSCOPE);
/* Should look up at scope where the templatefn is defined! */
if (bgeneric == NULL && declflag & TOPLEVEL)
bgeneric = findbinding(sv, NULL, FB_LOCALS|TOPLEVEL);
/* @@@ next line hacks round implicit fns (or memfn implementations) */
/* being moaned at as 'non-functions!' */
if (bgeneric && bindstg_(bgeneric) & bitofstg_(s_typedef) &&
bindstg_(bgeneric) & u_implicitdef)
bgeneric = 0;
if (bgeneric == NULL || h0_(bindtype_(bgeneric)) == t_ovld)
/* overload extension and resolution here. */
{ TypeExpr *bt;
TypeExpr *dt = princtype(d->decltype);
if (d->declrealname != NULL)
sv = d->declrealname;
d->declname = (declflag & TEMPLATE || contains_typevars(dt)) ?
ovld_function_template_name(sv, dt) : ovld_instance_name(sv, dt);
if (bgeneric != NULL && strcmp(sv->symname, "__dl") == 0 &&
h0_(princtype(dt)) == t_fnap)
{ FormTypeList *f = typefnargs_(dt);
if (!isvoidtype(typearg_(dt)) ||
f == NULL || !isptrtovoidtype(f->fttype) ||
f->ftcdr != NULL)
{ cc_rerr(xbind_rerr_bad_global_dl_type);
d->declname = sv = gensymval(1); /* hide name to recover */
bgeneric = 0;
}
}
/* Maybe some of this code should move to cppfe/overload.c */
if (bgeneric == 0)
{ DeclRhsList *d = mkDeclRhsList(sv,
(TypeExpr *)global_list4(SU_Type, t_ovld, 0, 0, 0), b_fnconst);
bgeneric = instate_declaration_1(d, declflag);
}
bt = bindtype_(bgeneric);
if (bindactuals_(bgeneric) != NULL)
declflag |= SPECIALIZE;
if (declflag & TEMPLATE)
{ BindList *bl;
bspecific = instate_declaration_1(d, declflag);
for (bl = bindftlist_(bgeneric); bl; bl = bl->bindlistcdr)
if (bindsym_(bl->bindlistcar) == bindsym_(bspecific))
{ binduses_(bspecific) |= binduses_(bl->bindlistcar);
bindinstances_(bl->bindlistcar) = bindinstances_(bspecific);
bl->bindlistcar = bspecific;
break;
}
if (!bl)
bindftlist_(bgeneric) = (BindList *)
global_cons2(SU_Bind, bindftlist_(bgeneric), bspecific);
}
else if (declflag & (SPECIALIZE|INSTANTIATE))
{ BindList *tempts = NULL;
Binder *ftemp = NULL;
ExprList *l = NULL;
FormTypeList *ft = typefnargs_(d->decltype);
for (; ft; ft = ft->ftcdr)
l = mkExprList(l, (Expr *)gentempbinder(ft->fttype));
l = (ExprList *)dreverse(l);
if (d->declstg & bitofstg_(s_friend))
{ if (parent && tagprimary_(parent) && tagprimary_(parent)->friends)
{ Friend *f = tagprimary_(parent)->friends;
int sl;
BindList *bl;
ExprList *tactuals = NULL;
Binder *b;
for (; f != NULL; f = f->friendcdr)
{ Binder *ffn = f->u.friendfn;
if (h0_(ffn) != s_binder) continue;
bl = bindftlist_(bgeneric);
for (; bl != NULL; bl = bl->bindlistcdr)
if (bl->bindlistcar == ffn)
tempts = binder_cons2(tempts, ffn);
}
for (b = tagactuals_(parent); b != NULL; b = bindcdr_(b))
{ tactuals =
binder_cons2(tactuals, (bindconst_(b) != NULL) ?
bindconst_(b) :
mk_expr1(s_typespec, bindtype_(b), NULL));
}
tactuals = dreverse((List *)tactuals);
sl = push_var_scope(NULL, Scope_TemplateArgs);
tempts = temp_reduce(tempts, l, tactuals, NULL);
pop_scope_no_check(sl);
f = tagprimary_(parent)->friends;
for (; f != NULL; f = cdr_(f))
{ Binder *ffn = f->u.friendfn;
bl = typeovldlist_(bindtype_(bgeneric));
for (; bl != NULL; bl = bl->bindlistcdr)
if (bl->bindlistcar == ffn)
tempts = binder_cons2(tempts, ffn);
}
}
else
{ BindList *bl = typeovldlist_(bindtype_(bgeneric));
tempts = bindftlist_(bgeneric);
for (; bl != NULL; bl = bl->bindlistcdr)
if (bindsym_(bl->bindlistcar) == d->declname)
tempts = binder_cons2(tempts, bl->bindlistcar);
}
}
else
tempts = temp_reduce(NULL, l, NULL, bgeneric);
if (length((List *)tempts) == 1)
{ bool has_failed = NO;
ScopeSaver env;
TypeExpr *t;
ftemp = tempts->bindlistcar;
if (declflag & INSTANTIATE && bindstg_(ftemp) & b_undef)
cc_err(xbind_err_template_undef, ftemp);
if (d->declstg & bitofstg_(s_friend))
bspecific = ftemp;
else {
Symstr *newsv;
if (declflag & SPECIALIZE)
{ BindList *ins = NULL;
for (ins = bindinstances_(ftemp); ins; ins = ins->bindlistcdr)
{ if (bindsym_(ins->bindlistcar) != d->declname) continue;
if (!(bindstg_(ins->bindlistcar) & b_undef) &&
!(d->declstg & b_undef))
cc_err(xbind_err_template_specialize_after);
break;
}
}
env = bindformals_(ftemp);
t = type_deduction(bindtype_(ftemp), l,
bindactuals_(bgeneric), &env, YES, &has_failed);
if (has_failed)
syserr("type deduction failed: shouldn't happen");
newsv = ovld_tmptfn_instance_name(bindsym_(ftemp), env);
d->declname = ovld_instance_name(newsv, dt);
bspecific = instate_declaration_1(d, declflag);
if ((contains_typevars(d->decltype) && (l || bindactuals_(bgeneric))) ||
declflag & INSTANTIATE)
{ bindenv_(bspecific) = env = globalize_env(env);
bindtype_(bspecific) = t = globalize_typeexpr(t);
fixup_template_arg_type(bindtype_(bspecific), env);
if (declflag & INSTANTIATE && !(bindstg_(ftemp) & b_undef))
add_pendingfn(bindsym_(bgeneric), newsv, t,
(bindstg_(bspecific)&~b_undef), NULL, NULL,
bindtext_(ftemp), env, YES);
}
if (declflag & SPECIALIZE)
add_instance(bspecific, &bindinstances_(ftemp), YES);
add_instance(bspecific, &typeovldlist_(bt), NO);
}
}
else
{ cc_err((tempts == NULL) ? xbind_err_template_none :
xbind_err_template_ambiguous);
bspecific = global_mk_binder(NULL, d->declname, d->declstg, d->decltype);
}
bindactuals_(bgeneric) = NULL;
}
else
{ BindList *bl;
/* Replace existing (necessary? match topbindingchain?) or add... */
bspecific = instate_declaration_1(d, declflag);
stg = d->declstg;
bindstg_(bspecific) |= stg & b_clinkage;
bt = bindtype_(bgeneric);
for (bl = typeovldlist_(bt); bl != NULL; bl = bl->bindlistcdr)
{ Binder *b = bl->bindlistcar;
if (bindsym_(b) == bindsym_(bspecific))
{ bl->bindlistcar = bspecific;
bt = 0;
}
else if ((stg & b_clinkage) && (bindstg_(b) & b_clinkage))
{ cc_rerr(xbind_rerr_more_than_one_C_linkage, sv);
stg &= ~b_clinkage;
bindstg_(bspecific) &= ~b_clinkage;
}
}
if (bt)
typeovldlist_(bt) = (BindList *)
global_cons2(SU_Type, typeovldlist_(bt), bspecific);
if ((stg & b_clinkage) && realbinder_(bspecific) == 0)
{ realbinder_(bspecific) =
global_mk_binder(0, sv,
bindstg_(bspecific), bindtype_(bspecific));
bindstg_(bspecific) |= b_impl;
}
}
local_scope = save_scope;
return bspecific;
}
else
cc_rerr(xbind_rerr_ovld_non_fn, bgeneric);
local_scope = save_scope;
}
return instate_declaration_1(d, declflag);
}
static int s_contents_in(Expr *e)
{ if (e == NULL)
return 0;
if (h0_(e) == s_dot || h0_(e) == s_content)
return s_contents_in(arg1_(e)) + (h0_(e) == s_content ? 1 : 0);
return 0;
}
static Binder *implicit_decl_cpp(Symstr* sv)
{
DeclRhsList d;
TypeExpr *t = te_int;
TypeExprFnAux s;
d.declcdr = NULL;
d.declname = sv;
d.u.init = NULL;
d.decltype = g_mkTypeExprfn(t_fnap, t, 0, 0,
packTypeExprFnAux(s, 0, 1999, 0, 0,
fpregargs_disabled ? f_nofpregargs : 0)); /* minargs_ */
d.declstg = bitofstg_(s_extern)|b_clinkage|b_fnconst|b_undef;
d.fileline = curlex.fl;
d.declbind = NULL;
d.declrealname = NULL;
d.tentative = NULL;
return instate_declaration_cpp(&d, TOPLEVEL);
}
static Expr *simpler_path_of(Expr *e1, Expr *e2)
{
/* e1 and e2 are a tower of '.' and '*' operators. Choose whichever */
/* has fewer '*' operators (the '.'s get coalesced later...). */
return s_contents_in(e1) < s_contents_in(e2) ? e1 : e2;
}
/* The following provide for-style iterators for C++ classes which */
/* can steer round CB_CORE etc. See mip/bind.h. */
ClassMember *ClassMemo_next(ClassMemo *m)
{ ClassMember *p;
if ((p = m->core) != 0) return (m->core = memcdr_(p), p);
if ((p = m->outer) != 0) return (m->outer = memcdr_(p), p);
return 0;
}
ClassMember *ClassMemo_first(ClassMemo *m, ClassMember *p)
{ m->core = 0, m->outer = p;
if (p && attributes_(p) & CB_CORE)
{ TypeExpr *t = memtype_(p);
if (h0_(t) == s_typespec && typespecmap_(t) & CLASSBITS)
{ TagBinder *tb = typespectagbind_(t);
ClassMember *q = tagbindmems_(tb);
m->core = q, m->outer = memcdr_(p);
}
else
syserr("ClassMemo_first");
}
return ClassMemo_next(m);
}
/* This routine is used to PUSH scopes A and B for definitions like */
/* int A::B::x = a+b; or int A::B::f() { return a+b; } */
/* where A::a and B::b. */
int push_multi_scope(TagBinder *cl)
{ int x = scope_level;
if (cl)
{ push_multi_scope(cl->tagparent);
if (tagbindbits_(cl) & TB_TEMPLATE)
push_var_scope(tagformals_(cl), Scope_TemplateArgs);
push_scope(cl, Scope_Ord);
}
return x;
}
static Expr *path_to_member_2(ClassMember *member, TagBinder *b, int flags,
ClassMember *vbases, TagBinder *privately_deriving_class)
{ ClassMember *l = tagbindmems_(b);
if (l != NULL && (attributes_(l) & CB_CORE))
{ Expr *e;
/* This section is both useful for testing (in effect implementing a */
/* language extension allowing access to bases by name) and used by */
/* pointercast() which generates casts between base and derived types. */
e = path_to_member_1(member, b, (flags & ~FB_INHERIT),
NULL, privately_deriving_class);
if (e != NULL) return e;
b = typespectagbind_(memtype_(l));
if (b == 0) syserr("path_to_core_member(0,...)");
}
return path_to_member_1(member, b, flags, vbases, privately_deriving_class);
}
int derivation_level;
ClassMember *derived_from(TagBinder *base, TagBinder *scope)
{ ClassMember *l, *ll;
if (debugging(DEBUG_BIND)) cc_msg("derived_from($b,$b)\n", base, scope);
derivation_level++;
/* For why the next line is present consider: */
/* class A{}; class B:virtual A{}; class C:B {}; */
/* without it C does not appear derived from B, only core(B). */
if ((l = tagbindmems_(base)) != NULL && attributes_(l) & CB_CORE)
return derived_from(typespectagbind_(princtype(memtype_(l))), scope);
/* But we also need to do the same to scope so that we never have */
/* derived_from(C,C) being true: */
/* Maybe the correct thing to use is a 'path_to_baseclass' function */
/* since used as a predicate or to get a name for path_to_member... */
if ((l = tagbindmems_(scope)) != NULL && attributes_(l) & CB_CORE)
return derived_from(base, typespectagbind_(princtype(memtype_(l))));
for (l = tagbindmems_(scope); l != NULL; l = memcdr_(l))
if (attributes_(l) & (CB_BASE | CB_VBPTR))
{ TypeExpr *t = princtype(memtype_(l));
if (attributes_(l) & CB_VBPTR) t = princtype(typearg_(t));
if (base == typespectagbind_(t)) return l;
}
for (l = tagbindmems_(scope); l != NULL; l = memcdr_(l))
if (attributes_(l) & (CB_BASE | CB_VBPTR))
{ TypeExpr *t = princtype(memtype_(l));
if (attributes_(l) & CB_VBPTR) t = princtype(typearg_(t));
if ((ll = derived_from(base, typespectagbind_(t))) != NULL)
return ll;
}
return 0;
}
bool derived_fromeq(TagBinder *base, TagBinder *scope)
{
return core_class(base) == core_class(scope) ||
derived_from(base, scope) != NULL;
}
/* Vblist is the list of members at the top level of the derivation - */
/* starting with the core member and followed by the vbases. Off is the */
/* offset of the base member l if it is not virtual, the offset of the */
/* virtual base pointer member l if it is. Return a cheat s_invisible */
/* Expr containing an extra field with the base offset in it. */
static Expr *base_and_offset(ClassMember *l, ClassMember *vblist, int32 off,
TypeExpr *t)
{ if (attributes_(l) & CB_VBPTR)
{ TypeExpr *t = typearg_(memtype_(l));
ClassMember *vb;
for (vb = vblist; vb != NULL; vb = memcdr_(vb))
{ if (equivtype(memtype_(vb), t) == 2)
{ l = vb;
off = memwoff_(l);
break;
}
}
if (vb == NULL)
syserr("Can't find VBASE for VBPTR $r", memsv_(l));
}
return mk_expr3(s_invisible, t, (Expr *)l, NULL, (Expr *)(IPtr)off);
}
static int is_vbasetype(TypeExpr *t, ClassMember *vblist)
{ ClassMember *vb;
TypeExpr *pt = princtype(t);
if (isclasstype_(pt))
for (vb = vblist; vb != NULL; vb = memcdr_(vb))
if (equivtype(memtype_(vb), t) == 2)
return 1;
return 0;
}
static bool is_dependent_base(TypeExpr *t, ScopeSaver actuals)
{
for (; actuals; actuals = bindcdr_(actuals))
if (equivtype(t, bindtype_(actuals)))
return YES;
/* base class B<T> is defined at the point of defn */
#if 0
if (tagactuals_(typespectagbind_(princtype(t))) != NULL)
return YES;
#endif
return NO;
}
static Expr *path_to_base_member(ClassMember *member, TagBinder *b,
int flags, ClassMember *vbases, TagBinder *privately_deriving_class)
{ ClassMember *l;
Expr *path = NULL, *tmp, *tmpi, *e;
/* search the inherited base classes for a name match... */
for (l = tagbindmems_(b); l != NULL; l = memcdr_(l))
{ TypeExpr *t;
if (!is_datamember_(l) ||
!(attributes_(l) & (CB_BASE | CB_VBPTR))) break;
t = memtype_(l);
/* Ignore dependent base if it is an instantiation */
if ((flags == ALLSCOPES) && has_template_arg_scope() &&
is_dependent_base(t, tagactuals_(b)))
continue;
if (attributes_(l) & CB_VBPTR) t = typearg_(t);
tmp = path_to_member_2(member, typespectagbind_(t), flags, vbases,
(attributes_(l) & bitofaccess_(s_private)) ? b :
privately_deriving_class);
if (tmp == NULL || tmp == errornode) continue;
/* not found, or error already diagnosed */
/* Record the base member containing the found entity, unless */
/* already recorded at a deeper level of recursion. */
if (h0_(tmp) == s_invisible)
{ tmpi = tmp;
tmp = arg2_(tmpi);
}
else
tmpi = base_and_offset(l, vbases, memwoff_(l), t);
if (h0_(tmp) == s_dot || h0_(tmp) == s_content)
{ e = mk_exprwdot(s_dot, memtype_(l),
nullbinder(bindparent_(l)), memwoff_(l));
if (attributes_(l) & CB_VBPTR) e = mk_expr1(s_content, t, e);
tmp = rooted_path(tmp, 0, e);
}
arg2_(tmpi) = tmp;
if (path == NULL) {path = tmpi; continue;}
if (accessOK & 4) break; /* already found to be ambiguous */
/* Check for ambiguity between path and tmpi: the arg2_() field */
/* is an exprdotmemfn, a (Binder *) or an (Expr *) representing */
/* a path to a member. Identical (Binder *)s are unambiguous; */
/* exprdotmemfns and path expressions cannot be identical... */
if (arg2_(path) == tmp) continue;
/* Second, check for paths to the same (virtual) base member... */
/* LDS @@@ 14-Oct-94 OR same virtual base pointer... */
/* NB if the containing members are identical and the entity */
/* reprns are not, then the entities are represented by path */
/* exprns and, hence, are data members/exprdotmemfns. */
if (arg1_(path) == arg1_(tmpi)
||
h0_(tmp) == s_dot && h0_(arg2_(path)) == s_dot &&
type_(tmp) == type_(arg2_(path)) &&
h0_(type_(tmp)) == t_content &&
is_vbasetype(typearg_(type_(tmp)), vbases))
{ arg2_(path) = simpler_path_of(arg2_(path), tmp);
continue;
}
/* Third, see whether path dominates tmpi or vice versa. If so, */
/* retain the dominant entity and discard the other. */
if (type_derived_from(memtype_((ClassMember *)arg1_(path)),
memtype_((ClassMember *)arg1_(tmpi))))
{ /* the name of the entity described by tmpi dominates that */
/* of the entity described by path, so retain tmpi. */
path = tmpi;
continue;
}
if (type_derived_from(memtype_((ClassMember *)arg1_(tmpi)),
memtype_((ClassMember *)arg1_(path))))
{ /* the name of the entity described by path dominates that */
/* of the entity described by tmpi, so discard tmpi. */
continue;
}
/* CHECK_INHERITED_VIRTUAL is now (03-Oct-1997) a misnomer;
it now finds the virtual base member instead, if existed and
left-most preferred.
*/
if (flags & CHECK_INHERITED_VIRTUAL)
{ Binder *b1 = exb_(arg2_(path));
Binder *b2 = exb_(arg2_(tmpi));
if (h0_(b1) == s_binder && h0_(b2) == s_binder &&
isfntype(bindtype_(b1)) && isfntype(bindtype_(b2)))
{
#if 0
if ((bindstg_(b1) & bitofstg_(s_virtual)) !=
(bindstg_(b2) & bitofstg_(s_virtual)))
cc_rerr(xbind_rerr_both_virtual_and_nonvirtual,
(Symstr *)member, b);
#endif
if (!(bindstg_(b1) & bitofstg_(s_virtual)) &&
bindstg_(b2) & bitofstg_(s_virtual))
path = tmpi;
continue;
}
}
{ Symstr *sv = h0_(member) == s_identifier ?
(Symstr *)member : memsv_(member);
/* if b is a CORE class, use the class containing b, so that 'class C' */
/* rather than 'class __K_C' will occur in the diagnostic */
TagBinder *cl = tagbindbits_(b) & TB_CORE ? b->tagparent : b;
cc_rerr(xbind_rerr_is_ambiguous_name, sv, cl);
accessOK |= 4; /* suppress all but the first complaint */
break; /* and terminate the search now... */
}
}
return path;
}
TagBinder *current_member_scope(void)
{ Scope *scope;
for (scope = local_scope; scope != NULL; scope = scope->prev)
if (scope->class_tag != NULL) return scope->class_tag;
return NULL;
}
static Binder *accessing_fn;
static TagBinder *accessing_class;
TagBinder *set_access_context(TagBinder *cl, Binder *fn)
{ TagBinder *tb = accessing_class;
if (cl == NULL && fn == NULL)
{ accessing_class = 0;
accessing_fn = 0;
}
else
{ if (cl != NULL) accessing_class = cl;
if (fn != NULL) accessing_fn = fn;
}
return tb;
}
static bool accessor_is_friendof(TagBinder *ofclass)
{ Friend * f;
for (f = ofclass->friends; f != NULL; f = f->friendcdr)
{ Binder *friendfn = f->u.friendfn;
TagBinder *friendclass = f->u.friendclass;
/* /* template member fn not done e.g. t14c.dir/_1453W31.cpp */
if (accessing_class == friendclass ||
accessing_fn == friendfn ||
(h0_(friendfn) == s_binder && bindformals_(friendfn) &&
is_an_instance(bindinstances_(friendfn), accessing_fn)) ||
(h0_(friendclass) == s_tagbind && tagbindbits_(friendclass) & TB_TEMPLATE &&
is_an_instance(taginstances_(friendclass), (Binder *)accessing_class)))
return 1;
}
return 0;
}
void mk_friend_class(TagBinder *classtag, TagBinder *ofclass)
{ Friend *f;
if (debugging(DEBUG_BIND))
{ if (h0_(classtag) == s_tagbind)
cc_msg("adding friend $c to $c\n", classtag, ofclass);
else
cc_msg("added friend fn $b to $c\n", classtag, ofclass);
}
if (!(tagbindbits_(ofclass) & TB_BEINGDEFD))
syserr("adding friend to completed scope $c", ofclass);
for (f = ofclass->friends; f != NULL; f = f->friendcdr)
{ if (f->u.friendclass == classtag) return;
}
f = (Friend *) GlobAlloc(SU_Other, sizeof(Friend));
/* @@@ Could Fix the storage class better here... */
f->friendcdr = ofclass->friends;
ofclass->friends = f;
f->u.friendclass = classtag;
}
void mk_friend_fn(Binder *bspecific, TagBinder *ofclass)
{ mk_friend_class((TagBinder *)bspecific, ofclass);
}
/* Access control: (i) whether access is permitted or not is a property */
/* of a path through a derivation and (ii) if there are multiple paths */
/* to the same entity then access is permitted if at least one path */
/* allows access. Below, FB_PRIVATELY_DERIVED is set when searching a */
/* privately derived base class. */
void check_access(ClassMember *m, TagBinder *privately_deriving_class)
{ TagBinder *tb = bindparent_(m);
if (accessOK) return; /* already determined or more serious error */
if (privately_deriving_class == 0 &&
(attributes_(m) & bitofaccess_(s_public)))
accessOK = 1;
else if (accessing_class != NULL)
{ if ((attributes_(m) & bitofaccess_(s_private)))
{ if (core_class(accessing_class) == core_class(tb) ||
tagbindsym_(accessing_class) == bindsym_(m)) accessOK =1;
}
else
{
/* A protected member or a privately derived public or protected member */
/* Access is OK if the accessing class is derived_fromeq this class and */
/* the privately deriving class is derived_fromeq the accessing class. */
if (derived_fromeq(tb, accessing_class) &&
((feature & FEATURE_CFRONT) ||
(!accessing_fn || rootOfPath == NULL ||
rootOfPath->bindlistcdr->bindlistcar == NULL ||
/* only interested in the leftScope, if there is one */
derived_fromeq(accessing_class,
(TagBinder *)rootOfPath->bindlistcdr->bindlistcar)) &&
(privately_deriving_class == 0 ||
derived_fromeq(accessing_class, privately_deriving_class))))
accessOK = 1;
}
}
if (!accessOK && (accessor_is_friendof(tb) ||
(rootOfPath != NULL &&
(rootOfPath->bindlistcar == NULL ||
accessor_is_friendof((TagBinder *)rootOfPath->bindlistcar)) &&
(rootOfPath->bindlistcdr->bindlistcar == NULL ||
accessor_is_friendof((TagBinder *)rootOfPath->bindlistcdr->bindlistcar)))))
accessOK = 1;
}
bool no_access_context(void)
{ return (!accessing_class && !accessing_fn);
}
void check_access_1(ClassMember *l, TagBinder *scope)
{ TagBinder *old_accessing_class = accessing_class;
int old_accessOK = accessOK;
if (!scope && attributes_(l) &
(bitofaccess_(s_private)|bitofaccess_(s_protected)) &&
!accessor_is_friendof(bindparent_(l)))
{ diagnose_access(bindsym_(l), bindparent_(l));
return;
}
accessing_class = scope;
accessOK = 0;
check_access(l, 0);
accessing_class = old_accessing_class;
accessOK = old_accessOK;
}
Binder *instate_classname(DeclRhsList *d, TagBinder *tb)
/* Instate a classname typedef in the same scope as its tagbinder */
/* Note: findtag_in_members() finds tb by address, not by name. */
{ Binder *b;
Scope *saved_scope = local_scope, *scope;
for (scope = local_scope; scope != NULL; scope = scope->prev)
{ ClassMember *l;
TagBinder *cl = scope->class_tag;
if (cl != NULL)
l = tagbindmems_(core_class(cl));
else
l = scope->scopemems;
if (findtag_in_members((Symstr *)tb, l) != 0) break;
}
local_scope = scope;
b = instate_declaration(d, scope == NULL ? TOPLEVEL :
(tagbindbits_(tb) & TB_TEMPLATE) ? GLOBALSTG : LOCALSCOPE);
local_scope = saved_scope;
return b;
}
bool is_two_arg_delete(Binder* delgeneric)
{ if (bindparent_(delgeneric) == 0) return NO;
{ TypeExpr *bt = bindtype_(delgeneric);
BindList *bl;
FormTypeList *f;
if (h0_(bt) != t_ovld) syserr("$b is not a member function?", delgeneric);
bl = typeovldlist_(bt);
bt = princtype(bindtype_(bl->bindlistcar));
if (h0_(bt) != t_fnap) syserr("overloaded non-function $b?", bl->bindlistcar);
f = typefnargs_(bt);
return f->ftcdr != NULL;
}
}
/* Caution: this is not of general utility; see syserr below. */
bool is_local_binder(Binder *b)
{ Scope *scope = local_scope;
TagBinder *cl;
if (scope == NULL || scope->kind == Scope_Args)
return NO;
cl = current_member_scope();
if (!cl) syserr("no local class");
for (; scope && scope->class_tag != cl; scope = scope->prev)
if (find_scopemember(bindsym_(b), scope->scopemems) != NULL)
return YES;
/* now for template actuals */
scope = scope->prev;
for (; scope && (scope->kind == Scope_TemplateArgs ||
scope->kind == Scope_TemplateDef);
scope = scope->prev)
if (find_scopemember(bindsym_(b), scope->scopemems) != NULL)
return YES;
return NO;
}
bool is_template_arg_binder(Expr *e)
{ Scope *scope = local_scope;
Binder *temp, *b;
if (!e) return NO;
e = skip_invisible_or_cast(e);
if (h0_(e) == s_binder) b = exb_(e);
else return NO;
for (; scope; scope = scope->prev)
{ if (scope->kind != Scope_TemplateArgs) continue;
for (temp = scope->scopemems; temp; temp = bindcdr_(temp))
if (bindsym_(temp) == bindsym_(b)) return YES;
}
return NO;
}
bool has_template_arg_scope(void)
{ Scope *scope = local_scope;
for(; scope; scope = scope->prev)
if (scope->kind == Scope_TemplateArgs) return YES;
return NO;
}
BindList *clone_bindlist(BindList * bl, bool glob)
{ Binder *b;
TypeExpr *t;
if (!bl) return NULL;
b = (Binder *) ((glob) ? GlobAlloc(SU_Bind, sizeof(Binder)) :
BindAlloc(sizeof(Binder)));
memcpy((char *)b, (char *)bl->bindlistcar, sizeof(Binder));
t = clone_typeexpr(bindtype_(bl->bindlistcar));
bindtype_(b) = (glob) ? globalize_typeexpr(t) : t;
return (glob) ? (BindList *)global_cons2(SU_Bind,
clone_bindlist(bl->bindlistcdr, glob), b) :
mkBindList(clone_bindlist(bl->bindlistcdr, glob), b);
}
ScopeSaver dup_template_scope(void)
{ ClassMember *l;
ScopeSaver p = NULL, q = NULL;
Scope *s = local_scope;
bool glob;
while (s != NULL && (s->kind == Scope_TemplateArgs || s->kind == Scope_Args))
s = s->prev;
glob = (s == NULL);
l = glob ? topbindingchain : s->scopemems;
for (; l; l = bindcdr_(l))
switch (h0_(l)) {
case s_binder:
{ ClassMember *b;
b = (ClassMember *)GlobAlloc(SU_Bind, SIZEOF_NONAUTO_BINDER);
memcpy((char *)b, (char *)l, SIZEOF_NONAUTO_BINDER);
if (h0_(bindtype_(l)) == t_ovld)
{ TypeExpr *e;
e = (TypeExpr *)global_list4(SU_Type, t_ovld, 0, 0, 0);
typeovldlist_(e) = clone_bindlist(typeovldlist_(bindtype_(b)), YES);
bindtype_(b) = e;
}
else
bindtype_(b) = globalize_typeexpr(bindtype_(l));
if (p == NULL) p = q = b; else bindcdr_(q) = b, q = b;
break;
}
case s_tagbind:
break;
default:
syserr("Unrecognizable scope mem");
}
return p;
}
void save_labels(LabBind **lc, LabBind **symlabs)
{ int i = 0;
*lc = labelchain;
if (length((List *)labelchain) > MAX_SAVED_LABELS)
syserr("too many labels to save");
for (; labelchain; labelchain = labelchain->labcdr)
{ symlabs[i++] = symlab_(labelchain->labsym);
symlab_(labelchain->labsym) = NULL;
}
}
void restore_labels(LabBind *lc, LabBind **symlabs)
{ int i = 0;
labelchain = lc;
for (; lc; lc = lc->labcdr, i++)
symlab_(lc->labsym) = symlabs[i];
}
/* end of cppfe/xbind.c */
|
stardot/ncc | mip/aout.h | <reponame>stardot/ncc<filename>mip/aout.h<gh_stars>0
/*
* Modified a.out.h for use with ARM. In fact the mod is to
* a comment only and concerns the value of r_length in a
* relocation record when the relocated object is an ARM branch.
* LJA.
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
/*
* Copyright (c) 1980 Regents of the University of California.
* SPDX-Licence-Identifier: BSD-1-Clause
* All rights reserved. The Berkeley software License Agreement
* specifies the terms and conditions for redistribution.
*
* @(#)a.out.h 5.1 (Berkeley) 5/30/85
*/
/*
* For cross-compilation
*/
#define PAGESIZE 32768
/*
* Header prepended to each a.out file.
*/
struct exec {
#ifdef TARGET_IS_SPARC
unsigned char a_toolversion; /* dynamic + what is this? */
unsigned char a_machtype; /* machine type */
unsigned short a_magic; /* magic number */
#else
long a_magic; /* magic number */
#endif
unsigned long a_text; /* size of text segment */
unsigned long a_data; /* size of initialized data */
unsigned long a_bss; /* size of uninitialized data */
unsigned long a_syms; /* size of symbol table */
unsigned long a_entry; /* entry point */
unsigned long a_trsize; /* size of text relocation */
unsigned long a_drsize; /* size of data relocation */
#ifdef TARGET_IS_CLIPPER
unsigned int /* Per-process flags */
a_format:1, /* If true, rest are defined */
a_rz:1, /* If true, zero is readable */
a_ip:1, /* If true, enable instruction prefetch */
a_tcs:3, /* Text cache strategy */
a_dcs:3, /* Data cache strategy */
a_scs:3, /* Stack cache strategy */
a_dummy:20;
#endif
};
#ifdef TARGET_IS_CLIPPER
#define OMAGIC 01407 /* old impure format */
#define NMAGIC 01410 /* read-only text */
#define ZMAGIC 01413 /* demand load format */
#else
#define OMAGIC 0407 /* old impure format */
#define NMAGIC 0410 /* read-only text */
#define ZMAGIC 0413 /* demand load format */
#endif
#define M_OLDSUN2 0 /* old sun-2 executable files */
#define M_68010 1 /* runs on either 68010 or 68020 */
#define M_68020 2 /* runs only on 68020 */
#define M_SPARC 3 /* runs on SPARC only */
/*
* Macros which take exec structures as arguments and tell whether
* the file has a reasonable magic number or offsets to text|symbols|strings.
*/
#define N_BADMAG(x) \
(((x).a_magic)!=OMAGIC && ((x).a_magic)!=NMAGIC && ((x).a_magic)!=ZMAGIC)
#define N_TXTOFF(x) \
((x).a_magic==ZMAGIC ? PAGESIZE : sizeof (struct exec))
#define N_SYMOFF(x) \
(N_TXTOFF(x) + (x).a_text+(x).a_data + (x).a_trsize+(x).a_drsize)
#define N_STROFF(x) \
(N_SYMOFF(x) + (x).a_syms)
/*
* Format of a relocation datum.
*/
#ifdef TARGET_IS_SPARC
struct relocation_info {
unsigned int r_address;
unsigned int r_symbolnum :24,
r_extern :1,
:2,
r_type :5;
int r_addend;
};
#define RELOC_32 2
#define RELOC_WDISP30 6
#define RELOC_WDISP22 7
#define RELOC_HI22 8
#define RELOC_22 9
#define RELOC_13 10
#define RELOC_LO10 11
#else
struct relocation_info {
int r_address; /* address which is relocated */
unsigned int r_symbolnum:24, /* local symbol ordinal */
r_pcrel:1, /* was relocated pc relative already */
r_length:2, /* 0=byte, 1=word, 2=long 3=ARM branch */
r_extern:1, /* does not include value of sym referenced */
r_neg:1, /* -ve relocation */
:3; /* nothing, yet */
};
#endif
#define RELINFOSZ 8
/*
* Format of a symbol table entry; this file is included by <a.out.h>
* and should be used if you aren't interested the a.out header
* or relocation information.
*/
struct nlist {
union {
char *n_name; /* for use when in-core */
long n_strx; /* index into file string table */
} n_un;
unsigned char n_type; /* type flag, i.e. N_TEXT etc; see below */
char n_other; /* unused */
short n_desc; /* see <stab.h> */
unsigned long n_value; /* value of this symbol (or sdb offset) */
};
#define NLISTSZ 12
#define n_hash n_desc /* used internally by ld */
/*
* Simple values for n_type.
*/
#define N_UNDF 0x0 /* undefined */
#define N_ABS 0x2 /* absolute */
#define N_TEXT 0x4 /* text */
#define N_DATA 0x6 /* data */
#define N_BSS 0x8 /* bss */
#define N_COMM 0x12 /* common (internal to ld) */
#define N_FN 0x1f /* file name symbol */
#define N_EXT 01 /* external bit, or'ed in */
#define N_TYPE 0x1e /* mask for all the type bits */
/*
* Sdb entries have some of the N_STAB bits set.
* These are given in <stab.h>
*/
#define N_STAB 0xe0 /* if any of these bits set, a SDB entry */
/*
* Format for namelist values.
*/
#define N_FORMAT "%08x"
|
stardot/ncc | mip/store.h | /*
* mip/store.h, version 6
* Copyright (C) Codemist Ltd., 1988.
* Copyright (C) Acorn Computers Ltd., 1988.
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
/* There are four classes or storage:
PermAlloc: permanent (for cmd-line arguments, etc)
GlobAlloc: per translation unit
BindAlloc: until alloc_reinit
SynAlloc: until drop_local_store
alloc_mark/alloc_unmark can be used to hold keep Syn/Bind store
past it's normal life.
*/
/* AM memo: I would like to improve the security of the following by */
/* discouraging the use of macros involving casts (or void *). */
#ifndef _store_LOADED
#define _store_LOADED 1
extern void ClearToNull(void **a, int32 n);
typedef enum {
SU_Data,
SU_Xref,
SU_Xsym,
SU_Sym,
SU_Bind,
SU_Type,
SU_Const,
SU_PP,
SU_Dbg,
SU_Inline,
SU_Other
} StoreUse;
#define global_cons2(t,a,b) xglobal_cons2(t,(IPtr)(a),(IPtr)(b))
#define global_list3(t,a,b,c) xglobal_list3(t,(IPtr)(a),(IPtr)(b),(IPtr)(c))
#define global_list4(t,a,b,c,d) xglobal_list4(t,(IPtr)(a),(IPtr)(b),(IPtr)(c),(IPtr)(d))
#define global_list5(t,a,b,c,d,e) xglobal_list5(t,(IPtr)(a),(IPtr)(b),(IPtr)(c),(IPtr)(d),(IPtr)(e))
#define global_list6(t,a,b,c,d,e,f) xglobal_list6(t,(IPtr)(a),(IPtr)(b),(IPtr)(c),(IPtr)(d),(IPtr)(e),(IPtr)(f))
extern VoidStar xglobal_cons2(StoreUse t, IPtr a, IPtr b);
extern VoidStar xglobal_list3(StoreUse t, IPtr a, IPtr b, IPtr c);
extern VoidStar xglobal_list4(StoreUse t, IPtr a, IPtr b, IPtr c, IPtr d);
extern VoidStar xglobal_list5(StoreUse t, IPtr a, IPtr b, IPtr c, IPtr d, IPtr e);
extern VoidStar xglobal_list6(StoreUse t, IPtr a, IPtr b, IPtr c, IPtr d, IPtr e, IPtr f);
#ifdef CALLABLE_COMPILER
extern VoidStar xglobal_list7(StoreUse t, IPtr a, IPtr b, IPtr c, IPtr d, IPtr e, IPtr f, IPtr g);
#endif
extern VoidStar GlobAlloc(StoreUse t, int32 n);
#ifndef CALLABLE_COMPILER
extern VoidStar PermAlloc(int32 n);
extern VoidStar BindAlloc(int32 n);
extern VoidStar SynAlloc(int32 n);
extern VoidStar discard2(VoidStar p);
extern VoidStar discard3(VoidStar p);
#else
#define PermAlloc(n) GlobAlloc(SU_Other,n)
#define BindAlloc(n) GlobAlloc(SU_Other,n)
#define SynAlloc(n) GlobAlloc(SU_Other,n)
#define discard2 discard
#define discard3 discard
extern VoidStar discard(VoidStar p);
#endif
#define NewPerm(T) ((T *)PermAlloc(sizeof(T)))
#define NewPermN(T,n) ((T *)PermAlloc((int32)sizeof(T)*(n)))
#define NewPermK(T,n) ((T *)PermAlloc((int32)sizeof(T)+(n)))
#define NewGlob(T,sort) ((T *)GlobAlloc((sort), sizeof(T)))
#define NewGlobN(T,sort,n) ((T *)GlobAlloc((sort), (int32)sizeof(T)*(n)))
#define NewGlobK(T,sort,n) ((T *)GlobAlloc((sort), (int32)sizeof(T)+(n)))
#define NewSyn(T) ((T *)SynAlloc(sizeof(T)))
#define NewSynN(T,n) ((T *)SynAlloc((int32)sizeof(T)*(n)))
#define NewSynK(T,n) ((T *)SynAlloc((int32)sizeof(T)+(n)))
#define NewBind(T) ((T *)BindAlloc(sizeof(T)))
#define NewBindN(T,n) ((T *)BindAlloc((int32)sizeof(T)*(n)))
#define NewBindK(T,n) ((T *)BindAlloc((int32)sizeof(T)+(n)))
#define syn_cons2(a, b) xsyn_list2((IPtr)(a), (IPtr)(b))
#define binder_cons2(a, b) xbinder_list2((IPtr)(a), (IPtr)(b))
#define binder_icons2(a, b) xbinder_list2((IPtr)(a), b)
#define binder_icons3(a, b, c) xbinder_list3((IPtr)(a), b, c)
#define syn_list2(a,b) xsyn_list2((IPtr)(a),(IPtr)(b))
#define syn_list3(a,b,c) xsyn_list3((IPtr)(a),(IPtr)(b),(IPtr)(c))
#define syn_list4(a,b,c,d) xsyn_list4((IPtr)(a),(IPtr)(b),(IPtr)(c),(IPtr)(d))
#define syn_list5(a,b,c,d,e) xsyn_list5((IPtr)(a),(IPtr)(b),(IPtr)(c),(IPtr)(d),(IPtr)(e))
#define syn_list6(a,b,c,d,e,f) xsyn_list6((IPtr)(a),(IPtr)(b),(IPtr)(c),(IPtr)(d),(IPtr)(e),(IPtr)(f))
#define syn_list7(a,b,c,d,e,f,g) xsyn_list7((IPtr)(a),(IPtr)(b),(IPtr)(c),(IPtr)(d),(IPtr)(e),(IPtr)(f),(IPtr)(g))
#ifndef CALLABLE_COMPILER
extern VoidStar xsyn_list2(IPtr a, IPtr b);
extern VoidStar xsyn_list3(IPtr a, IPtr b, IPtr c);
extern VoidStar xsyn_list4(IPtr a, IPtr b, IPtr c, IPtr d);
extern VoidStar xsyn_list5(IPtr a, IPtr b, IPtr c, IPtr d, IPtr e);
extern VoidStar xsyn_list6(IPtr a, IPtr b, IPtr c, IPtr d, IPtr e, IPtr f);
extern VoidStar xsyn_list7(IPtr a, IPtr b, IPtr c, IPtr d, IPtr e, IPtr f, IPtr g);
#else
#define xsyn_list2(a,b) xglobal_cons2(SU_Other,a,b)
#define xsyn_list3(a,b,c) xglobal_list3(SU_Other,a,b,c)
#define xsyn_list4(a,b,c,d) xglobal_list4(SU_Other,a,b,c,d)
#define xsyn_list5(a,b,c,d,e) xglobal_list5(SU_Other,a,b,c,d,e)
#define xsyn_list6(a,b,c,d,e,f) xglobal_list6(SU_Other,a,b,c,d,e,f)
#define xsyn_list7(a,b,c,d,e,f,g) xglobal_list7(SU_Other,a,b,c,d,e,f,g)
#endif
#define binder_list2(a,b) xbinder_list2((IPtr)(a),(IPtr)(b))
#define binder_list3(a,b,c) xbinder_list3((IPtr)(a),(IPtr)(b),(IPtr)(c))
#ifndef CALLABLE_COMPILER
extern VoidStar xbinder_list2(IPtr a, IPtr b);
extern VoidStar xbinder_list3(IPtr a, IPtr b, IPtr c);
typedef struct Mark Mark;
extern Mark* alloc_mark(void);
extern void alloc_unmark(Mark*);
extern void drop_local_store(void);
extern void alloc_reinit(void);
extern void alloc_noteAEstoreuse(void);
extern void show_store_use(void);
extern void alloc_perfileinit(void);
extern void alloc_perfilefinalise(void);
extern void alloc_initialise(void);
extern void alloc_finalise(void);
#else
#define xbinder_list2(a,b) xglobal_cons2(SU_Other,a,b)
#define xbinder_list3(a,b,c) xglobal_list3(SU_Other,a,b,c)
#define alloc_mark() ((void)0)
#define alloc_unmark() ((void)0)
#define drop_local_store() ((void)0)
#define alloc_reinit() ((void)0)
#define alloc_noteAEstoreuse() ((void)0)
#define show_store_use() ((void)0)
#define alloc_perfileinit() ((void)0)
#define alloc_perfilefinalise() ((void)0)
#define alloc_initialise() ((void)0)
#define alloc_finalise() ((void)0)
#endif /* CALLABLE_COMPILER */
#endif
|
stardot/ncc | mip/aetree.c | <reponame>stardot/ncc<filename>mip/aetree.c
/*
* C compiler file aetree.c, version 42
* Copyright (C) Codemist Ltd., 1987.
* Copyright (C) Acorn Computers Ltd., 1988
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
#ifdef __STDC__
# include <stdarg.h>
#else
# include <varargs.h>
#endif
#include <stddef.h>
#include <ctype.h>
#include <string.h>
#include "globals.h"
#include "aetree.h"
#include "defs.h"
#include "store.h"
#include "aeops.h"
#include "bind.h"
#include "builtin.h"
/*/* The following inclusion of sem.h for isbitfield() and moan_nonconst() */
/* shows a structural weakness. Mid-end code should not depend on the */
/* front-end in this sort of way. */
#include "sem.h"
#include "errors.h"
#include "syn.h" /* for copy_env() */
AEop tagbindsort(TagBinder *b)
{ return tagbindbits_(b) & bitoftype_(s_enum) ? s_enum :
tagbindbits_(b) & bitoftype_(s_struct) ? s_struct :
tagbindbits_(b) & bitoftype_(s_class) ? s_class :
tagbindbits_(b) & bitoftype_(s_union) ? s_union : s_nothing;
}
/* Expr parse tree constructors */
Expr *mk_expr1(AEop op, TypeExpr *t, Expr *a1)
{
return (Expr *) syn_list4(op, t, (FileLine *)0, a1);
}
Expr *mk_expr2(AEop op, TypeExpr *t, Expr *a1, Expr *a2)
{
return (Expr *) syn_list5(op, t, (FileLine *)0, a1, a2);
}
Expr *mk_exprlet(AEop op, TypeExpr *t, SynBindList *a1, Expr *a2)
{
return (Expr *) syn_list5(op, t, (FileLine *)0, a1, a2);
}
Expr *mk_expr3(AEop op, TypeExpr *t, Expr *a1, Expr *a2, Expr *a3)
{
return (Expr *) syn_list6(op, t, (FileLine *)0, a1, a2, a3);
}
#ifdef EXTENSION_VALOF
Expr *mk_expr_valof(AEop op, TypeExpr *t, Cmd *c)
{
return (Expr *) syn_list4(op, t, (FileLine *)0, c);
}
#endif
Expr *mk_exprwdot(AEop op, TypeExpr *t, Expr *a1, IPtr a2)
{
return (Expr *) syn_list5(op, t, (FileLine *)0, a1, a2);
}
Expr *mk_exprbdot(AEop op, TypeExpr *t, Expr *a1, int32 a2, int32 a3,
int32 a4)
{
return (Expr *)syn_list7(op, t, (FileLine *)0, a1, a2, a3, a4);
}
#ifdef TARGET_HAS_INLINE_ASSEMBLER
AsmInstr *mk_asminstr(void)
{
AsmInstr *a = (AsmInstr *)SynAlloc(sizeof(AsmInstr));
a->opcode = 0, a->cdr = 0; a->opnd1 = a->opnd2 = a->opnd3 = a->opnd4 = 0;
return a;
}
#endif
DeclRhsList *mkDeclRhsList(Symstr *sv, TypeExpr *t, SET_BITMAP s)
{ /* slowly becoming local to syn.c */
DeclRhsList *p = (DeclRhsList *) SynAlloc(sizeof(DeclRhsList));
p->declcdr = NULL; p->declname = sv; p->declrealname = NULL;
p->decltype = t;
declinit_(p) = NULL; /* p->decbits = 0; */
p->declstg = s; p->declbind = NULL;
p->fileline.f = NULL; p->fileline.l = 0;
p->tentative = NULL;
#ifdef PASCAL /*ECN*/
p->synflags = 0;
#endif
return(p);
}
/* Hmm. The last arg to this varies wildly in type */
TypeExpr *mk_typeexpr1(AEop op, TypeExpr *t, Expr *a1)
{
return (TypeExpr *)syn_list4(op, t, a1, 0);
}
TopDecl *mkTopDeclFnDef(AEop a, Binder *b, SynBindList *c, Cmd *d, bool e)
{
return (TopDecl *)syn_list5(a, b, c, d, e);
}
TypeExpr *mkTypeExprfn(AEop a, TypeExpr *b, SET_BITMAP s, FormTypeList *c,
const TypeExprFnAux *d)
{
/*
* The fnaux field in a TypeExpr contains a RealRegSet, the size of which
* depends on the number of registers that our target has. For this reason,
* we allocate the TypeExpr in Binder store rather than syntax store, so that
* regalloc can locate and use the RealRegSet value.
*/
TypeExpr *t = (TypeExpr *)BindAlloc(sizeof(TypeExpr));
h0_(t) = a;
typearg_(t) = b;
typeptrmap_(t) = s;
typefnargs_(t) = c;
typedbginfo_(t) = 0;
typefnaux_(t) = *d; /* At least 2 words, more if > 32 real registers exist */
#ifdef PASCAL /*ECN*/
t->pun.type = syn_list3(t_fnap, 0, 0);
#endif
return t;
}
TypeExpr *g_mkTypeExprfn(AEop a, TypeExpr *b, SET_BITMAP s, FormTypeList *c,
const TypeExprFnAux *d)
{
TypeExpr *t = (TypeExpr *)GlobAlloc(SU_Type, sizeof(TypeExpr));
h0_(t) = a;
typearg_(t) = b;
typeptrmap_(t) = s;
typefnargs_(t) = c;
typedbginfo_(t) = 0;
typefnaux_(t) = *d;
#ifdef PASCAL /*ECN*/
t->pun.type = global_list3(SU_Type, t_fnap, 0, 0);
#endif
return t;
}
FormTypeList *mkFormTypeList(FormTypeList *ftcdr, Symstr *ftname,
TypeExpr *fttype, Expr *ftdefault)
{ return (FormTypeList *)syn_list4(ftcdr, ftname, fttype, ftdefault);
}
FormTypeList *g_mkFormTypeList(FormTypeList *ftcdr, Symstr *ftname,
TypeExpr *fttype, Expr *ftdefault)
{ return (FormTypeList *)global_list4(SU_Other, ftcdr, ftname, fttype,
ftdefault);
}
/* comments re globalisation:
Binders are globalized or not on creation, the only need for
globalize routines is for the type expressions (see globalize_typeexpr()
below) which hang from them.
*/
Expr *globalize_int(int32 n)
{ /* could insert special code here to use globalize_bool()... */
/* possibly via lit_true or lit_false. */
return (Expr*)global_list5(SU_Const, s_integer,te_int,(FileLine *)0,n,0);
}
static FormTypeList *globalize_formals_1(FormTypeList *d, bool defaultvals)
{ FormTypeList *d1;
if (d == NULL) return NULL;
d1 = g_mkFormTypeList(0, d->ftname,
globalize_typeexpr(d->fttype),
defaultvals && d->ftdefault ?
globalize_expr(d->ftdefault) : 0);
d1->ftcdr = globalize_formals_1(d->ftcdr, defaultvals);
return d1;
}
#define TYPEMEMOHASHSIZE 128
#define typehash_(t) (h0_(t) + (IPtr)typearg_(t) + ((IPtr)typespecbind_(t))>>2)
static struct te_memo { struct te_memo *cdr; TypeExpr te; }
*glob_typeexpr_memo[TYPEMEMOHASHSIZE];
#define EQtype_(t1,t2) ((t1)->h0==(t2)->h0 && typearg_(t1)==typearg_(t2) \
&& typespecbind_(t1)==typespecbind_(t2))
static TypeExpr *globalize_memo(TypeExpr *t)
{ struct te_memo *p;
int hash = ((int)typehash_(t)) & (TYPEMEMOHASHSIZE - 1);
for (p = glob_typeexpr_memo[hash]; p != 0; p = p->cdr)
if (EQtype_(t, &p->te)) break;
if (p == 0)
p = glob_typeexpr_memo[hash] =
(struct te_memo*) global_list5(SU_Type, glob_typeexpr_memo[hash],
h0_(t), typespecmap_(t), typespecbind_(t), 0);
return &p->te;
}
#if 0
static void globaltypehashstats(void)
{ struct te_memo **p = glob_typeexpr_memo;
struct te_memo **limit =
p + (sizeof glob_typeexpr_memo / sizeof *glob_typeexpr_memo);
int used = 0, maxlen = 0;
for (; p < limit; ++p)
{ int len = 0;
struct te_memo *p2 = *p;
for (; p2 != 0; p2 = p2->cdr) ++len;
if (maxlen < len) maxlen = len;
if (0 < len) ++used;
cc_msg("bucket %d, chain length = %d\n", p - glob_typeexpr_memo, len);
}
cc_msg("glob_typeexpr_memo: %d of %d buckets used; max chain length = %d\n",
used, TYPEMEMOHASHSIZE, maxlen);
}
#endif
/*
* a temporary home before its demise...
*/
int32 evaluate(Expr *a)
{
/* evaluate the compile-time expression a to yield an integer result */
for (;;) switch (h0_(a))
{
case s_evalerror:
if (has_template_arg_scope() && arg3_(a) == NULL)
/* silent mode */ ;
else
cc_rerr((msg_t)arg3_(a), h0_(arg2_(a)));
a = arg1_(a);
break;
case s_integer:
return(intval_(a));
case s_int64con:
{ int32 n;
if ((int64map_(a) & bitoftype_(s_unsigned))
|| I64_SToI(&n, &int64val_(a).i) != i64_ok) {
if (I64_UToI((uint32 *)&n, &int64val_(a).u) != i64_ok)
cc_rerr(sem_rerr_implicit_cast_overflow(te_uint, 0, 0));
}
return n;
}
default:
/* Beware: this is not a catch-all. Some callers don't have the right
scope for it. Requires fix at the call site.
*/
if (!is_template_arg_binder(a))
moan_nonconst(a, bind_msg_const_nonconst, bind_msg_const_nonconst1,
bind_msg_const_nonconst2);
return 1;
}
}
/* globalize_typeexpr caches only basic types (including structs/typedefs) */
/* and pointers/refs to things already cached. Tough ched arrays/fns. */
/* N.B. we should never cache empty arrays as size may get updated. */
static TypeExpr *globalize_typeexpr_1(TypeExpr *t, bool defaultvals)
{ static bool glob_incache;
TypeExpr *ans;
#ifdef PASCAL /*ECN*/
assert(0);
#else
switch (h0_(t))
{
case t_content:
case t_ref:
{ TypeExpr *gt = globalize_typeexpr(typearg_(t));
if (glob_incache)
{ TypeExpr temp;
h0_(&temp) = h0_(t), typearg_(&temp) = gt,
typeptrmap_(&temp) = typeptrmap_(t);
/* dbglanginfo field? Doesn't matter for C! */
return globalize_memo(&temp);
}
return (TypeExpr *)global_list4(SU_Type,
h0_(t), gt, typeptrmap_(t), 0);
/* note that glob_incache is set correctly */
}
case t_subscript:
{ Expr *subsz = typesubsize_(t);
ans = (TypeExpr*) global_list4(SU_Type, t_subscript,
globalize_typeexpr(typearg_(t)),
subsz == 0 ? (Expr *)0 : (h0_(subsz) == s_binder ||
(h0_(subsz) == s_cast) && h0_(arg1_(subsz)) == s_binder) ?
globalize_expr(subsz) :
globalize_int(evaluate(subsz)),
0);
glob_incache = 0;
return ans;
}
case t_fnap:
/* the DeclRhsList of formals could well become a ClassMember */
ans = g_mkTypeExprfn(t_fnap,
globalize_typeexpr(typearg_(t)),
typeptrmap_(t),
globalize_formals_1(typefnargs_(t), defaultvals),
&typefnaux_(t));
glob_incache = 0;
return ans;
case t_ovld: /* all t_ovld types a global */
glob_incache = 0;
return t;
case t_coloncolon:
ans = (TypeExpr *)global_list4(SU_Type, t_coloncolon,
globalize_typeexpr(typearg_(t)),
typespectagbind_(t),
0);
glob_incache = 0;
return ans;
case s_typespec:
/* N.B. any binder in typespecbind_(t) is assumed globalised */
if (typespecmap_(t) & (bitoftype_(s_typedefname)|ENUMORCLASSBITS)
&& (!(typespecmap_(t) & ENUMORCLASSBITS ?
attributes_(typespectagbind_(t)) :
attributes_(typespecbind_(t))) & A_GLOBALSTORE))
syserr("globalization failure: $b", typespecbind_(t));
glob_incache = 1;
return typespecmap_(t) == typespecmap_(te_void) ? te_void :
typespecmap_(t) == typespecmap_(te_int) ? te_int :
typespecmap_(t) == typespecmap_(te_lint) ? te_lint :
typespecmap_(t) == typespecmap_(te_uint) ? te_uint :
typespecmap_(t) == typespecmap_(te_ulint) ? te_ulint :
typespecmap_(t) == typespecmap_(te_float) ? te_float :
typespecmap_(t) == typespecmap_(te_double) ? te_double :
typespecmap_(t) == typespecmap_(te_ldble) ? te_ldble :
globalize_memo(t);
case t_unknown:
return t;
default:
syserr(syserr_globalize1, (VoidStar)t, (long)h0_(t));
return t;
}
#endif
}
FormTypeList *globalize_formals(FormTypeList *d)
{
return globalize_formals_1(d, YES);
}
TypeExpr *globalize_typeexpr(TypeExpr *t)
{
return globalize_typeexpr_1(t, YES);
}
static FormTypeList *clone_formals(FormTypeList *ft);
static FormTypeList *clone_formals(FormTypeList *ft)
{ if (!ft) return NULL;
return (FormTypeList *)syn_list4(clone_formals(ft->ftcdr), ft->ftname,
clone_typeexpr(ft->fttype), ft->ftdefault);
}
ScopeSaver globalize_env(ScopeSaver env)
{ ScopeSaver temp = NULL;
for (; env; env = bindcdr_(env))
{ temp = global_mk_binder(temp, bindsym_(env), bindstg_(env),
globalize_typeexpr(bindtype_(env)));
bindconst_(temp) = bindconst_(env);
}
return dreverse_binder(temp);
}
TypeExpr *clone_typeexpr(TypeExpr *t)
{
switch (h0_(t)) {
case t_content:
case t_ref:
return mk_typeexpr1(h0_(t),
clone_typeexpr(typearg_(t)), (Expr*)typeptrmap_(t));
case t_subscript:
return mk_typeexpr1(t_subscript,
clone_typeexpr(typearg_(t)), (Expr*)typesubsize_(t));
case t_ovld:
if (length((List *)typeovldlist_(t)) == 1)
t = bindtype_(typeovldlist_(t)->bindlistcar);
else
{ syserr("clone_typeexpr: lack of target type, overload found");
return t;
}
case t_fnap:
return mkTypeExprfn(t_fnap,
clone_typeexpr(typearg_(t)), typeptrmap_(t),
clone_formals(typefnargs_(t)), &typefnaux_(t));
case t_coloncolon:
return mk_typeexpr1(t_coloncolon,
clone_typeexpr(typearg_(t)), (Expr*)typespectagbind_(t));
case s_typespec:
{ Binder *b = typespecbind_(t);
TypeExpr *t1 = princtype(t);
/* break structure sharing, name is the link */
if (isprimtype_(t, s_typedefname) && (h0_(t1) == t_unknown
|| (isclasstype_(t1) && (tagbindbits_(typespectagbind_(t1)) & TB_TEMPLATE))))
{ TagBinder *parent;
if (b == NULL) syserr("Odd typevar");
parent = bindparent_(b);
b = (attributes_(b) & A_GLOBALSTORE) ?
global_mk_binder(0, bindsym_(b), bindstg_(b), bindtype_(b)) :
mk_binder(bindsym_(b), bindstg_(b), bindtype_(b));
bindparent_(b) = parent;
if (isclasstype_(t1))
{ TagBinder *tb = typespectagbind_(t1);
Symstr *sv = specialized_name_of(tb);
BindList *bl = taginstances_(tb);
TagBinder *clone = NULL;
for (; bl != NULL; bl = bl->bindlistcdr)
if (tagbindsym_(bl->bindlistcar) == sv)
{ clone = (TagBinder *)bl->bindlistcar;
break;
}
if (clone == NULL)
{ Binder *b1;
ExprList *types = NULL;
AEop sort = tagbindsort(tb);
/* pretends this is a specialization */
clone = (attributes_(tb) & A_GLOBALSTORE) ?
global_mk_tagbinder(0, sv, sort) : mk_tagbinder(sv, sort);
/* Exactly the same as the primary, except for the those
used in type deduction.
Beware instance list shared and the clone is on it!
*/
*clone = *tb;
tagformals_(clone) =
globalize_env(copy_env(tagformals_(tb), env_size(tagformals_(tb))));
tagprimary_(clone) = tb;
for (b1 = tagformals_(tb); b1 != NULL; b1 = bindcdr_(b))
types = syn_cons2(types,
mk_typeexpr1(s_typespec, bindtype_(b1), 0));
types = dreverse((List *)types);
tagactuals_(clone) =
globalize_template_arg_binders(tagformals_(tb), types);
#if 0
tagbindtype_(clone) = mk_typeexpr1(s_typespec,
(TypeExpr*)bitoftype_(sort), (Expr*)clone);
#endif
add_instance((Binder *)clone, &taginstances_(tb), YES);
}
bindtype_(b) = tagbindtype_(clone);
}
}
return mk_typeexpr1(s_typespec, typearg_(t), (Expr*)b);
}
case t_unknown:
return t;
default:
syserr("un-clonable type");
return t;
}
}
TypeExpr *globalize_typeexpr_no_default_arg_vals(TypeExpr *t)
{
return globalize_typeexpr_1(t, NO);
}
static FileLine *globalize_fileline(Expr *e)
{ if (hasfileline_(h0_(e)) && exprfileline_(e) != NULL)
{ FileLine *fl = (FileLine *)GlobAlloc(SU_Other, (int32)sizeof(FileLine));
*fl = *exprfileline_(e);
return fl;
}
return NULL;
}
static Expr *globalize_integer(Expr *e)
{ Binder *b = exb_(arg2_(e));
/* Don't bother with "globalize_expr(arg2_(e))" for intorig_() field */
/* unless the intorig_field is already a global binder... Relied on by */
/* C++'s end-of-class default argument binding code. FRIGORAMA! */
if (b != 0 && !(attributes_(b) & A_GLOBALSTORE)) b = 0;
return (Expr *)global_list5(SU_Other, s_integer,
globalize_typeexpr(type_(e)),
globalize_fileline(e),
arg1_(e),
/* preseve global binder => */ b);
}
StringSegList *globalize_strseg(StringSegList *s)
{ if (s == NULL) return NULL;
return (StringSegList *)global_list3(SU_Other,
globalize_strseg(s->strsegcdr),
memcpy(GlobAlloc(SU_Other, s->strseglen),
s->strsegbase, (size_t)s->strseglen),
s->strseglen);
}
static Expr *globalize_string(AEop op, String *s)
{
return (Expr *)global_cons2(SU_Other,
op,
globalize_strseg(s->strseg));
}
static ExprList *globalize_exprlist(ExprList *l)
{ if (l == NULL) return NULL;
return (ExprList *)global_cons2(SU_Other,
globalize_exprlist(l->cdr),
globalize_expr(exprcar_(l)));
}
static Binder *globalize_binder(Binder *b)
{ Binder *p;
Symstr *sv;
/* Non-temp binders are global iff they need to be global. Temp ones */
/* may need to be globalized (cf s_let in globalize_expr() below). */
if (attributes_(b) & A_GLOBALSTORE) return b;
sv = bindsym_(b);
if (!isgensym(sv))
{ syserr("globalize_binder");
return b;
}
else if (bind_global_(sv) != 0)
return bind_global_(sv);
sv = sym_insert_id(sv->symname);
p = global_mk_binder(0, sv, bindstg_(b), globalize_typeexpr(bindtype_(b)));
bind_global_(bindsym_(b)) = p;
attributes_(p) = (attributes_(b) & ~A_LOCALSTORE) | A_GLOBALSTORE;
bindaddr_(p) = bindaddr_(b);
bindconst_(p) = bindconst_(b) ? globalize_expr(bindconst_(b)) : 0;
return p;
}
static SynBindList *globalize_bindlist(SynBindList *l)
{ if (l == NULL) return NULL;
return (SynBindList *)global_cons2(SU_Other,
globalize_bindlist(l->bindlistcdr),
globalize_binder(l->bindlistcar));
}
Expr *globalize_expr(Expr *e)
{ AEop op;
/* This is now sometimes needed even in a C-only compiler (though */
/* the more complicated cases can't arise) now that constant values */
/* get propagated in C from the bindconst_ field of a const binder */
switch (op = e ? h0_(e) : s_error)
{
case s_typespec:
return global_list3(SU_Type, s_typespec,
globalize_typeexpr(type_(e)), arg1_(e));
case s_evalerror:
if (has_template_arg_scope()) return globalize_expr(arg1_(e));
/* else same as s_error, drop thru */
case s_error:
case s_invisible: /* shouldn't occur in optimise0() results. */
break;
case s_binder:
return (Expr *)globalize_binder(exb_(e));
case s_floatcon: /* uses global store @@@ DANGEROUS assumption */
case s_int64con: /* uses global store @@@ DANGEROUS assumption */
return e;
case s_integer:
return globalize_integer(e);
#ifdef EXTENSION_UNSIGNED_STRINGS
case s_ustring:
#endif
case s_wstring:
case s_string:
return globalize_string(h0_(e), (String *)e);
case s_fnapstruct:
case s_fnap:
return (Expr *) global_list5(SU_Other,
op,
globalize_typeexpr(type_(e)),
globalize_fileline(e),
globalize_expr(arg1_(e)),
globalize_exprlist(exprfnargs_(e)));
case s_qualified|s_let:
case s_let:
return (Expr *) global_list5(SU_Other,
op,
globalize_typeexpr(type_(e)),
globalize_fileline(e),
globalize_bindlist(exprletbind_(e)),
globalize_expr(arg2_(e)));
#ifdef RANGECHECK_SUPPORTED
case s_rangecheck:
#endif
case s_cond:
return (Expr *) global_list6(SU_Other,
op,
globalize_typeexpr(type_(e)),
globalize_fileline(e),
globalize_expr(arg1_(e)),
globalize_expr(arg2_(e)),
globalize_expr(arg3_(e)));
case s_dot:
{ bool is_bitfield = isbitfield_type(type_(e));
Expr *r = (Expr *)GlobAlloc(SU_Other,
is_bitfield ? 7L*sizeof(int32) : 5L*sizeof(int32));
h0_(r) = op;
type_(r) = globalize_typeexpr(type_(e));
exprfileline_(r) = globalize_fileline(e);
arg1_(r) = globalize_expr(arg1_(e));
exprdotoff_(r) = exprdotoff_(e);
if (is_bitfield)
{ exprbsize_(r) = exprbsize_(e);
exprmsboff_(r) = exprmsboff_(e);
}
return r;
}
default:
if (ismonad_(op) || op == s_return || op == s_cast)
{
return (Expr *) global_list4(SU_Other,
op,
globalize_typeexpr(type_(e)),
globalize_fileline(e),
globalize_expr(arg1_(e)));
}
else if (isdiad_(op) || op == s_init
#ifdef RANGECHECK_SUPPORTED
|| op == s_checknot
#endif
)
{
return (Expr *) global_list5(SU_Other,
op,
globalize_typeexpr(type_(e)),
globalize_fileline(e),
globalize_expr(arg1_(e)),
globalize_expr(arg2_(e)));
}
}
syserr("globalize_expr(%p:%.lu)", e, op);
return NULL;
}
void aetree_init(void)
{ struct te_memo **p = glob_typeexpr_memo;
struct te_memo **limit =
p + (sizeof glob_typeexpr_memo / sizeof *glob_typeexpr_memo);
for (; p < limit; ++p)
*p = 0;
}
/* command nodes... */
Cmd *mk_cmd_0(AEop op, FileLine x) /* op = s_break,s_endcase,s_continue */
{
Cmd *p = (Cmd *) SynAlloc(offsetof(Cmd,cmd1));
p->fileline = x;
h0_(p) = op;
return p;
}
Cmd *mk_cmd_e(AEop op, FileLine x, Expr *e) /* op = s_return,s_semicolon */
{
Cmd *p = (Cmd *) SynAlloc(offsetof(Cmd,cmd2));
p->fileline = x;
h0_(p) = op, cmd1e_(p) = e;
return p;
}
Cmd *mk_cmd_default(FileLine x, Cmd *c)
{
Cmd *p = (Cmd *) SynAlloc(offsetof(Cmd,cmd2));
p->fileline = x;
h0_(p) = s_default, cmd1c_(p) = c;
return p;
}
Cmd *mk_cmd_lab(AEop op, FileLine x, LabBind *b, Cmd *c)
{ /* op = s_colon,s_goto */
Cmd *p = (Cmd *) SynAlloc(offsetof(Cmd,cmd3));
p->fileline = x;
h0_(p) = op, cmd1c_(p) = (Cmd *)b, cmd2c_(p) = c;
return p;
}
Cmd *mk_cmd_block(FileLine x, SynBindList *bl, CmdList *cl)
{
Cmd *p = (Cmd *) SynAlloc(offsetof(Cmd,cmd3));
p->fileline = x;
if ( (LanguageIsCPlusPlus) && bl && (bl -> bindlistcdr != NULL))
/* For ease of generating destructor information after each
declaration of an auto variable for which there is a destructor,
allow only one declaration per block SW09Sep97*/
{
SynBindList* blc = bl -> bindlistcdr;
bl -> bindlistcdr = NULL;
cmd2c_(p) = (Cmd *) mkCmdList (0, mk_cmd_block(x, blc, cl));
}
else
cmd2c_(p) = (Cmd *)cl;
h0_(p) = s_block, cmd1c_(p) = (Cmd *)bl;
return p;
}
Cmd *mk_cmd_do(FileLine x, Cmd *c, Expr *e)
{
Cmd *p = (Cmd *) SynAlloc(offsetof(Cmd,cmd3));
p->fileline = x;
h0_(p) = s_do, cmd1c_(p) = c, cmd2e_(p) = e;
return p;
}
Cmd *mk_cmd_if(FileLine x, Expr *e, Cmd *c1, Cmd *c2)
{
Cmd *p = (Cmd *) SynAlloc(offsetof(Cmd,cmd4));
p->fileline = x;
h0_(p) = s_if, cmd1e_(p) = e, cmd2c_(p) = c1, cmd3c_(p) = c2;
return p;
}
Cmd *mk_cmd_switch(FileLine x, Expr *e, Cmd *c1, Cmd *c2, Cmd *c3)
{
Cmd *p = (Cmd *) SynAlloc(sizeof(Cmd));
p->fileline = x;
h0_(p) = s_switch, cmd1e_(p) = e, cmd2c_(p) = c1,
cmd3c_(p) = c2, cmd4c_(p) = c3;
return p;
}
Cmd *mk_cmd_for(FileLine x, Expr *e1, Expr *e2, Expr *e3, Cmd *c)
{
Cmd *p = (Cmd *) SynAlloc(sizeof(Cmd));
p->fileline = x;
h0_(p) = s_for, cmd1e_(p) = e1, cmd2e_(p) = e2,
cmd3e_(p) = e3, cmd4c_(p) = c;
return p;
}
/* for 'case' labels of a switch */
Cmd *mk_cmd_case(FileLine x, Expr *e, Cmd *c1, Cmd *c2)
{
Cmd *p = (Cmd *) SynAlloc(sizeof(Cmd));
p->fileline = x;
h0_(p) = s_case, cmd1e_(p) = e, cmd2c_(p) = c1,
cmd3c_(p) = c2, cmd4c_(p) = 0; /* cmd4c_ = LabelNumber */
return p;
}
Cmd *mk_cmd_try(FileLine x, Cmd *body, Handler *handler_list, Cmd *exit)
{
Cmd *p = (Cmd *) SynAlloc(offsetof(Cmd,cmd4));
p->fileline = x;
h0_(p) = s_try, cmd1c_(p) = body,
cmd2c_(p) = (Cmd *) handler_list, cmd3c_(p) = exit;
return p;
}
static bool is_fpval(Expr const *e, FPConst const *fc)
{
while (h0_(e) == s_invisible) e = arg2_(e);
if (h0_(e) == s_floatcon)
{ FloatCon const *f = (FloatCon const *)e;
if (is_float_(f->floatlen))
return (f->floatbin.fb.val == fc->s->floatbin.fb.val);
else if (is_anydouble_(f->floatlen))
return (f->floatbin.db.msd == fc->d->floatbin.db.msd &&
f->floatbin.db.lsd == fc->d->floatbin.db.lsd);
}
return NO;
}
bool is_fpzero(Expr const *e)
{
return is_fpval(e, &fc_zero);
}
bool is_fpone(Expr const *e)
{
return is_fpval(e, &fc_one);
}
bool is_fpminusone(Expr const *e)
{
return is_fpval(e, &fc_minusone);
}
int32 result2;
bool integer_constant(Expr const *x)
{
/* Test if x is an integer constant, and if it is leave its value in result2 */
if (h0_(x)==s_integer)
{ result2 = intval_(x);
return YES;
}
return NO;
}
bool is_intzero(Expr const *x)
{
return (integer_constant(x) && result2==0);
}
bool is_intone(Expr const *x)
{
return (integer_constant(x) && result2==1);
}
bool is_intminusone(Expr const *x)
{
return (integer_constant(x) && result2==-1);
}
bool resultinflags_fn(Expr *e)
{
if (h0_(e) == s_fnap)
{
TypeExpr *t = princtype(typeofexpr(arg1_(e)));
while (h0_(t) == t_content || h0_(t) == t_coloncolon || h0_(t) == t_ref)
t = princtype(typearg_(t));
if (h0_(t) != t_fnap) syserr("function type expected");
return typefnauxflags_(t) & f_resultinflags;
}
return NO;
}
#ifdef ENABLE_AETREE
#define ANY_ENABLED ENABLE_AETREE
#else
#ifdef ENABLE_BIND
#define ANY_ENABLED ENABLE_BIND
#else
#ifdef ENABLE_CG
#define ANY_ENABLED ENABLE_CG
#else
#ifdef ENABLE_REGS
#define ANY_ENABLED ENABLE_REGS
#else
#ifdef ENABLE_TYPE
#define ANY_ENABLED ENABLE_TYPE
#endif
#endif
#endif
#endif
#endif
int32 aetree_debugcount;
#define DebugShowBinderTypes (aetree_debugcount > 1)
#define DebugShowTypedefTypes (aetree_debugcount > 1)
#define DebugShowRealBinders (aetree_debugcount > 1)
#define DebugShowPointers (aetree_debugcount > 2)
static void pr_typeexpr_e(TypeExpr *x, Symstr *s, bool nolinebreak);
#define PR_CMD 1
#define PR_HAND 2
#define PR_BIND 3
#define PR_FORMTYPE 4
#define PR_VTAB 5
#define symbol_name_(s) ((sym_name_table[s]))
static int32 position = 0;
void eprintf(char const *s, ...)
{ char b[512];
va_list ap;
va_start(ap,s);
vsprintf(b, s, ap);
{ size_t len = strlen(b);
if (0 < len && b[len - 1] == '\n')
position = 0;
else
position += len;
}
cc_msg("%s", b);
va_end(ap);
}
void pr_stringsegs(StringSegList *z)
/* only used here and in jopprint.c */
{ eprintf("\"");
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)) eprintf("%c", ch);
else if (ch=='\n') eprintf("\\n");
else eprintf("\\%lo", (long)ch);
}
}
eprintf("\"");
}
#ifdef ANY_ENABLED
static void enewline(void)
{ cc_msg("\n");
position = 0;
}
static void elinebreak(void)
{
if (position>64)
enewline();
}
static void elinebreakorspace(void)
{
if (position>64)
enewline();
else
{ cc_msg(" ");
++position;
}
}
static void pr_id(Symstr *sv)
{
if (sv == 0) eprintf("<NULL-ID>");
else if (h0_(sv) != s_identifier) eprintf("<odd id %p/%lx>", sv, (long)h0_(sv));
else eprintf("[id:%s]",symname_(sv));
elinebreak();
}
static void pr_memb(ClassMember *m)
{
Symstr *sv = memsv_(m);
eprintf("[mem:%s]", sv ? symname_(sv) : "*NULL*");
}
static void pr_label(LabBind *x)
{ pr_id(x->labsym);
}
static void pr_bind0(Binder *b)
{ Symstr *sv = bindsym_(b);
if (sv != 0)
eprintf("%s", symname_(sv));
else
{ eprintf("nullbinder<");
pr_typeexpr(bindtype_(b), 0);
eprintf(">");
}
}
static void pr_stg(SET_BITMAP *m)
{ AEop op = s_auto;
for (; bitofstg_(op) & STGBITS; ++op)
if (*m & bitofstg_(op))
{ eprintf("%s ", symbol_name_(op));
*m &= ~bitofstg_(op);
}
}
static void pr_bind1(Binder *b)
{ Symstr *sv = bindsym_(b);
SET_BITMAP orig_s = bindstg_(b);
SET_BITMAP s = orig_s;
eprintf(DebugShowPointers ? "[Bind%p:" : "[Bind:", (VoidStar)b);
if (sv) eprintf(" %s ", symname_(sv)); else eprintf(" <no name>");
pr_stg(&s);
if (s != 0) eprintf("s=%lx", (long)s);
if (DebugShowBinderTypes)
{ eprintf(" t=");
pr_typeexpr_e(bindtype_(b), 0, YES);
elinebreakorspace();
}
if (orig_s & (b_impl|b_pseudonym))
{ if (DebugShowRealBinders)
eprintf("real="), pr_bind1(realbinder_(b));
}
else if ((orig_s & bitofstg_(s_auto)) && (bindaddr_(b) & BINDADDR_MASK) == BINDADDR_ARG)
eprintf(" formal(%ld)", (long)(bindaddr_(b) & ~BINDADDR_MASK));
else if ((orig_s & bitofstg_(s_auto)) && (bindaddr_(b) & BINDADDR_MASK) == BINDADDR_LOC)
eprintf(" local(%ld)", (long)(bindaddr_(b) & ~BINDADDR_MASK));
else if (bindaddr_(b) != 0 && bindaddr_(b) != BINDADDR_UNSET)
eprintf(" addr=%ld", (long)bindaddr_(b));
eprintf("]");
elinebreak();
}
static void pr_tagbindname(TagBinder *b)
{ if (DebugShowPointers)
eprintf("[TagBind%p: %s %s]",
(VoidStar)b, symbol_name_(tagbindsort(b)), symname_(bindsym_(b)));
else
eprintf("%s", symname_(bindsym_(b)));
/* do not print member list in case circular type! */
elinebreak();
}
/* pr_tagbind is not actually used anywhere in the compiler, but is */
/* intended to be called from a debugger */
static void pr_tagbind(TagBinder *tb)
{ eprintf("%s ", symbol_name_(tagbindsort(tb)));
pr_tagbindname(tb);
eprintf(" {\n");
if (isclasstagbinder_(tb))
{ ClassMember *m = tagbindmems_(tb);
for (; m != NULL; m = memcdr_(m))
{ eprintf(" %s: ", symname_(memsv_(m)));
pr_typeexpr_e(memtype_(m), 0, YES);
}
}
else if (isenumtagbinder_(tb))
{ BindList *bl = tagbindenums_(tb);
for (; bl != NULL; bl = bl->bindlistcdr)
eprintf(" %s = %d,\n",
symname_(bindsym_(bl->bindlistcar)),
bindenumval_(bl->bindlistcar));
} else
eprintf("<unknown tag bind kind>");
eprintf("};\n");
enewline();
}
static void pr_optexpr(Expr *x, char *s)
{
if (x!=0) pr_expr(x);
eprintf("%s", s);
elinebreak();
}
static void pr_condition(Expr *x)
{
eprintf("(");
pr_expr(x);
eprintf(")");
elinebreak();
}
static void pr_handler(Handler *x);
static void pr_list(int32 frep, VoidStar x)
{
if (x != NULL)
for (;;)
{ switch (frep)
{
default: eprintf("?");
break;
case PR_CMD: pr_cmd(cmdcar_((CmdList *)x));
break;
case PR_FORMTYPE:
pr_typeexpr(((FormTypeList *)x)->fttype, ((FormTypeList *)x)->ftname);
break;
case PR_BIND: pr_bind1(((BindList *)x)->bindlistcar);
break;
case PR_HAND: pr_handler((Handler *)x);
break;
case PR_VTAB: { VfnList *v = (VfnList *)x;
pr_bind0(v->vfmem);
eprintf("[delta=%ld]", v->vfdelta);
}
break;
}
x = (VoidStar) cdr_((List *)x);
if (x == NULL)
break;
eprintf(" ");
elinebreak();
}
}
static void pr_cv(SET_BITMAP *m)
{ AEop op = s_const;
for (; op <= s_unaligned; ++op)
if (*m & bitoftype_(op))
{ eprintf("%s ", symbol_name_(op));
*m &= ~bitoftype_(op);
}
}
static void pr_typespec(TypeExpr *x)
{
SET_BITMAP orig_m = typespecmap_(x);
SET_BITMAP m = orig_m;
AEop op = s_unsigned;
if (DebugShowPointers)
eprintf("<Type%p: ", (VoidStar)x);
if (h0_(x)!=s_typespec)
eprintf("<bad typespec %ld>", (long)h0_(x));
else
{ pr_cv(&m);
if (int_islonglong_(m)) {
m ^= (bitoftype_(s_short)|bitoftype_(s_long)|bitoftype_(s_longlong));
if (feature & FEATURE_FUSSY)
/* in which case, the printname of s_longlong is __int64, */
/* rather than long long */
m ^= bitoftype_(s_int);
}
for (; s_bool <= op; --op)
if (m & bitoftype_(op))
{ m &= ~bitoftype_(op);
eprintf("%s%s", symbol_name_(op), m == 0 ? "" : " ");
}
if (m != 0) eprintf(" __typespecmap(%lx)", (long)m);
if (orig_m & ENUMORCLASSBITS)
{ elinebreakorspace();
pr_tagbindname(typespectagbind_(x));
} else if (orig_m & bitoftype_(s_typedefname))
{ elinebreakorspace();
pr_bind1(typespecbind_(x));
} else if (typespecbind_(x) != 0)
{ elinebreakorspace();
eprintf("Odd type binder %p", (VoidStar)typespecbind_(x));
}
}
if (DebugShowPointers)
eprintf(">");
}
static void pr_ptr(TypeExpr *x, Symstr *s)
{ AEop op = h0_(x);
SET_BITMAP m = typeptrmap_(x);
eprintf(op == t_content ? "*" :
op == t_ref ? "&" :
"Unexpected op %ld (%s)", (long)op, symbol_name_(op));
pr_cv(&m);
if (m != 0) eprintf("%lx ", (long)m);
pr_typeexpr_e(typearg_(x),s,YES);
}
/* this SHOULD print out the typeexpr backwards as a declarator with
string s (possibly 0) as the declaree innermost. Some fine day... */
static void pr_typeexpr_e(TypeExpr *x, Symstr *s, bool nolinebreak)
{
switch (h0_(x))
{
case s_typespec:pr_typespec(x);
if (s != NULL)
{ eprintf(" ");
pr_id(s);
}
break;
case t_coloncolon: eprintf("<"); pr_tagbindname(typespectagbind_(x));
eprintf("::"); pr_typeexpr_e(typearg_(x),s,YES);
eprintf(">");
break;
case t_content:
case t_ref: pr_ptr(x, s);
break;
case t_subscript:
pr_typeexpr(typearg_(x),s);
eprintf("[");
pr_optexpr(typesubsize_(x),"");
eprintf("]");
break;
case t_fnap: pr_typeexpr(typearg_(x),s);
eprintf(" (");
pr_list(PR_FORMTYPE, typefnargs_(x));
eprintf(" fnauxflags %x", typefnauxflags_(typearg_(princtype(x))));
eprintf(")");
break;
case t_ovld: eprintf("<ovld:");
if (s != NULL)
{ eprintf(" ");
pr_id(s);
}
pr_list(PR_BIND, typeovldlist_(x));
eprintf(">");
break;
case t_unknown:
{ SET_BITMAP m = typespecmap_(x);
pr_cv(&m);
eprintf("typevar");
if (m & (bitoftype_(s_struct)|bitoftype_(s_class)))
eprintf(" %s",
symbol_name_(m & bitoftype_(s_struct) ? s_struct : s_class));
}
break;
default: eprintf("[unrecognized typeexpr %p:%ld]",
(void *)x, (long)h0_(x));
if (s != NULL)
{ eprintf(" ");
pr_id(s);
}
break;
}
if (!nolinebreak) elinebreak();
}
void pr_typeexpr(TypeExpr *x, Symstr *s)
{ pr_typeexpr_e(x, s, NO);
}
void pr_int64(int64 const *x)
{ eprintf("<int64 0x%lx_%.8lx>", (long)x->hi, (long)x->lo);
}
void pr_expr(Expr *x)
{
AEop op;
if (x == 0) eprintf("<missing expr>");
else if (x == (Expr *)DUFF_ADDR) eprintf("<DUFF_ADDR>");
else switch (op = h0_(x))
{
case s_error: eprintf("previous_error");
return;
case s_identifier:
pr_id((Symstr *)x);
return;
case s_member:
pr_memb((ClassMember *)x);
return;
case s_binder:
#ifdef DETAILED
pr_bind1(exb_(x));
#else
pr_bind0(exb_(x));
#endif
return;
case s_integer: { TypeExpr *t = princtype(type_(x));
if (isprimtype_(t, s_bool))
{ if (intval_(x)==1)
{ eprintf("true");
return;
}
if (intval_(x)==0)
{ eprintf("false");
return;
}
}
}
eprintf("%ld", (long)intval_(x));
return;
case s_floatcon:eprintf("<float %s>", exf_(x)->floatstr);
return;
case s_int64con:pr_int64(&int64val_(x).i);
return;
case s_string: elinebreak();
eprintf(" ");
pr_stringsegs(exs_(x) -> strseg);
eprintf(" ");
elinebreak();
return;
case s_fnapstructvoid:
case s_fnapstruct:
case s_fnap: pr_expr(arg1_(x));
eprintf("(");
{ ExprList *y = exprfnargs_(x);
while (y != NULL)
{ pr_expr(exprcar_(y));
y = cdr_(y);
if (y != NULL) { eprintf(", "); elinebreak(); }
}
}
eprintf(")");
return;
case s_cond: eprintf("(");
pr_expr(arg1_(x));
eprintf(" ? ");
elinebreak();
pr_expr(arg2_(x));
eprintf(" : ");
elinebreak();
pr_expr(arg3_(x));
eprintf(")");
elinebreak();
return;
#ifdef RANGECHECK_SUPPORTED
case s_checknot: eprintf("(");
pr_expr(arg1_(x));
eprintf(" ne ");
elinebreak();
pr_expr(arg2_(x));
eprintf(")");
elinebreak();
return;
case s_rangecheck: eprintf("(");
pr_expr(arg1_(x));
eprintf(" in ");
elinebreak();
eprintf("[");
pr_expr(arg2_(x));
eprintf(" : ");
elinebreak();
pr_expr(arg3_(x));
eprintf("])");
elinebreak();
return;
#endif
case s_dot:
case s_qualdot: eprintf("(");
pr_expr(arg1_(x));
eprintf(op == s_dot ? " . " : " ::. ");
if (h0_(type_(x)) == t_ovld || h0_(type_(x)) == t_fnap)
pr_expr(arg2_(x));
else
eprintf("%ld", (long)exprdotoff_(x));
eprintf(")");
return;
case s_cast: eprintf("(CAST(");
pr_typeexpr(type_(x),0);
eprintf(") ");
elinebreak();
pr_expr(arg1_(x));
eprintf(")");
return;
case s_invisible: eprintf("INVISIBLE(");
pr_expr(arg1_(x));
eprintf(" ==> ");
elinebreak();
pr_expr(arg2_(x));
eprintf(")");
return;
case s_let: eprintf("(LET ");
elinebreak();
pr_list(PR_BIND, arg1_(x));
eprintf(" IN ");
elinebreak();
pr_expr(arg2_(x));
eprintf(")");
return;
#ifdef EXTENSION_VALOF
case s_valof: eprintf("VALOF ");
pr_cmd(expr1c_(x));
return;
#endif
case s_content4:op = s_content; /* and fall through */
default:
if (ismonad_(op) || op == s_return || op == s_throw)
{ eprintf("(%s ", symbol_name_(op));
elinebreak();
pr_expr(arg1_(x));
eprintf(")");
}
else if (isdiad_(op))
{ eprintf("(");
pr_expr(arg1_(x));
eprintf(" %s ", symbol_name_(op));
elinebreak();
pr_expr(arg2_(x));
eprintf(")");
}
else
{ eprintf("Unprintable op %ld (%s)\n", (long)op, symbol_name_(op));
position = 0;
}
return;
}
}
static void pr_handler(Handler *x)
{ eprintf("catch(");
pr_list(PR_BIND, x->handbl);
eprintf(")");
pr_cmd(x->handbody);
elinebreak();
}
void pr_cmd(Cmd *x)
{
AEop op;
for (;;)
{
if (x!=0) switch (op = h0_(x))
{
default: eprintf("<odd cmd %ld = %s>",(long)op, symbol_name_(op));
elinebreak();
return;
case s_break:
case s_endcase:
case s_continue:eprintf("%s", symbol_name_(op));
break;
case s_return: eprintf("return ");
pr_optexpr(cmd1e_(x),";");
elinebreak();
return;
#ifdef EXTENSION_VALOF
case s_resultis:
eprintf("resultis ");
pr_optexpr(cmd1e_(x),";");
elinebreak();
return;
#endif
case s_case: eprintf("case");
pr_condition(cmd1e_(x));
eprintf(":");
elinebreak();
x = cmd2c_(x);
continue;
case s_default: eprintf("default:");
elinebreak();
x = cmd1c_(x);
continue;
case s_do: eprintf("do ");
pr_cmd(cmd1c_(x));
eprintf("while");
elinebreak();
pr_condition(cmd2e_(x));
break;
case s_for: eprintf("for(");
pr_optexpr(cmd1e_(x),";");
elinebreak();
pr_optexpr(cmd2e_(x),";");
elinebreak();
pr_optexpr(cmd3e_(x),")");
elinebreak();
x = cmd4c_(x);
continue;
case s_goto: eprintf("goto");
pr_label(cmd1lab_(x));
break;
case s_if: eprintf("if");
pr_condition(cmd1e_(x));
elinebreak();
pr_cmd(cmd2c_(x));
elinebreak();
if ((x = cmd3c_(x)) != 0) continue;
else return;
case s_switch: eprintf("switch ");
pr_condition(cmd1e_(x));
elinebreak();
x = cmd2c_(x);
continue;
case s_colon: pr_label(cmd1lab_(x));
eprintf(":");
elinebreak();
x = cmd2c_(x);
continue;
case s_thunkentry:
eprintf("thunktable{");
pr_list(PR_VTAB, cmd1c_(x));
eprintf("}");
elinebreak();
break;
case s_semicolon:
pr_expr(cmd1e_(x));
break;
case s_block: eprintf("{");
pr_list(PR_BIND, cmdblk_bl_(x));
eprintf(" ");
elinebreak();
pr_list(PR_CMD, cmdblk_cl_(x));
eprintf("}");
break;
case s_catch: eprintf("(Error: catch block, should be try block: ");
continue;
case s_try: eprintf("try");
pr_cmd(cmd1c_(x));
elinebreak();
pr_list(PR_HAND, cmdhand_(x));
break;
}
eprintf(";");
elinebreak();
return;
}
}
void pr_topdecl(TopDecl *x)
{
position = 0;
if (x==NULL)
{ eprintf("<missing topdecl>\n");
position = 0;
return;
}
switch (h0_(x))
{
case s_fndef: eprintf("FNDEF ");
pr_bind1(x->v_f.fn.name);
eprintf("\n");
pr_list(PR_BIND, x->v_f.fn.formals);
if (x->v_f.fn.ellipsis) eprintf(" (...)");
eprintf("\n");
pr_cmd(x->v_f.fn.body);
eprintf("\n");
case s_eof:
case s_decl: break;
default: eprintf("<unknown top level %ld>", (long)h0_(x));
position = 0;
break;
}
}
void pr_exproftype(char const *s, Expr *e)
{ position = 0;
eprintf(s); pr_expr(e);
eprintf(" of type "); pr_typeexpr_e(typeofexpr(e), 0, YES);
eprintf("\n");
}
void pr_typeexpr_nl(TypeExpr *x, Symstr *s)
{ pr_typeexpr(x, s);
eprintf("\n");
}
void pr_expr_nl(Expr *x)
{ pr_expr(x);
eprintf("\n");
}
#else
/* non-debugging version: */
void pr_topdecl(TopDecl *x) { IGNORE(x); }
void pr_expr(Expr *x) { IGNORE(x); }
void pr_cmd(Cmd *x) { IGNORE(x); }
void pr_typeexpr(TypeExpr *x, Symstr *s) { IGNORE(x); IGNORE(s); }
void pr_exproftype(char const *s, Expr *e) { IGNORE(s); IGNORE(e); }
void pr_typeexpr_nl(TypeExpr *x, Symstr *s) { IGNORE(x); IGNORE(s); }
void pr_expr_nl(Expr *x) { IGNORE(x); }
#endif
/* End of section aetree.c */
|
stardot/ncc | mip/xrefs.h | /*
* xrefs.h, version 2q
* Copyright (C) Codemist Ltd, 1988.
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
#ifndef _xrefs_LOADED
#define _xrefs_LOADED 1
typedef struct CodeXref CodeXref;
struct CodeXref {
CodeXref *codexrcdr;
int32 codexroff; /* plus flags in msb. */
Symstr *codexrsym;
/* The next comment is out of date-- see codebuf.c */
int32 codexrlitoff;/* armgen.c only: for searching for suitable literal - */
/* holds value or address offset of codeseg literal */
/*#ifdef TARGET_IS_HELIOS*/
int32 codexrpos; /* holds position in obj file to be patched */
# define codexrcode codexrlitoff
/* for Helios codexrcode holds the offset from the symbol. */
/* The symbol offset from the segment base needs to be added to this */
/* when a reloc32 relocation is output. */
/*#endif*/
};
typedef struct DataXref DataXref;
struct DataXref {
DataXref *dataxrcdr;
int32 dataxroff;
Symstr *dataxrsym;
};
/* Things which may appear in msb of codexrefs->codexroff. */
/* AM: these are a bit (lot) in flux and need naming tidying. */
/* Note that all dataseg relocs in dataxrefs->dataxroff are currently */
/* implicitly absreloc. */
#define X_absreloc 0x01000000L /* 32 bit abs (direct) reloc. */
/* Note that X_absreloc need not be word aligned even if data is (e.g. */
/* as opcode address field. X_absreloc only used by clipper so far. */
#define X_backaddrlit 0x02000000L /* same as absreloc, but used ONLY */
/* by vargen.c to share literals */
/* The following codes are only used on some machines. */
#define X_PCreloc 0x03000000L /* PC relative CALL/BR, e.g. ARM. */
/* X_DataAddr relocates immediate field(s) to load an ADCON into a */
/* register. E.g. use of 3 ADD/SUB's on 27bit ARM or OR.H;OR.U on */
/* m88k, i860, amd29000 etc. As an alternative some machines do this */
/* by loading an ADCON literal (X_absreloc) from pc-relative addr mode. */
/* We MAY need to distinguish X_DataAddr from X_FnAddr for 32000 etc. */
/* Helios needs similar things. */
#define X_DataAddr 0x04000000L /* Immediate field in load address */
#define X_DataVal 0x05000000L /* Ditto but for load/store. */
#define X_DataAddr1 0x06000000L /* Immediate field (high part-word) */
#define X_DataVal1 0x07000000L
#define X_TailCall 0x08000000L
#ifdef THUMB_CPLUSPLUS
# define X_PCreloc_32 0x17000000L
#endif
struct ExtRef
{ ExtRef *extcdr;
Symstr *extsym;
int32 extindex;
int extflags; /* xr_xxx things below */
int32 extoffset;
Symstr *codesym; /* for code defs when one area per fn */
RealRegSet usedregs;
};
/*
* 'flags' arg to obj_symref().
* No bits set => reference to untyped symbol.
*/
#define xr_code 0x01 /* defined as code, or imported as code */
#define xr_data 0x02 /* defined as data, or imported as data */
#define xr_bss 0x04
#define xr_constdata 0x08
#ifdef TARGET_HAS_ADCON_AREA
#define xr_adcon 0x10
#define xr_area (xr_code+xr_data+xr_bss+xr_constdata+xr_adcon)
#else
#define xr_area (xr_code+xr_data+xr_bss+xr_constdata)
#endif
#define xr_defloc 0x20 /* local (= static) definition. */
#define xr_defext 0x40 /* exported definition. */
/* The following bits are not used (as not needed) by all back-ends: */
#define xr_comref 0x80 /* OR-ed with xr_data in COMMON ref. */
#define xr_cblock 0x100 /* common block definition */
#define xr_weak 0x200
#define xr_dataincode 0x400 /* data object, but in the code segment */
/* rationally, we would use xr_code+ */
/* xr_data for this, but see below */
#define xr_objflg 0x800 /* private use by object code formatter */
#define xr_objflg1 0x1000
#define xr_objflg2 0x2000
#define xr_objflg3 0x4000
#define xr_objflg4 0x8000
#define xr_objflg5 0x10000
#define xr_objflg6 0x20000
#ifdef THUMB_CPLUSPLUS
#define xr_code_32 xr_objflg1
#endif
/* (Currently for Acorn AOF object format only), bits in the */
/* 0xfffc0000 area are used for common block index numbers. */
/* The following macros sugar the conversion between the flag field */
/* and index values. */
#define xr_flagtoidx_(n) ((n) >> 18)
#define xr_idxtoflag_(n) ((n) << 18)
/* Due to an idleness (actually silly optimisation when ~TARGET_CALL...*/
/* ...USES_DESCRIPTOR) xr_data may get spuriously set, so always test */
/* xr_code. E.g. { extern int f(); g(f); } @@@ AM to fix soon. */
/* Values for code_flag_(byteaddr). One byte of flag per code word. */
/* See mip/codebuf.h. One byte gives us enough room for the following */
/* and possible extensions on byte-oriented machines of 2 bytes opcode */
/* plus 2 bytes literal. Currently such things do not happen. */
/* They are used (a) for disassembly (when they are aided by aux */
/* entries in code_aux_() and (b) for object output (when cross-sex */
/* compiling). Currently exactly those tagged ($) below have a */
/* code_aux_() entry. */
/* AM thinks that maybe we need LIT_OPCODE to be an OR-ed in bit to */
/* deal with thinks like fp literals (88000) or 2*16bit addressing. */
#define LIT_OPCODE 0x00 /* all 4 bytes opcode. */
#define LIT_RELADDR 0x01 /* ($) all 4 bytes opcode, but flags */
/* that code_aux_ has an entry. E.g. */
/* BL foo. Redundant? */
#define LIT_NUMBER 0x02 /* 4 byte integer constant literal */
#define LIT_ADCON 0x03 /* 4 byte address constant literal */
#define LIT_FPNUM 0x04 /* ($) 4 byte floating constant literal */
#define LIT_FPNUM1 0x05 /* ($) first 4 bytes of double literal */
#define LIT_FPNUM2 0x06 /* ($) second 4 bytes of double literal */
#define LIT_STRING 0x10 /* 4 bytes of string literal */
/* old ACW implementations need gaps 0x10-13 for extra LIT_STRING info. */
/* The above are also used to flag data values (in struct DataInit), */
/* with the exception of LIT_OPCODE and LIT_RELADDR, but the following */
/* additional values are also used (but beware that LIT_FPNUM is used */
/* for all FP data values which are discriminated by FloatCon fields). */
#define LIT_HH 0x08 /* 2 halfwords datainit in host sex */
#define LIT_BBBB LIT_STRING /* 4 bytes datainit in host sex */
#define LIT_BBH 0x0a /* 2 bytes then halfword in host sex */
#define LIT_HBB 0x0b /* halfword then 2 bytes in host sex */
#define LIT_LABEL 0x0c /* static/extern defined here. */
#define LIT_FNCON 0x0d /* an alternative to LIT_ADCON, either */
/* vestigial (obj_symref subsumes) or */
/* up-and-coming. Currenltly only used */
/* if TARGET_CALL_USES_DESCRIPTOR. */
/* the following used only if sizeof_ptr == 2 or in the presence of */
/* initialisation of s_unaligned objects */
#define LIT_HX 0x0e /* one halfword only (host sex) */
#define LIT_BBX 0x0f /* two bytes only (host sex) */
/* the following used only in the presence of initialisation of */
/* s_unaligned objects */
#define LIT_BXXX 0x14
#define LIT_BBBX 0x15
#define LIT_HBX 0x16
/* ECN: Support for single halfwords sized objects */
#define LIT_H 0x17
#define LIT_BB 0x18
#ifdef THUMB_CPLUSPLUS
/* ECN: Support for embedding 32 bit ARM instructions in a Thumb code sequence */
#define LIT_OPCODE_32 0x19
#endif
#define LIT_INT64_1 0x1a
#define LIT_INT64_2 0x1b
extern CodeXref *codexrefs;
extern ExtRef *obj_symlist;
extern DataXref *dbgxrefs;
extern int32 obj_symref(Symstr *s, int flags, int32 loc);
extern int32 obj_symdef(Symstr *s, int flags, int32 loc);
#define LITF_INCODE 1L
#define LITF_FIRST 2L
#define LITF_LAST 4L
#define LITF_PEEK 8L
#define LITF_NEW 16L
#define LITF_DOUBLE 32L
#ifdef TARGET_HAS_BYTE_INSTRUCTIONS /* currently ACW only */
#define LITB_OPCODE 0
#define LITB_BASE 1
#define LITB_CASE 2
#define LITB_DISP 3
#define LITB_CHAR 4
#define LITB_PROVIGN 5
#define LITB_IGN 6
#define LITB_HEX 7
#define LITB_FLOATSTR 8
#define COUNTMAGIC 0xE6E6DEE6L
#define FUNMAGIC 0xFEE6E600L
#endif /* TARGET_HAS_BYTE_INSTRUCTIONS */
#endif
/* end of xrefs.h */
|
stardot/ncc | mip/sr.c | <reponame>stardot/ncc<filename>mip/sr.c<gh_stars>0
/*
* sr.c: Live range splitting
* Copyright 1993-1997 Advanced Risc Machines Limited. All rights reserved
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$ Codemist 2
* Checkin $Date$
* Revising $Author$
*/
#include <stdio.h>
#ifdef __STDC__
# include <string.h>
#else
# include <strings.h>
#endif
#include "globals.h"
#include "aeops.h"
#include "cgdefs.h"
#include "jopcode.h"
#include "regsets.h"
#include "sr.h"
#include "store.h"
#include "flowgraf.h"
#include "builtin.h"
#include "cg.h"
#include "regalloc.h"
#include "bind.h"
#include "mcdep.h"
#include "simplify.h"
#include "errors.h"
typedef struct VKUse VKUse;
typedef struct VKLoc VKLoc;
typedef struct VKList VKList;
typedef struct MOVCList MOVCList;
typedef struct AdconvList AdconvList;
struct MOVCList {
MOVCList *cdr;
BlockHead *block;
Icode *ic;
Binder *b1, *b2;
};
#define mkMOVCList(a,b,c,d,e) (MOVCList *)syn_list5(a,b,c,d,e)
struct VKUse {
VKUse *cdr;
Icode *use;
};
#define mkVKUse(a,b) (VKUse *)syn_list2(a,b)
struct VKLoc {
VKLoc *cdr;
unsigned32 offset;
int type;
VRegnum ruse;
VKUse *uses;
Binder *bind;
};
struct VKList {
VKList *cdr;
VRegnum bindxx;
bool splittable;
VKLoc *locs;
Binder *b;
};
struct AdconvList {
AdconvList *cdr;
IPtr /* VRegnum */ r;
Binder *b;
};
#define mkAdconvList(a,b,c) (AdconvList *)syn_list3(a,b,c)
#define AdconvList_DiscardOne(p) ((AdconvList *)discard3(p))
static VKList *vklist;
static VKUse *setsplist;
static MOVCList *movclist, **movctail;
static int const memsize[] = {
1,
2,
4,
sizeof_float,
sizeof_double,
8
};
#define BinderIsArg(b) \
(!(bindstg_(b) & b_bindaddrlist) && /* (implies BINDADDR_LOC) */ \
(bindaddr_(b) & BINDADDR_MASK) == BINDADDR_ARG)
static VRegnum ArgumentRegister(Binder *b) {
return (bindaddr_(b) & ~BINDADDR_MASK) / alignof_toplevel_auto -
currentfunction.fltargwords;
}
static BindList *bindlist_member(Binder *b, BindList *bl) {
for (; bl != NULL; bl = cdr_(bl))
if (bl->bindlistcar == b) return bl;
return NULL;
}
static void SpliceInBL(BindList *bl, VKLoc *locs, bool setbindaddr) {
if (bl != NULL) {
BindList *newbl, *q = cdr_(bl);
Binder *b = locs->bind;
bl->bindlistcar = b;
if (setbindaddr) bindbl_(b) = bl;
for (; (locs = cdr_(locs)) != NULL; bl = newbl) {
b = locs->bind;
newbl = mkBindList(NULL, b);
cdr_(bl) = newbl;
if (setbindaddr) bindbl_(b) = newbl;
}
cdr_(bl) = q;
}
}
static bool Overlap(int typea, int32 offseta, int typeb, int32 offsetb) {
return (offseta >= offsetb && offseta < offsetb + memsize[typeb]) ||
(offsetb >= offseta && offsetb < offseta + memsize[typea]);
}
static VKLoc *VKLoc_New(VKLoc *next, int32 offset, int type, VRegnum ruse) {
VKLoc *p = NewSyn(VKLoc);
cdr_(p) = next;
p->type = type;
p->offset = offset;
p->ruse = ruse;
p->uses = NULL;
p->bind = NULL;
return p;
}
static VKLoc *VKLoc_ReverseCopy(VKLoc *locs) {
VKLoc *res = NULL;
for (; locs != NULL; locs = cdr_(locs)) {
VKLoc *p = NewSyn(VKLoc);
*p = *locs;
cdr_(p) = res;
res = p;
}
return res;
}
#define bindvklist_(b) ((VKList *)bindxxp_(b))
static VKList *GetVKList(Binder *b) {
if ((bindstg_(b) & (bitofstg_(s_auto)|b_addrof|b_spilt)) != bitofstg_(s_auto))
return NULL;
if (BinderIsArg(b)) {
/* Only attempt to split argument structures passed entirely in registers */
VRegnum argreg = ArgumentRegister(b);
int32 size = bindmcrep_(b) & MCR_SIZE_MASK;
if (argreg + size / sizeof_int > NARGREGS) return NULL;
}
if (!(bindstg_(b) & u_loctype)) {
VKList *vk = NewSyn(VKList);
cdr_(vk) = vklist;
vklist = vk;
vk->bindxx = bindxx_(b);
vk->splittable = YES;
vk->b = b;
vk->locs = NULL;
bindxxp_(b) = vk;
bindstg_(b) |= u_loctype;
return vk;
} else
return bindvklist_(b);
}
static void MarkAdconvUnsplittable(VRegnum r, AdconvList *p) {
for (; p != NULL; p = cdr_(p))
if (r == p->r) {
if (debugging(DEBUG_SR))
cc_msg("Mark adconv unsplittable $b\n", p->b);
bindvklist_(p->b)->splittable = NO;
break;
}
}
static void MarkBinderUnsplittable(Binder *b) {
VKList *vk = GetVKList(b);
if (vk != NULL) {
if (debugging(DEBUG_SR))
cc_msg("Mark binder unsplittable $b\n", b);
vk->splittable = NO;
}
}
static AdconvList *adconv_unused;
static RegList *movc_unknown;
static void AddStructsInBL(BindList const *bl) {
for (; bl != NULL; bl = cdr_(bl)) {
Binder *b = bl->bindlistcar;
if ((bindmcrep_(b) & MCR_SORT_MASK) == MCR_SORT_STRUCT)
GetVKList(b);
}
}
static void OpRewritten(Icode const *c) {
if (debugging(DEBUG_SR)) {
cc_msg("rewritten: ");
print_jopcode(c);
}
}
static void SplitStructs_ScanBlock(BlockHead const *block) {
Icode *c, *limit;
AdconvList *adconvs = NULL;
if (debugging(DEBUG_SR))
cc_msg("L%li:\n", (long)lab_name_(blklab_(block)));
AddStructsInBL(blkstack_(block));
for (c = blkcode_(block), limit = c + blklength_(block); c < limit; ++c) {
VKList *vk;
if (debugging(DEBUG_SR))
print_jopcode(c);
switch (c->op & J_TABLE_BITS) {
case J_LDRK: case J_STRK:
{ AdconvList *p = adconvs;
for (; p != NULL; p = cdr_(p)) {
if (p->r == c->r2.r) {
c->op = J_addvk(c->op);
c->r2 = c->r3;
c->r3.b = p->b;
OpRewritten(c);
break;
}
}
if (p == NULL) break;
}
/* Fall through */
case J_LDRVK: case J_LDRLVK:
case J_LDRFVK: case J_LDRDVK:
case J_STRVK: case J_STRLVK:
case J_STRFVK: case J_STRDVK:
vk = GetVKList(c->r3.b);
if (vk != NULL && vk->splittable) {
uint32 offset = c->r2.i;
int type = (int)j_memsize(c->op);
VKLoc *locs, **locp = &vk->locs;
bool add = YES;
for (; (locs = *locp) != NULL; locp = &cdr_(locs))
if (type == locs->type && offset == locs->offset) {
add = NO;
break;
} else if (Overlap(type, offset, locs->type, locs->offset)) {
if (debugging(DEBUG_SR))
cc_msg("Mark binder unsplittable $b\n", c->r3.b);
vk->splittable = NO;
goto ExitSwitch;
} else if (offset < locs->offset)
break;
if (add) *locp = locs = VKLoc_New(locs, offset, type, c->r1.r);
locs->uses = mkVKUse(locs->uses, c);
}
ExitSwitch:
continue;
case J_LDRBVK: case J_LDRWVK:
case J_STRBVK: case J_STRWVK:
MarkBinderUnsplittable(c->r3.b);
continue;
case J_ADCONV:
vk = GetVKList(c->r3.b);
if (vk != NULL && vk->splittable)
adconvs = mkAdconvList(adconvs, c->r1.r, c->r3.b);
continue;
case J_MOVC:
{ AdconvList *p, *q = adconvs, **pp = &q;
Binder *b1 = NULL, *b2 = NULL;
for (; (p = *pp) != NULL; ) {
VRegnum r = p->r;
if (r == c->r1.r)
b1 = p->b;
else if (r == c->r2.r)
b2 = p->b;
else {
pp = &cdr_(p);
continue;
}
*pp = AdconvList_DiscardOne(p);
}
if (b1 == NULL) movc_unknown = (RegList *)syn_list2(movc_unknown, c->r1.r);
if (b2 == NULL) movc_unknown = (RegList *)syn_list2(movc_unknown, c->r2.r);
adconvs = q;
if (c->r3.i <= NARGREGS * sizeof_int) {
if (b1 != NULL || b2 != NULL) {
MOVCList *p = mkMOVCList(NULL, block, c, b1, b2);
*movctail = p;
movctail = &cdr_(p);
}
} else {
if (b1 != NULL) MarkBinderUnsplittable(b1);
if (b2 != NULL) MarkBinderUnsplittable(b2);
}
}
continue;
case J_SETSPENV:
AddStructsInBL(c->r3.bl);
case J_SETSPGOTO:
AddStructsInBL(c->r2.bl);
setsplist = mkVKUse(setsplist, c);
continue;
case J_MOVR:
if (!isany_realreg_(c->r1.r)) {
/* Move to a real register means function argument, so splitting mustn't
happen (and we drop into the default case to prevent it).
*/
AdconvList *p;
for (p = adconvs; p != NULL; p = cdr_(p))
if (p->r == c->r3.r) {
adconvs = mkAdconvList(adconvs, c->r1.r, p->b);
break;
}
for (p = adconv_unused; p != NULL; p = cdr_(p))
if (p->r == c->r3.r) {
adconvs = mkAdconvList(adconvs, c->r1.r, p->b);
break;
}
continue;
}
break;
case J_LDRDV: case J_STRDV:
case J_LDRLV: case J_STRLV:
case J_LDRFV: case J_STRFV:
case J_LDRV: case J_STRV:
MarkBinderUnsplittable(c->r3.b);
break;
}
if (adconvs != NULL) {
if (reads_r1(c->op)) MarkAdconvUnsplittable(c->r1.r, adconvs);
if (reads_r2(c->op)) MarkAdconvUnsplittable(c->r2.r, adconvs);
if (reads_r3(c->op)) MarkAdconvUnsplittable(c->r3.r, adconvs);
if (reads_r4(c->op)) MarkAdconvUnsplittable(c->r4.r, adconvs);
}
}
if (debugging(DEBUG_SR) && !(blkflags_(block) & BLKSWITCH)) {
Icode ic;
INIT_IC(ic, J_NOOP);
if (blkflags_(block) & BLK2EXIT) {
ic.op = J_B + (blkflags_(block) & Q_MASK);
ic.r3.l = blknext1_(block);
print_jopcode(&ic);
}
if (!(blkflags_(block) & BLK0EXIT)) {
ic.op = J_B;
ic.r3.l = blknext_(block);
print_jopcode(&ic);
}
}
if (blkflags_(block) & BLKREXPORTED) {
VRegnum exportedr = GAP;
if (blkflags_(block) & BLKREXPORTED2) {
c--;
if (loads_r1(c->op) && !isany_realreg_(c->r1.r))
exportedr = c->r1.r;
}
for (; adconvs != NULL; adconvs = AdconvList_DiscardOne(adconvs))
if (exportedr == GAP || exportedr == adconvs->r) {
if (debugging(DEBUG_SR))
cc_msg("Binder $b unsplittable (exportedr)\n", adconvs->b);
bindvklist_(adconvs->b)->splittable = NO;
}
} else if (adconvs != NULL) {
AdconvList **pp = &adconvs;
for (; *pp != NULL; pp = &cdr_(*pp)) continue;
*pp = adconv_unused;
adconv_unused = adconvs;
}
}
static void FillInFields(Binder *b, unsigned32 n) {
VKList *v = bindvklist_(b);
VKLoc **locsp = &v->locs;
VKLoc *locs;
unsigned32 offset = 0;
if (v->splittable) {
/* Even a structure referenced only as a whole (*locsp == NULL */
/* here) is worth splitting: it's the only way that unwanted */
/* writes to it can be discarded. */
for (; offset < n; locsp = &cdr_(locs)) {
locs = *locsp;
if (locs != NULL && offset == locs->offset)
offset += memsize[locs->type];
else {
unsigned32 isize = memsize[MEM_I];
unsigned32 size = n - offset;
if (locs != NULL && size > locs->offset - offset)
size = locs->offset - offset;
if (size % isize != 0) {
offset = 0;
break;
}
for (; size != 0; offset += isize, size -= isize) {
VKLoc *p = VKLoc_New(locs, offset, (int)MEM_I, GAP);
*locsp = p; locsp = &cdr_(p);
}
}
}
if (offset != n) v->splittable = NO;
}
}
static bool CheckSameStructure(Binder *b1, Binder *b2, unsigned32 n) {
/* There is a structure assignment from b2 to b1. Check that b1 and b2 have
the same structure, as far as it's known, and fill in the unknown bits
from the other. If there's a mismatch, mark both b1 and b2 as
unsplittable (really, only one need be marked, but which?).
*/
VKList *v1 = bindvklist_(b1),
*v2 = bindvklist_(b2);
VKLoc **locs1p = &v1->locs,
**locs2p = &v2->locs;
unsigned32 offset = 0;
unsigned32 size;
for (; offset < n; offset += size) {
VKLoc *locs1 = *locs1p,
*locs2 = *locs2p;
if (locs1 != NULL && offset == locs1->offset) {
size = memsize[locs1->type];
if (locs2 != NULL && offset == locs2->offset) {
if (locs1->type != locs2->type) {
offset = 0;
break;
}
} else if (locs2 != NULL && offset+size > locs2->offset) {
offset = 0;
break;
} else
*locs2p = locs2 = VKLoc_New(locs2, offset, locs1->type, locs1->ruse);
locs1p = &cdr_(locs1); locs2p = &cdr_(locs2);
} else if (locs2 != NULL && offset == locs2->offset) {
size = memsize[locs2->type];
if (locs1 != NULL && offset+size > locs1->offset) {
offset = 0;
break;
} else
*locs1p = locs1 = VKLoc_New(locs1, offset, locs2->type, locs2->ruse);
locs1p = &cdr_(locs1); locs2p = &cdr_(locs2);
} else {
unsigned32 isize = memsize[MEM_I];
size = n - offset;
if (locs1 != NULL && size > locs1->offset - offset)
size = locs1->offset - offset;
if (locs2 != NULL && size > locs2->offset - offset)
size = locs2->offset - offset;
if (size % isize != 0) {
offset = 0;
break;
}
for (; size != 0; offset += isize, size -= isize) {
VKLoc *p = VKLoc_New(locs1, offset, (int)MEM_I, GAP);
*locs1p = p; locs1p = &cdr_(p);
p = VKLoc_New(locs2, offset, (int)MEM_I, GAP);
*locs2p = p; locs2p = &cdr_(p);
}
}
}
if (offset != n) {
v1->splittable = v2->splittable = NO;
return NO;
} else
return YES;
}
static RegSort SortOfReg(VRegnum r) {
if (r != GAP) switch (vregsort(r)) {
case FLTREG: return FLTREG;
case DBLREG: return DBLREG;
#ifdef ADDRESS_REG_STUFF
case ADDRREG: return ADDRREG;
#endif
}
return INTREG;
}
static J_OPCODE LDRV_Op(int32 memtype) {
switch (memtype) {
case MEM_F: return J_LDRFV | J_ALIGN4;
case MEM_D: return J_LDRDV | J_ALIGN8;
case MEM_LL: return J_LDRLV | J_ALIGN8;
default: return J_LDRV | J_ALIGN4;
}
}
static Binder *SR_NewBinder(char *name, VRegnum oldr) {
/* @@@ The following code should share with with addcsebinder(), */
/* particularly beware te_int for 64-bit machines. */
RegSort regsort = SortOfReg(oldr);
return gentempvarofsortwithname(regsort, name);
}
static void SplitStructs(BindList *local_binders, BindList *regvar_binders) {
/* Here we turn non address taken local structures into a set of */
/* binders, one per field. Fields must be disjoint, and accessed only */
/* in one way (unions of machine-level distinct types not allowed). */
/* For structures accessed only by loads and stores, ({LD/ST}RxVK) */
/* this transformation is regardless of size: those assigned to and */
/* from (MOVC) are transformed only if they are sufficiently small. */
BlockHead *b;
int32 argwords = 0;
vklist = NULL;
setsplist = NULL;
movclist = NULL, movctail = &movclist;
adconv_unused = NULL;
movc_unknown = NULL;
if (debugging(DEBUG_SR))
cc_msg("Splitting structures\n\n");
for (b = top_block; b != NULL; b = blkdown_(b))
SplitStructs_ScanBlock(b);
{ RegList *rl = movc_unknown;
for (; rl != NULL; rl = rl->rlcdr) {
AdconvList *a = adconv_unused;
VRegnum r = rl->rlcar;
for (; a != NULL; a = cdr_(a))
if (a->r == r) {
if (debugging(DEBUG_SR))
cc_msg("$b unsplittable (adconv_unused)\n", a->b);
MarkBinderUnsplittable(a->b);
break;
}
}
}
{ MOVCList *p = movclist;
for (; p != NULL; p = cdr_(p))
if (p->b1 == NULL)
FillInFields(p->b2, p->ic->r3.i);
else if (p->b2 == NULL)
FillInFields(p->b1, p->ic->r3.i);
else
CheckSameStructure(p->b1, p->b2, p->ic->r3.i);
}
{ VKList *p; VKLoc *loc;
/* Argument structures some of whose fields aren't integers can't */
/* be split */
for (p = vklist; p != NULL; p = cdr_(p))
if (BinderIsArg(p->b))
for (loc = p->locs; loc != NULL; loc = cdr_(loc))
if (loc->type != MEM_I) {
if (debugging(DEBUG_SR))
cc_msg("$b unsplittable (argument with non-int field)\n", p->b);
p->splittable = NO;
break;
}
for (p = vklist; p != NULL; p = cdr_(p))
if (p->splittable) {
Binder *oldb = p->b;
bool isarg = BinderIsArg(oldb);
/* p->locs == NULL and p->splittable means completely unused. */
/* (Probably CSE discarded uses). Splitting the struct is the */
/* easy way to discard it. */
if (p->locs == NULL) {
if ((bindmcrep_(oldb) & MCR_SIZE_MASK) >= sizeof_int)
FillInFields(oldb, sizeof_int);
else {
if (debugging(DEBUG_SR))
cc_msg("$b unsplittable (referenced argument)\n", p->b);
p->splittable = NO;
}
if (!p->splittable) continue;
}
if (debugging(DEBUG_SR | DEBUG_CG))
cc_msg("split $b\n", oldb);
for (loc = p->locs; loc != NULL; loc = cdr_(loc)) {
char name[128];
VKUse *use;
Binder *newb;
sprintf(name, "<%s.%ld>", symname_(bindsym_(oldb)), loc->offset);
newb = SR_NewBinder(name, loc->ruse);
if (isarg) {
argwords++;
bindaddr_(newb) = bindaddr_(oldb) + loc->offset;
} else
bindstg_(newb) |= b_bindaddrlist;
for (use = loc->uses; use != NULL; use = cdr_(use)) {
Icode *c = use->use;
c->op = J_XtoY(c->op, J_LDRVK, J_LDRV);
c->r2.r = GAP;
c->r3.b = newb;
}
loc->bind = newb;
}
{ BindList *bl = NULL;
for (b = top_block; b != NULL; b = blkdown_(b)) {
bl = bindlist_member(p->b, blkstack_(b));
if (bl != NULL) break;
}
if (bl == NULL) {
VKUse *sp;
for (sp = setsplist; sp != NULL; sp = cdr_(sp)) {
bl = bindlist_member(p->b, sp->use->r2.bl);
if (bl == NULL && sp->use->op == J_SETSPENV)
bl = bindlist_member(p->b, sp->use->r3.bl);
if (bl != NULL) break;
}
}
SpliceInBL(bl, p->locs, YES);
SpliceInBL(bindlist_member(p->b, local_binders), p->locs, NO);
SpliceInBL(bindlist_member(p->b, regvar_binders), p->locs, NO);
SpliceInBL(bindlist_member(p->b, argument_bindlist), p->locs, NO);
}
}
}
{ MOVCList *p, **pp = &movclist;
for (; (p = *pp) != NULL; ) {
if (p->b1 != NULL && !bindvklist_(p->b1)->splittable) p->b1 = NULL;
if (p->b2 != NULL && !bindvklist_(p->b2)->splittable) p->b2 = NULL;
if (p->b1 == NULL && p->b2 == NULL)
*pp = cdr_(p);
else
pp = &cdr_(p);
}
if (argwords != 0) {
BlockHead *b = top_block;
int32 oldl = blklength_(b);
Icode *newic = newicodeblock(oldl+argwords);
Icode *oldic = blkcode_(b);
VKList *vk;
int32 n;
blkcode_(b) = newic;
/* Copy everything up to J_ENTER */
n = 0;
do { *newic++ = *oldic++; n++; } while (((newic-1)->op & J_TABLE_BITS) != J_ENTER);
blklength_(b) += argwords;
for (vk = vklist; vk != NULL; vk = cdr_(vk)) {
VKLoc *loc;
if (vk->splittable && BinderIsArg(vk->b))
for (loc = vk->locs; loc != NULL; loc = cdr_(loc), newic++) {
VRegnum ir = ArgumentRegister(loc->bind);
INIT_IC(*newic, J_MOVR);
newic->r1.r = bindxx_(loc->bind);
newic->r3.r = R_P1+ir;
}
}
memcpy(newic, oldic, (size_t)(oldl-n) * sizeof(Icode));
}
for (p = movclist; p != NULL; ) {
BlockHead *b = p->block;
MOVCList *q;
int32 n = 0;
for (q = p; q != NULL && q->block == b; q = cdr_(q)) {
unsigned32 size = q->ic->r3.i;
Binder *b = q->b1 == NULL ? q->b2 : q->b1;
VKLoc *loc = bindvklist_(b)->locs;
for (; loc != NULL; loc = cdr_(loc))
if (loc->offset < size) n += 2;
n--;
}
{ int32 oldl = blklength_(b);
Icode *newic = newicodeblock(oldl+n);
Icode *oldic = blkcode_(b);
int32 i;
blkcode_(b) = newic;
blklength_(b) += n;
for ( i = 0 ; i != oldl ; i++ ) {
if (p == q || &oldic[i] != p->ic)
*newic++ = oldic[i];
else {
unsigned32 size = p->ic->r3.i;
Binder *b1 = p->b1,
*b2 = p->b2;
VKLoc *loc, *loc2;
if (b1 == NULL)
loc = loc2 = VKLoc_ReverseCopy(bindvklist_(b2)->locs);
else {
loc = bindvklist_(b1)->locs;
loc2 = b2 == NULL ? NULL : bindvklist_(b2)->locs;
}
for (; loc != NULL; loc = cdr_(loc))
if (loc->offset >= size) {
if (loc2 != NULL) loc2 = cdr_(loc2);
} else {
VRegnum r = vregister(SortOfReg(loc->ruse));
if (b2 == NULL) {
INIT_IC(*newic, J_XtoY(LDRV_Op(loc->type), J_LDRV, J_LDRK));
newic->r1.r = r;
newic->r2 = p->ic->r2;
newic->r3.i = loc->offset;
} else {
INIT_IC(*newic, LDRV_Op(loc->type));
newic->r1.r = r;
newic->r3.b = loc2->bind;
loc2 = cdr_(loc2);
}
newic++;
if (b1 == NULL) {
INIT_IC(*newic, J_LDtoST(J_XtoY(LDRV_Op(loc->type), J_LDRV, J_LDRK)));
newic->r1.r = r;
newic->r2 = p->ic->r1;
newic->r3.i = loc->offset;
} else {
INIT_IC(*newic, J_LDtoST(LDRV_Op(loc->type)));
newic->r1.r = r;
newic->r3.b = loc->bind;
}
newic++;
}
p = cdr_(p);
}
}
}
}
}
{ VKList *p;
for (p = vklist; p != NULL; p = cdr_(p)) {
bindxx_(p->b) = p->bindxx;
bindstg_(p->b) ^= u_loctype;
}
}
}
struct SRBlockHead {
VRegSetP reach, gen, kill, use;
};
#define sr_kill_(p) (blksr_(p)->kill)
#define sr_use_(p) (blksr_(p)->use)
#define sr_gen_(p) (blksr_(p)->gen)
#define sr_reach_(p) (blksr_(p)->reach)
typedef struct SR_UseList SR_UseList;
typedef struct SR_DefList SR_DefList;
typedef struct SR_Def SR_Def;
struct SR_Def {
SR_Def *cdr;
unsigned32 index;
BlockHead *block;
int32 ic;
SR_UseList *uses;
VRegSetP usedefs;
};
struct SR_DefList {
SR_DefList *cdr;
SR_Def *def;
};
#define mkSR_DefList(a,b) (SR_DefList *)syn_list2(a,b)
typedef struct SR_Use SR_Use;
struct SR_Use {
SR_Use *cdr;
BlockHead *block;
int32 ic;
VRegSetP def;
};
struct SR_UseList {
SR_UseList *cdr;
SR_Use *use;
};
#define mkSR_UseList(a,b) (SR_UseList *)syn_list2(a,b)
typedef struct SR_Binder SR_Binder;
struct SR_Binder {
SR_Binder *cdr;
unsigned32 index;
Binder *binder;
SR_Def *defs;
SR_Use *uses;
VRegSetP defset;
SuperBinder *super;
};
SuperBinder *superbinders;
#define SRSEGSIZE 512
#define SRINDEXSIZE 64
#define SRSEGBITS 9
static SR_Binder **binderindex[SRINDEXSIZE];
#define sr_binder_(id) (binderindex[(id)>>SRSEGBITS])[(id)&(SRSEGSIZE-1)]
#define SRHASHSIZE 512
#define SRHASH(b) ((((IPtr)b>>2) |((IPtr)b>>11)) & (SRHASHSIZE-1))
static SR_Binder **binderhash;
static unsigned32 bindercount;
static unsigned32 defcount;
static VRegSetAllocRec allocrec;
static unsigned32 nsets, newsets, setbytes;
#define debug_sr debugging(DEBUG_SPILL)
static SR_Binder *LookupBinder(Binder *b) {
SR_Binder *p, **pp = &binderhash[SRHASH(b)];
if (bindstg_(b) & (b_addrof+b_spilt+b_globalregvar) || bindxx_(b) == GAP)
return NULL;
for (; (p = *pp) != NULL; pp = &cdr_(p))
if (p->binder == b) return p;
{ unsigned32 id = bindercount++;
SR_Binder **index = binderindex[id>>SRSEGBITS];
p = NewSyn(SR_Binder);
cdr_(p) = NULL; p->index = id; p->binder = b;
p->defs = NULL; p->uses = NULL; p->defset = NULL;
p->super = NULL;
*pp = p;
if (index == NULL) {
index = NewSynN(SR_Binder *, SRSEGSIZE);
binderindex[id>>SRSEGBITS] = index;
ClearToNull((void **)index, SRSEGSIZE);
}
index[id & (SRSEGSIZE-1)] = p;
}
return p;
}
static SR_Binder *AddDef(Binder *b, BlockHead *block, int32 ic) {
SR_Binder *sr = LookupBinder(b);
if (sr != NULL) {
unsigned32 n = defcount++;
SR_Def *p = NewSyn(SR_Def);
cdr_(p) = sr->defs; sr->defs = p;
p->index = n;
p->block = block; p->ic = ic;
p->uses = NULL;
sr->defset = vregset_insert(n, sr->defset, NULL, &allocrec);
if (debug_sr) cc_msg("%ld $b %ld:%ld\n", n, b, lab_name_(blklab_(block)), ic);
}
return sr;
}
static void Scan_MakeGenSet(int32 n, void *arg) {
BlockHead *b = (BlockHead *)arg;
SR_Binder *sr = sr_binder_(n);
sr_gen_(b) = vregset_insert(sr->defs->index, sr_gen_(b), NULL, &allocrec);
}
static void ScanBlock(BlockHead *block) {
Icode *c, *limit;
VRegSetP use = NULL, kill = NULL, gen = NULL;
/* gen set of binders defined in this blocks whose definition reaches the end.
kill set of binders whose definition on block entry is killed before block
end (since we only concern ourself with simple non-address-taken object
binders, gen and kill are very similar. In fact, they differ only for
top_block, where arguments are members of gen but not kill).
use the set of binders read in the block where the read is reached by
definitions entering the block.
*/
for (c = blkcode_(block), limit = c + blklength_(block); c < limit; ++c)
switch (c->op & J_TABLE_BITS) {
case J_LDRBV: case J_LDRWV:
case J_LDRV: case J_LDRLV:
case J_LDRFV: case J_LDRDV:
{ SR_Binder *sr = LookupBinder(c->r3.b);
if (sr != NULL) {
SR_Use *p = NewSyn(SR_Use);
cdr_(p) = sr->uses; sr->uses = p;
p->block = block; p->ic = c - blkcode_(block);
/* Uses with a definition in the same block do not get added to */
/* the use set, but must be linked to the definition immediately. */
if (!vregset_member(sr->index, gen)) {
use = vregset_insert(sr->index, use, NULL, &allocrec);
p->def = NULL;
} else
p->def = vregset_insert(sr->defs->index, NULL, NULL, &allocrec);
}
break;
}
case J_MOVR: case J_MOVIDR: case J_MOVIFR:
case J_MOVDR: case J_MOVDFR:
/* Special case of initialisation of the binder for an argument passed */
/* in a register. It's a pain that these aren't handled in the natural */
/* way, by stores into the binder. */
if (block == top_block && isany_realreg_(c->r3.r)) {
BindList *bl = argument_bindlist;
for (; bl != NULL; bl = cdr_(bl))
if (bindxx_(bl->bindlistcar) == c->r1.r) {
SR_Binder *sr = AddDef(bl->bindlistcar, block, c - blkcode_(block));
if (sr != NULL) gen = vregset_insert(sr->index, gen, NULL, &allocrec);
break;
}
}
break;
case J_LDRV1: case J_LDRLV1:
case J_LDRFV1: case J_LDRDV1:
/* Initialisation of the binder for an argument passed on the stack. */
case J_INIT: case J_INITF: case J_INITD:
case J_STRBV: case J_STRWV:
case J_STRV: case J_STRLV:
case J_STRFV: case J_STRDV:
{ SR_Binder *sr = AddDef(c->r3.b, block, c - blkcode_(block));
if (sr != NULL) {
kill = vregset_insert(sr->index, kill, NULL, &allocrec);
gen = vregset_insert(sr->index, gen, NULL, &allocrec);
}
break;
}
}
/* We can turn gen directly into a set of binder definitions now: use and kill
must wait until all blocks have been scanned (when we know the set of all
definitions for each binder).
*/
sr_use_(block) = use;
sr_kill_(block) = kill;
sr_gen_(block) = NULL;
sr_reach_(block) = NULL;
vregset_map(gen, Scan_MakeGenSet, (void *)block);
vregset_discard(gen);
}
static void SR_MakeKilledSet(int32 n, void *arg) {
BlockHead *b = (BlockHead *)arg;
SR_Binder *sr = sr_binder_(n);
sr_kill_(b) = vregset_union(sr_kill_(b), sr->defset, &allocrec);
}
static bool ReachSucc(LabelNumber *lab, VRegSetP reachpred) {
if (!is_exit_label(lab)) {
BlockHead *b = lab->block;
if (vregset_compare(reachpred, sr_reach_(b)) > VR_EQUAL) {
sr_reach_(b) = vregset_union(sr_reach_(b), reachpred, &allocrec);
return YES;
}
}
return NO;
}
static void ReplaceBinder(SR_Def *def, Binder *newb, Binder *oldb) {
SR_UseList *p = def->uses;
Icode *ip = &blkcode_(def->block)[def->ic];
switch (ip->op & J_TABLE_BITS)
{
case J_INIT: case J_INITF: case J_INITD:
ip->r3.b = newb;
ip->r1.r = bindxx_(newb);
if (p != NULL && (feature & FEATURE_ANOMALY))
cc_warn(regalloc_warn_use_before_set, oldb);
break;
case J_LDRV1: case J_LDRLV1:
case J_LDRFV1: case J_LDRDV1:
ip->r3.b = newb;
ip->r1.r = bindxx_(newb);
break;
case J_MOVR: case J_MOVIDR: case J_MOVIFR:
case J_MOVDR: case J_MOVDFR:
/* Special case of initialisation of the binder for an argument passed
* in registers
*/
ip->r1.r = bindxx_(newb);
break;
default:
ip->r3.b = newb;
}
for (; p != NULL; p = cdr_(p))
blkcode_(p->use->block)[p->use->ic].r3.b = newb;
}
static Binder *SubBinder(SR_Binder *p, SR_Def *def) {
Binder *newb;
Binder *oldb = p->binder;
if (p->super == NULL) {
SuperBinder *super = NewBind(SuperBinder);
cdr_(super) = superbinders; superbinders = super;
super->binder = oldb;
super->spillcount = 0;
p->super = super;
}
/* @@@ The following code should share with with addcsebinder(), */
/* particularly beware te_int for 64-bit machines. */
{ char name[128];
char *oldname = symname_(bindsym_(oldb));
sprintf(name, "<%s__%ld:%ld>",
oldname, lab_name_(blklab_(def->block)), def->ic);
newb = SR_NewBinder(name, bindxx_(oldb));
bindstg_(newb) = (bindstg_(oldb) & ~b_bindaddrlist) | b_pseudonym;
bindsuper_(newb) = p->super;
return newb;
}
}
static BindList *splitranges_i(BindList *local_binders, BindList *regvar_binders) {
BindList *newbinders = NULL;
if (!(var_cc_private_flags & 131072L)) {
phasename = "SplitStructs";
SplitStructs(local_binders, regvar_binders);
}
if (!(var_cc_private_flags & 256L)) {
BlockHead *b;
phasename = "SplitRanges";
defcount = bindercount = 0;
vregset_init();
binderhash = NewSynN(SR_Binder *, SRHASHSIZE);
ClearToNull((void **)binderhash, SRHASHSIZE);
ClearToNull((void **)binderindex, SRINDEXSIZE);
for (b = top_block; b != NULL; b = blkdown_(b)) {
blksr_(b) = NewSyn(SRBlockHead);
ScanBlock(b);
}
for (b = top_block; b != NULL; b = blkdown_(b)) {
VRegSetP killedbinders = sr_kill_(b);
sr_kill_(b) = NULL;
vregset_map(killedbinders, SR_MakeKilledSet, (void *)b);
}
{ bool changed;
do {
if (debug_sr) cc_msg("Reaching definition iteration\n");
changed = NO;
for (b = top_block; b != NULL; b = blkdown_(b)) {
VRegSetP reachend = vregset_copy(sr_reach_(b), &allocrec);
reachend = vregset_difference(reachend, sr_kill_(b));
reachend = vregset_union(reachend, sr_gen_(b), &allocrec);
if (blkflags_(b) & BLKSWITCH) {
LabelNumber **v = blktable_(b);
int32 i, n = blktabsize_(b);
for (i = 0 ; i < n ; i++)
changed = changed | ReachSucc(v[i], reachend);
} else {
changed = changed | ReachSucc(blknext_(b), reachend);
if (blkflags_(b) & BLK2EXIT)
changed = changed | ReachSucc(blknext1_(b), reachend);
}
}
} while (changed);
}
{ unsigned32 bno = 0;
for (; bno < bindercount; bno++) {
SR_Binder *p = sr_binder_(bno);
SR_Use *use; SR_Def *def, *d;
for (use = p->uses; use != NULL; use = cdr_(use)) {
if (use->def == NULL) {
use->def = vregset_copy(sr_reach_(use->block), &allocrec);
use->def = vregset_intersection(use->def, p->defset);
}
}
for (def = p->defs; def != NULL; def = cdr_(def)) {
unsigned32 ix = def->index;
VRegSetP defset = NULL;
for (use = p->uses; use != NULL; use = cdr_(use))
if (vregset_member(ix, use->def)) {
def->uses = mkSR_UseList(def->uses, use);
defset = vregset_union(defset, use->def, &allocrec);
}
def->usedefs = defset;
}
{ bool changed;
do {
changed = NO;
for (def = p->defs; def != NULL; def = cdr_(def)) {
VRegSetP defset = def->usedefs;
for (d = p->defs; d != NULL; d = cdr_(d))
if (d != def && vregset_member(d->index, defset) &&
vregset_compare(defset, d->usedefs) != VR_EQUAL) {
changed = YES;
defset = vregset_union(defset, d->usedefs, &allocrec);
d->usedefs = vregset_union(d->usedefs, defset, &allocrec);
}
def->usedefs = defset;
}
} while (changed);
}
{ SR_DefList *defl = NULL;
SR_Def *nextdef;
for (def = p->defs; def != NULL; def = nextdef) {
VRegSetP defset = def->usedefs;
SR_Def *q, **qp;
nextdef = cdr_(def);
cdr_(def) = NULL;
defl = mkSR_DefList(defl, def);
for (qp = &nextdef; (q = *qp) != NULL;)
if (vregset_compare(defset, q->usedefs) == VR_EQUAL) {
*qp = cdr_(q);
cdr_(q) = defl->def;
defl->def = q;
} else
qp = &cdr_(q);
}
/* defl == NULL is possible here, though curious, thanks to the */
/* workings of deadcode (otherwise, there's always at least a */
/* J_INIT definition). */
if ( defl != NULL &&
cdr_(defl) != NULL &&
/* Definitions do partition into more than one set */
/* Avoid the case where one set is just a J_INIT with no uses */
( cdr_(cdr_(defl)) != NULL ||
( (cdr_(defl->def) != NULL || defl->def->uses != NULL) &&
(cdr_(cdr_(defl)->def) != NULL || cdr_(defl)->def->uses != NULL)) ) ) {
if (debug_sr)
cc_msg("Split $b:", p->binder);
for (; defl != NULL; defl = cdr_(defl)) {
SR_Def *d = defl->def;
Binder *newb = SubBinder(p, d);
SR_Def *initd = d;
char *s1 = " {", *s2 = "";
newbinders = mkBindList(newbinders, newb);
if (debug_sr)
cc_msg(" $b", newb);
for (; d != NULL; d = cdr_(d)) {
ReplaceBinder(d, newb, p->binder);
if (debug_sr && d != initd) {
cc_msg("%s%ld:%ld", s1, lab_name_(blklab_(d->block)), d->ic);
s1 = ", "; s2 = "}";
}
}
if (debug_sr) cc_msg("%s", s2);
}
if (debug_sr) cc_msg("\n");
bindxx_(p->binder) = GAP;
}
}
}
}
}
if ( debugging(DEBUG_CG) &&
(var_cc_private_flags & (131072L+256L)) != (131072L+256L))
flowgraf_print("After range splitting:", NO);
return newbinders;
}
BindList *splitranges(BindList *local_binders, BindList *regvar_binders) {
BindList *newbinders = NULL;
BlockHead *b;
superbinders = NULL;
if (!usrdbg(DBG_LINE+DBG_VAR))
newbinders = splitranges_i(local_binders, regvar_binders);
for (b = top_block; b != NULL; b = blkdown_(b)) {
/* Although flowgraf also wants blkusedfrom_() for cross-jumping and
conditionalising, it wants a version after branch chaining, and the
branch chaining algorithm can't easily adjust it.
*/
BlockList *bl = blkusedfrom_(b);
while (bl != NULL) bl = (BlockList *)discard2((List *)bl);
blkusedfrom_(b) = NULL;
vregset_discard(blk_dominators_(b));
blk_dominators_(b) = NULL;
}
return newbinders;
}
void splitrange_init(void) {
allocrec.alloctype = AT_Syn;
allocrec.statsloc = &nsets;
allocrec.statsloc1 = &newsets;
allocrec.statsbytes = &setbytes;
}
|
stardot/ncc | mip/codebuf.c | <reponame>stardot/ncc
/*
* C compiler file codebuf.c.
* Copyright (C) Codemist Ltd, 1988-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 30
* Checkin $Date$
* Revising $Author$
*/
/* Memo to AM: 1. tidy up mustlitby interface (only arm uses so far). */
/* also observe 2 "transsex compilation worry"s (AM check). */
/* AM Dec 90: remove much BSS code since now unified in mip/bind.c */
/* AM May 89: remove packing of (24 bit) pointer and LIT_xxx flags. */
/* All 'aux' fields below are ONLY for producing nicely formatted asm -- */
/* they are NOT to be used for object output for which code_flag_ is still */
/* appropriate. */
/* AM July 88: elide setlabel(litlab) if empty pool (space/asm listing). */
/* AM June 88: bug fix: move call to optimise_code() to gen.c case ENDPROC */
/* AM April 88: change codeseg_flush interface with vargen.c */
/* AM 10-oct-86: this file contains (hopefully) machine independent
code buffering routines, literal buffering etc.
*/
/* Memo: should we conditionally (TARGET_IS_ARM) compile count_name et al? */
/* exports - for reading only: codebase, codep, litpoolp */
#ifdef __STDC__
# include <string.h>
#else
# include <strings.h>
#endif
#include "globals.h"
#include "codebuf.h"
#include "cgdefs.h"
#include "store.h"
#include "xrefs.h"
#include "bind.h" /* for sym_insert_id in ACW case, and ARM case */
#include "builtin.h" /* for codesegment */
#include "util.h"
#include "mcdep.h"
#include "errors.h"
#include "aeops.h" /* bitofstg_ */
#ifdef PUT_FILE_NAME_IN_AREA_NAME
# include "fname.h"
# include "compiler.h"
#endif
static DataDesc data, *datap, extable, exhandler;
#ifdef CONST_DATA_IN_CODE
static DataDesc constdata; /* ensure not used by accident */
#endif
ExceptionEnv *currentExceptionEnv;
int32 code_area_idx; /* exported for armcc -S -ZO ... */
static bool codebuf_inroutine;
/* codeloc and codeseg_flush added by AM (to old emit.c),
*** probably in a silly position ***
The idea is that declarations of the form 'static char *a = "abc";'
put "abc" in the code segment and just put a pointer in the data
segment (it is as non modifyable as other strings) */
/* codeandflagvec and codeasmauxvec are doubly indexed by a BYTE address: */
struct CodeAndFlag *codeandflagvec[CODEVECSEGMAX];
#ifndef NO_ASSEMBLER_OUTPUT /* i.e. lay off otherwise */
VoidStar (*(codeasmauxvec[CODEVECSEGMAX]))[CODEVECSEGSIZE];
#endif
static int32 codeveccnt;
int32 codebase, codep;
static int32 maxprocsize;
static char *maxprocname;
/* litpool is of fixed size (LITPOOLSEGMAX*LITPOOLSEGSIZE), */
/* but with overflow taken care of. */
typedef struct {
int32 val, type; Symstr *xref;
VoidStar litaux; /* Only used #ifndef NO_ASSEMBLER_OUTPUT */
/* Could in principle share with xref field? */
} LitPoolEntry;
static LitPoolEntry (*(litpool[LITPOOLSEGMAX]))[LITPOOLSEGSIZE];
#define litpool_(n) (*litpool[(n)>>LITPOOLSEGBITS])[(n)&LITPOOLSEGSIZE-1]
static int32 litveccnt;
static int32 litalign;
int32 litpoolp;
LabelNumber *litlab;
static int32 next_label_name;
LabList *asm_lablist; /* @@@ This is not really part of codebuf */
/* One day it might join obj_symref in */
/* here as "gen/obj/asm support. */
/* For the sake of a cleaner separation between the FE and the BE */
DataInit *get_datadesc_ht(bool head)
{ return (head) ? datap->head : datap->tail;
}
void set_datadesc_ht(bool head, DataInit *val)
{ if (head) datap->head = val; else datap->tail = val;
}
int32 get_datadesc_size(void)
{ return datap->size;
}
void set_datadesc_size(int32 val)
{ datap->size = val;
}
DataXref *get_datadesc_xrefs(void)
{ return datap->xrefs;
}
void set_datadesc_xrefs(DataXref *val)
{ datap->xrefs = val;
}
int get_datadesc_xrarea(void)
{ return datap->xrarea;
}
void set_datadesc_xrarea(int val)
{ datap->xrarea = val;
}
DataDesc *get_datadesc(void)
{ return datap;
}
void copy_datadesc(DataDesc *dest)
{ *dest = data;
}
void restore_datadesc(DataDesc *src)
{ data = *src;
}
int32 data_size(void)
{ return data.size;
}
DataInit *data_head(void)
{ return data.head;
}
DataXref *data_xrefs(void)
{ return data.xrefs;
}
DataInit *get_extable_ht(bool head)
{ return (head) ? extable.head : extable.tail;
}
void set_extable_ht(bool head, DataInit *val)
{ if (head) extable.head = val; else extable.tail = val;
}
void set_extable_size(int32 val)
{ extable.size = val;
}
int32 extable_size(void)
{ return extable.size;
}
DataInit *extable_head(void)
{ return extable.head;
}
DataXref *extable_xrefs(void)
{ return extable.xrefs;
}
bool is_extable(void)
{ return (datap == &extable);
}
DataInit *get_exhandler_ht(bool head)
{ return (head) ? exhandler.head : exhandler.tail;
}
void set_exhandler_ht(bool head, DataInit *val)
{ if (head) exhandler.head = val; else exhandler.tail = val;
}
void set_exhandler_size(int32 val)
{ exhandler.size = val;
}
int32 exhandler_size(void)
{ return exhandler.size;
}
DataInit *exhandler_head(void)
{ return exhandler.head;
}
DataXref *exhandler_xrefs(void)
{ return exhandler.xrefs;
}
bool is_exhandler(void)
{ return (datap == &exhandler);
}
#ifdef CONST_DATA_IN_CODE
int32 constdata_size(void)
{ return constdata.size;
}
DataInit *constdata_head(void)
{ return constdata.head;
}
DataXref *constdata_xrefs(void)
{ return constdata.xrefs;
}
bool is_constdata(void)
{ return (datap == &constdata);
}
DataAreaSort SetDataArea(DataAreaSort sort) {
DataAreaSort oldsort = is_constdata() ? DS_Const : DS_ReadWrite;
if (sort == DS_Const)
datap = &constdata;
else if (sort == DS_ReadWrite)
datap = &data;
return oldsort;
}
#else
DataAreaSort SetDataArea(DataAreaSort sort) {
datap = &data;
return DS_ReadWrite;
}
#endif
/* obj/asm calls totargetsex() to get host word (as used internally */
/* in the compiler) into target sex for asm output or object file. */
/* It acts as a no-op if host sex is the same as target sex. */
int32 totargetsex(int32 w, int flag)
{ /* casts in next lines ensure host byte sex independence */
unsigned8 *pb = (unsigned8 *)&w;
unsigned16 *ph = (unsigned16 *)&w;
typedef unsigned32 u;
if (target_lsbytefirst == host_lsbytefirst) return w; /* short cut */
#ifdef TARGET_HAS_HALFWORD_INSTRUCTIONS
if (flag == LIT_OPCODE) flag = LIT_HH;
#endif
#ifdef TARGET_HAS_BYTE_INSTRUCTIONS
if (flag == LIT_OPCODE) flag = LIT_BBBB;
#endif
switch (flag)
{
default: syserr(syserr_totarget, flag); return w;
case LIT_BXXX:
case LIT_BBX:
case LIT_BBBX:
case LIT_BBBB: return target_lsbytefirst ?
(u)pb[0] | (u)pb[1]<<8 | (u)pb[2]<<16 | (u)pb[3]<<24 :
(u)pb[0]<<24 | (u)pb[1]<<16 | (u)pb[2]<<8 | (u)pb[3];
case LIT_HH: return target_lsbytefirst ?
(u)ph[0] | (u)ph[1]<<16 :
(u)ph[0]<<16 | (u)ph[1];
case LIT_BBH: return target_lsbytefirst ?
(u)pb[0] | (u)pb[1]<<8 | (u)ph[1]<<16 :
(u)pb[0]<<24 | (u)pb[1]<<16 | (u)ph[1];
case LIT_HX:
case LIT_HBX:
case LIT_HBB: return target_lsbytefirst ?
(u)ph[0] | (u)pb[2]<<16 | (u)pb[3]<<24 :
(u)ph[0]<<16 | (u)pb[2]<<8 | (u)pb[3];
#ifdef THUMB_CPLUSPLUS
case LIT_OPCODE_32:
#endif
case LIT_OPCODE:
case LIT_RELADDR:
case LIT_NUMBER:
case LIT_ADCON:
case LIT_FPNUM:
case LIT_FPNUM1:
case LIT_FPNUM2:
case LIT_INT64_1:
case LIT_INT64_2:
return w;
}
}
static void adddata1(DataInit *x)
{
#ifndef FORTRAN /* blows up f77 formats, which aren't aligned -- MRC. */
/* AM thinks this is because fortran currently puts out non-aligned labels */
if (datap->wpos != 0) syserr(syserr_vg_wpos, (long)datap->wpos); /* consistency */
#endif
if (datap->head == 0) datap->head = datap->tail = x;
else datap->tail->datacdr = x, datap->tail = x;
}
static void adddata(DataInit *a, int32 b, int32 c, IPtr d, IPtr e)
{ DataInit *x = (DataInit *) GlobAlloc(SU_Data, sizeof(DataInit));
x->datacdr = a, x->rpt = b, x->sort = c, x->len = d, x->val = e;
adddata1(x);
}
/* (sizeof_ptr == 2) or unaligned */
/* This routine outputs a LIT_BBX or LIT_HX just before a LIT_ADCON in */
/* the case where pointers are 2 bytes long. In this case not all data */
/* initialisations can be bundled into units of 4 bytes. */
/* Maybe this code is useful for APRM too? */
static void vg_wflush(void)
{ unsigned bytes = datap->wpos & 3;
if (bytes != 0)
{ int lit_flag;
switch (datap->wtype)
{ default: syserr(syserr_vg_wflush, datap->wtype);
case 1: lit_flag = bytes == 1 ? LIT_BXXX : LIT_HX; break;
case 3: lit_flag = bytes == 2 ? LIT_BBX : LIT_HBX; break;
case 7: lit_flag = LIT_BBBX; break;
}
switch (bytes) {
case 1: datap->wbuff.w8[1] = 0;
case 2: datap->wbuff.w16[1] = 0; break;
case 3: datap->wbuff.w8[3] = 0;
}
datap->wpos = 0, datap->wtype = 0;
adddata(0, 1, lit_flag, bytes, datap->wbuff.w32[0]);
}
}
void gendcI_a(int32 len, int32 val, bool aligned)
{
if (debugging(DEBUG_DATA))
cc_msg("%.6lx: DC FL%ld'%ld'\n",
(long)datap->size, (long)len, (long)val);
#if (alignof_int < 2)
#error alignof_int unexpectedly low /* cross sex code fails */
#endif
if (len == 8) /* temporary code */
{ if (target_lsbytefirst) gendcI(4, val), gendcI(4, 0);
else gendcI(4, 0), gendcI(4, val);
return;
}
if (datap->wpos & (len-1)) vg_wflush();
if ((len != 1 && len != 2 && len != 4) ||
(aligned && (datap->wpos & len-1 & alignof_int-1)))
/* check consistent - includes integral alignment */
syserr(syserr_gendcI, (long)len, (long)datap->wpos);
switch (len)
{ case 1: datap->wbuff.w8[datap->wpos] = (unsigned8)val; break;
case 2: datap->wbuff.w16[datap->wpos>>1] = (unsigned16)val; break;
case 4: datap->wbuff.w32[0] = val; break;
}
datap->wtype = (datap->wtype << len) | 1; /* flag 'byte' boundaries */
datap->wpos += (unsigned)len;
if (datap->wpos == 4)
{ int32 lit_flag;
/* the following values could be coded into the LIT_xxx values */
switch (datap->wtype)
{ default: syserr(syserr_vg_wtype, datap->wtype);
case 1: lit_flag = LIT_NUMBER; break;
case 5: lit_flag = LIT_HH; break;
case 15: lit_flag = LIT_BBBB; break;
case 7: lit_flag = LIT_HBB; break;
case 13: lit_flag = LIT_BBH; break;
}
datap->wpos = 0, datap->wtype = 0;
adddata(0, 1, lit_flag, 4, datap->wbuff.w32[0]);
}
datap->size += len;
}
void gendcE(int32 len, FloatCon *val)
{ vg_wflush(); /* only if sizeof_ptr == 2 */
adddata(0, 1, LIT_FPNUM, len, (IPtr)val);
if (debugging(DEBUG_DATA))
{ cc_msg("%.6lx: ", (long)datap->size);
{ int32 *p = val -> floatbin.irep;
cc_msg(" %.8lx", (long)p[0]);
if (len == 8) cc_msg(" %.8lx", (long)p[1]);
cc_msg(" DC %ldEL%ld'%s'\n", (long)1, (long)len, val -> floatstr);
}
}
datap->size += len;
}
#ifdef TARGET_CALL_USES_DESCRIPTOR
void gendcF(Symstr *sv, int32 offset)
{ /* (possibly external) function name + (illegal) offset */
if (offset != 0) cc_err(vargen_err_badinit, sv, offset);
(void)obj_symref(sv, xr_code, 0);
datap->xrefs = (DataXref *) global_list3(SU_Xref, datap->xrefs, datap->size, sv);
vg_wflush(); /* only if sizeof_ptr == 2 */
adddata(0, 1, LIT_FNCON, (int32)sv, offset);
if (debugging(DEBUG_DATA))
cc_msg("%.6lx: DC FNA(%s+%ld)\n",
(long)datap->size, symname_(sv), (long)offset);
datap->size += sizeof_ptr;
}
static int32 fnconlab;
int32 genfncon(Symstr* sv)
{ int32 d = datap->size;
Symstr *ss;
char s[20];
sprintf(s, "_FNC%ld", fnconlab++);
ss = sym_insert_id(s);
labeldata(ss);
(void)obj_symref(ss, xr_data+xr_defloc, d);
gendcF(sv, 0);
return d;
}
#endif /* TARGET_CALL_USES_DESCRIPTOR */
void gendcAX(Symstr *sv, int32 offset, int xrflavour)
{ /* (possibly external) name + offset, flavour is xr_data or xr_code */
(void)obj_symref(sv, xrflavour, 0);
#ifdef TARGET_IS_RISC_OS
/* This could be a more generally useful re-entrancy type fragment. */
if (arthur_module && (xrflavour & xr_data))
cc_rerr(vargen_rerr_datadata_reloc, sv);
#endif
if (sizeof_ptr == 8 && !target_lsbytefirst) gendcI(4, 0);
datap->xrefs = (DataXref *) global_list3(SU_Xref, datap->xrefs, datap->size, sv);
vg_wflush(); /* only if sizeof_ptr == 2 */
adddata(0, 1, LIT_ADCON, (IPtr)sv, offset);
if (debugging(DEBUG_DATA))
cc_msg("%.6lx: DC A(%s+%ld)\n",
(long)datap->size, symname_(sv), (long)offset);
if (sizeof_ptr == 8 && target_lsbytefirst)
/* As what may be a short-term expedient I will leave the gendcI to my caller */
datap->size += sizeof_ptr-4 /* , gendcI(4, 0) */;
else
datap->size += sizeof_ptr;
}
void gendc0(int32 nbytes)
{ if (debugging(DEBUG_DATA))
cc_msg("%.6lx: DC %ldX'00'\n", (long)datap->size, (long)nbytes);
while (nbytes != 0 && datap->wpos != 0) gendcI(1,0), nbytes--;
if ((nbytes>>2) != 0)
adddata(0, nbytes>>2, LIT_NUMBER, 4, 0);
while (nbytes & 3) gendcI(1,0), nbytes--;
datap->size += nbytes;
}
void vg_genstring(StringSegList *p, int32 size, int pad)
{
int32 planted = 0;
for (; p != 0; p = p->strsegcdr)
{ unsigned char *s = (unsigned char *)p->strsegbase;
int32 n = p->strseglen;
while (n-- > 0)
{ if (planted < size)
gendcI(1,*s++), planted++;
else
return;
}
}
if (planted < size)
{ if (pad == 0)
gendc0(size-planted);
else while (planted++ < size)
gendcI(1, pad);
}
}
void padstatic(int32 align)
{
if (datap->size & (align-1)) gendc0((-datap->size) & (align-1));
if (align == 4) vg_wflush();
}
void labeldata(Symstr *s)
{
vg_wflush(); /* only if sizeof_ptr == 2 */
if (asmstream != NULL /* nasty space-saving hack */
&& s != NULL) /* labeldata(NULL) provides access to vg_wflush() externally */
adddata1((DataInit *)global_list5(SU_Data, (DataInit *)0, s, LIT_LABEL, 0, 0));
}
/* The following procedure is used to delete trailing zeros in
* auto structs, unions and arrays. It carries a PLG Heath Warning !!
* In short it just (optionally) hacks the trailing zeros off the last
* static data item defined. AM has (partly) house trained it.
* 'previous' should be the place preceeding where to start searching
* for zeros -- i.e. data.tail before call or 0 if no previous statics.
* AM: maybe we should hold datainit backwards and then this code
* would be nearly trivial, but compatibility problems.
* Note that it currently misses floating point zeros.
*/
int32 trydeletezerodata(DataInit *previous, int32 minsize)
{ int32 size = 0;
DataInit *p,*q = previous;
for (p = q ? q->datacdr : datap->head; p; p = p->datacdr)
switch (p->sort)
{ case LIT_BBBB: case LIT_HH: case LIT_BBH: case LIT_HBB:
case LIT_NUMBER:
if (p->val == 0) { size += p->rpt * 4; break; }
/* else drop through */
default:
size = 0, q = p;
}
if (size >= minsize)
{ if (q==0) datap->head = 0; else datap->tail=q, q->datacdr=0;
datap->size -= size;
return size;
}
return 0;
}
void show_entry(Symstr *name, int flags)
{ /* slightly specious for a routine, but tail recursion is free */
(void)obj_symref(name, flags, codebase);
}
void show_code(Symstr *name)
{ if (name == NULL && codep == 0) return;
#ifndef NO_ASSEMBLER_OUTPUT
if (asmstream) display_assembly_code(name);
#endif
#ifndef NO_OBJECT_OUTPUT
if (objstream) obj_codewrite(name);
#endif
/* test name to avoid counting char *s = "abc"-like things. */
if (name != NULL)
{ if (codep > maxprocsize)
{ maxprocsize = codep;
maxprocname = symname_(name);
}
}
codebase += codep;
codep = 0; /* for static init by string constants */
}
LabelNumber *nextlabel(void)
{
LabelNumber *w = (LabelNumber *) BindAlloc(sizeof(LabelNumber));
w->block = (BlockHead *) DUFF_ADDR; /* unset label - illegal ptr */
w->u.frefs = NULL; /* no forward refs yet */
w->name = next_label_name++; /* name + union discriminator for u */
return w;
}
void outcodeword(int32 w, int32 f) /* macro soon? */
{ outcodewordaux(w, f, 0);
}
void outcodewordaux(int32 w, int32 f, VoidStar aux)
{
#ifndef TARGET_IS_NULL
int32 q = codep; /* byte address */
/* ECN: q+2 below allows q to be halfword aligned */
if (((q+2) >> (2+CODEVECSEGBITS)) >= codeveccnt)
{ if (codeveccnt >= CODEVECSEGMAX) syserr(syserr_codevec);
#ifndef NO_ASSEMBLER_OUTPUT
/* Only set up codeasmauxvec to store aux items if asmstream is active. */
codeasmauxvec[codeveccnt] = (VoidStar (*)[CODEVECSEGSIZE]) (
asmstream ? BindAlloc(sizeof(*codeasmauxvec[0])) : DUFF_ADDR);
#endif
codeandflagvec[codeveccnt] =
(struct CodeAndFlag *) BindAlloc(sizeof(*codeandflagvec[0]));
#ifdef TARGET_HAS_HALFWORD_INSTRUCTIONS
/* ECN: If we have halfword instructions a codeandflagvec object may contain
* either a word (represented as two halfwords with a single flag) or
* a halfword. If it is a word we must ensure that the flag for the
* second halfword contains 0.
*/
memset(codeandflagvec[codeveccnt], 0, sizeof(*codeandflagvec[0]));
#endif
codeveccnt++;
}
set_code_inst_(q,w);
code_flag_(q) = (CodeFlag_t)f;
#ifndef NO_ASSEMBLER_OUTPUT
if (asmstream) code_aux_(q) = aux;
#endif
codep += 4;
#else
IGNORE(f); IGNORE(w); IGNORE(aux);
#endif
}
int32 codeloc(void)
{
/* for the use of vargen.c: but consider rationalisation later */
return codebase + codep + litpoolp*4;
}
int32 lit_findadcon(Symstr *name, int32 offset, int32 wherefrom)
/* looks for a previous adcon literal from wherefrom to codebase+codep */
/* returns a byte address from wherefrom to codebase+codep or -1 */
{ CodeXref *x;
for (x = codexrefs; x!=NULL; x = x->codexrcdr)
{ if (x->codexrsym == name)
{ int32 k = x->codexroff;
/* See comments later in this file re x->codexrlitoff with X_backaddrlit */
if ((k & 0xff000000)==X_backaddrlit && x->codexrlitoff==offset)
{ /* adcon already in memory at byte address k */
k &= 0x00ffffff;
return (k >= wherefrom ? k : -1);
}
}
}
return -1;
}
static char *count_name_table[16];
static int count_name_pointer;
int lit_of_count_name(char *s)
{
/* This records an index number for each of the most recent few source */
/* files used in the current compilation. These numbers are used with */
/* the count option as enabled by the -K command-line option. */
int i;
for (i = 0; i < count_name_pointer; i++)
if (strcmp(s, count_name_table[i]) == 0) return i;
i = count_name_pointer++;
/* The next line duplicates ACN's functionality, should be OK as J_COUNT */
/* should always be incode (arg to dumplits2()). */
if (i >= 16) dumplits2(YES), i = count_name_pointer++;
count_name_table[i] = s;
return i;
}
void dump_count_names(void)
{
int i;
if (count_name_pointer == 0) return;
outcodeword(0xfff12340 | (count_name_pointer - 1L), LIT_NUMBER);
for (i = 0; i<count_name_pointer; i++)
{ char *file_name = count_name_table[i];
StringSegList x;
x.strsegbase = file_name;
x.strseglen = strlen(file_name);
x.strsegcdr = NULL;
codeseg_stringsegs(&x, NO);
}
outcodeword(0x31415926, LIT_NUMBER);
count_name_pointer = 0;
}
typedef struct LitPool {
struct LitPool *next;
int32 base; /* absolute address in code segment of pool base */
int32 size; /* size of pool (words) */
LitPoolEntry entries[1]; /* really variable */
} LitPool;
#define poolbase_(p) (p)->base
#define poolsize_(p) (p)->size
#define poolentry_(p, i) (p)->entries[i]
static LitPool *prevpools;
static void dumplits_inner(void)
{
int32 i;
LitPool *q = (LitPool *) GlobAlloc(SU_Other, sizeof(LitPool) + (litpoolp-1)*sizeof(LitPoolEntry));
q->next = prevpools; prevpools = q;
poolbase_(q) = codebase + codep; poolsize_(q) = litpoolp;
for (i=0; i<litpoolp; i++)
{ LitPoolEntry *p = &litpool_(i);
int32 f = p->type;
poolentry_(q, i) = *p;
if (f == LIT_ADCON || f == LIT_FNCON)
/* Note that xref list entries of type X_backaddrlit have an extra word */
/* that indicates a numeric offset relative to the named symbol. This */
/* field should ONLY be relevant when scanning to see if an existing */
/* literal pool entry can be reused. For object file generation the */
/* relevant offset will appear in codevec. */
{ codexrefs = (CodeXref *) global_list4(SU_Xref, codexrefs,
X_backaddrlit | (codebase+codep),
p->xref,
p->val); /* codexrlitoff */
#ifdef TARGET_CALL_USES_DESCRIPTOR /*@@@ AM thinks useful for pcc too */
/* /* bugs here ? */
if (f == LIT_FNCON)
(void)obj_symref(p->xref, xr_code, 0);
else
#endif
(void)obj_symref(p->xref, xr_data, 0);
}
#if defined(TARGET_IS_ARM) || defined(TARGET_IS_THUMB)
if (f != LIT_STRING) {
outcodewordaux(p->val, f, p->litaux);
} else {
int32 j;
char b[8];
#define word_has_nullbyte(w) (((w) - 0x01010101) & ~(w) & 0x80808080)
j = i;
while (j<litpoolp) {
p = &litpool_(j);
j++;
if (p->type != LIT_STRING || word_has_nullbyte(p->val))
break;
}
sprintf(b, "$S%ld", (j-i)*4);
obj_symdef(sym_insert_id(b), xr_code+xr_defloc+xr_dataincode, codebase+codep);
while (i<litpoolp) {
p = &litpool_(i);
poolentry_(q, i) = *p;
outcodewordaux(p->val, p->type, p->litaux);
i++;
if (p->type != LIT_STRING || word_has_nullbyte(p->val))
break;
}
i--;
}
#else
/* transfer relocation info (if any) to the planted literal */
outcodewordaux(p->val, f, p->litaux);
#endif
}
litpoolp = 0;
localcg_newliteralpool();
if (count_name_pointer >= 15)
dump_count_names(); /* else will overflow next time anyway */
}
static void dumplits0(void)
{
#ifdef TARGET_HAS_HALFWORD_INSTRUCTIONS
if ((codebase+codep) & 2) {
if ((codep & 2) == 0) {
outcodeword(0, LIT_OPCODE);
codep -= 4; /* ensure room */
code_flag_(codep+2) = LIT_OPCODE;
}
code_hword_(codep) = 0;
codep += 2;
}
#endif
/* ECN: Change | to + as codebase need not be aligned */
if ((codebase+codep) & 3) syserr(syserr_dumplits);
while (codebase+codep & litalign-1) outcodeword(0, LIT_NUMBER);
setlabel(litlab);
dumplits_inner();
litlab = nextlabel();
}
void dumplits2(bool needsjump)
{ if (needsjump)
{ LabelNumber *ll = nextlabel();
if (litlab->u.frefs == NULL) syserr(syserr_dumplits1);
localcg_newliteralpool();
branch_round_literals(ll);
/* That probably evaluated a J_B (AL) jopcode, which caused literals
* to be dumped, so now there are none left - but the interface isn't
* defined, so for safety we must check.
*/
if (litpoolp != 0) dumplits0();
setlabel(ll);
}
else
{
if (litlab->u.frefs == NULL)
{ if (litpoolp != 0) syserr(syserr_dumplits2);
}
else {
localcg_newliteralpool();
dumplits0();
}
}
}
static LabelNumber *litoverflowlab;
static int32 litsincode;
/* All words between LITF_FIRST and LITF_LAST are guaranteed contiguous */
void outlitword(int32 w, int32 flavour, Symstr *sym, VoidStar aux,
int32 flag)
{ if (!codebuf_inroutine)
{ /* /* Find 'codexrefs' above to see what should have been done. */
if (flavour == LIT_ADCON) syserr(syserr_outlitword);
outcodewordaux(w, flavour, aux);
return;
}
if (flag & LITF_DOUBLE)
{ litalign = alignof_double; /* IEEE 16byte long double soon? */
while ((litpoolp<<2) & litalign-1)
outlitword(0, LIT_NUMBER, 0, (VoidStar)0,
(flag&LITF_INCODE)|LITF_FIRST|LITF_LAST);
}
if (flag & LITF_FIRST)
litoverflowlab = 0, litsincode = flag & LITF_INCODE;
if ((litpoolp >> LITPOOLSEGBITS) >= litveccnt)
{ if (litveccnt < LITPOOLSEGMAX)
litpool[litveccnt++] = (LitPoolEntry (*)[LITPOOLSEGSIZE])
BindAlloc(sizeof(*litpool[0]));
else
{ localcg_newliteralpool();
if (litsincode)
{ branch_round_literals(litoverflowlab = nextlabel());
/* LDS observes that branch_round_literals() generates an unconditional */
/* branch which flushes the literal pool (currently on the ARM). */
/* On such a target the next test never succeeds. */
/* AM: this is true on the ARM, but note that some targets save all */
/* their literals to J_ENDPROC (i.e. J_B does not flush) but lots of */
/* J_STRING opcodes may force a LITPOOLSEGMAX overflow and hence this */
/* code to be activated. See comment in dumplits2(). */
if (litpoolp != 0)
{
if (litlab->u.frefs == NULL) syserr(syserr_dumplits3);
dumplits0();
}
litsincode = 0;
}
else dumplits_inner();
}
}
{ LitPoolEntry *p = &litpool_(litpoolp);
p->val = w, p->type = flavour, p->xref = sym, p->litaux = aux;
litpoolp++;
}
if (flag & LITF_LAST)
{ if (!litsincode) dumplits_inner(); /* if overflow then flush all */
if (litoverflowlab) setlabel(litoverflowlab);
}
}
static int32 lit_findword5(int32 w, int32 flavour, Symstr *sym,
VoidStar aux, int32 flag)
{ /* try to re-use literal in current pool */
int32 i;
if ((flag & LITF_FIRST+LITF_LAST+LITF_NEW) == LITF_FIRST+LITF_LAST)
/* only re-use one word, non-NEW, literals so far */
for (i=0; i<litpoolp; i++)
{ LitPoolEntry *p = &litpool_(i);
if (p->type == flavour && p->val == w && p->xref == sym)
{ /* adcon (or other lit) available in current literal pool */
/* if previous ref was addressable this one will be. */
if (p->litaux == 0) p->litaux = aux; /* best asm. */
return 4*i;
}
}
if (flag & LITF_PEEK) return -1; /* just window shopping */
outlitword(w, flavour, sym, aux, flag);
return 4*litpoolp-4; /* beware using this for multiword literals */
}
/* lit_findword (and lit_findwordaux) is now the approved route for gen.c */
/* It returns a BYTE offset into the current literal table */
int32 lit_findword(int32 w, int32 flavour, Symstr *sym, int32 flag)
{ return lit_findword5(w, flavour, sym, (VoidStar)0, flag);
}
int32 lit_findwordaux(int32 w, int32 flavour, VoidStar aux, int32 flag)
{ return lit_findword5(w, flavour, 0, aux, flag);
}
int32 lit_findwordsincurpool(int32 w[], int32 count, int32 flavour)
{ /* look for literal in current pool. Must be the same sort of thing,
to avoid worries about byte sex change. Floats and doubles are
similarly separate. Double word order has already been arranged
in target order by struct DbleBin in mip/defs.h.
Returns (byte) offset of literal in the pool if found, -1 otherwise.
Does NOT carry litaux info for asm printing.
Never refers to ADCONs hence xref==NULL test below.
*/
int32 i, j;
for (i=0; i<litpoolp; i++) {
for (j = 0 ; (i+j) < litpoolp ; j++) {
LitPoolEntry *p = &litpool_(i+j);
int32 f = ((flavour==LIT_FPNUM && count==2)
? (j==0 ? LIT_FPNUM1 : LIT_FPNUM2) :
(flavour == LIT_INT64_1 && count == 2 && j == 1)
? LIT_INT64_2 :
flavour);
if (!(p->type == f && p->val == w[j] && p->xref == NULL))
break;
if (j == count-1)
{ /* adcon available in current literal pool */
/* if previous ref was addressable this one will be */
/* set litaux a la lit_findword5()? */
return 4*i;
}
}
}
return -1; /* Not there - will be inserted by calls of findword */
}
int32 lit_findwordsinprevpools(int32 w[], int32 count, int32 flavour,
int32 earliest)
{ /* Look for literal in any previous pool in the SAME function.
Must be the same sort of thing, to avoid worries about byte sex change.
Must be at a codesegment address greater than or equal to earliest.
Returns (absolute) address of literal if found, -1 otherwise.
Does NOT carry litaux info for asm printing.
Never refers to ADCONs hence xref==NULL test below.
*/
LitPool *q;
for (q = prevpools ; q != NULL ; q = q->next) {
int32 i = (earliest - poolbase_(q))/4;
int32 size = poolsize_(q);
if (i >= size) break;
if (i < 0) i = 0;
for (; i < size ; i++) {
int32 j;
for (j = 0 ; (i+j) < size ; j++) {
LitPoolEntry *p = &poolentry_(q, i+j);
int32 f = ((flavour==LIT_FPNUM && count==2)
? (j==0 ? LIT_FPNUM1 : LIT_FPNUM2) :
(flavour == LIT_INT64_1 && count == 2 && j == 1)
? LIT_INT64_2 :
flavour);
if (!(p->type == f && p->val == w[j] && p->xref == NULL))
break;
if (j == count-1) return poolbase_(q)+4*i;
/* set litaux a la lit_findword5()? */
}
}
}
return -1;
}
static int32 nextstringword(StringSegList **s, int32 *ip, int32 *np)
{
StringSegList *x = *s;
int32 i = *ip;
int32 n = 0;
union { char c[4]; int32 i; } w;
for (w.i = 0; x != NULL; x = x->strsegcdr, i = 0)
{ char *p = x->strsegbase;
int32 len = x->strseglen;
for (; i < len; i++) {
w.c[n] = p[i];
++n;
if (n >= 4) {
if (++i == len && x->strsegcdr != NULL) {
*s = x->strsegcdr; *ip = 0;
} else {
*s = x; *ip = i;
}
return w.i;
}
}
}
*s = NULL; *ip = 0; *np = n;
return w.i;
}
int32 lit_findstringincurpool(StringSegList *s)
{ /* look for literal string in current pool.
Returns (byte) offset of literal in the pool if found, -1 otherwise.
*/
int32 i;
int32 n = 0;
int32 dummy;
int32 w = nextstringword(&s, &n, &dummy);
for (i = 0; i < litpoolp; i++) {
int32 j = i;
StringSegList *s1 = s;
int32 n1 = n;
int32 w1 = w;
for ( ; j < litpoolp ; j++) {
LitPoolEntry *p = &litpool_(j);
if (p->type != LIT_STRING || p->val != w1) break;
if (s1 == NULL) return 4*i;
w1 = nextstringword(&s1, &n1, &dummy);
}
}
return -1; /* Not there - will be inserted by calls of findword */
}
int32 lit_findstringinprevpools(StringSegList *s, int32 earliest)
{ /* Look for literal in any previous pool in the SAME function.
Must be the same sort of thing, to avoid worries about byte sex change.
Must be at a codesegment address greater than or equal to earliest.
Returns (absolute) address of literal if found, -1 otherwise.
*/
LitPool *q;
int32 n = 0;
int32 dummy;
int32 w = nextstringword(&s, &n, &dummy);
for (q = prevpools ; q != NULL ; q = q->next) {
int32 i = (earliest - poolbase_(q))/4;
int32 size = poolsize_(q);
if (i >= size) break;
if (i < 0) i = 0;
for (; i < size; i++) {
int32 j = i;
StringSegList *s1 = s;
int32 n1 = n;
int32 w1 = w;
for ( ; j < size; j++) {
LitPoolEntry *p = &poolentry_(q, j);
if (p->type != LIT_STRING || p->val != w1) break;
if (s1 == NULL) return poolbase_(q)+4*i;
w1 = nextstringword(&s1, &n1, &dummy);
}
}
}
return -1;
}
/* codeseg_stringsegs is exported to vargen.c and xxxgen.c */
void codeseg_stringsegs(StringSegList *x, bool incode)
{
int32 i = 0;
int32 litf = incode ? LITF_INCODE+LITF_FIRST : LITF_FIRST;
for ( ; ; ) {
int32 n;
int32 w = nextstringword(&x, &i, &n);
#define lit_strnbytes(n) LIT_STRING
if (x == NULL) {
outlitword(w, lit_strnbytes(n), 0, 0, litf | LITF_LAST);
return;
}
outlitword(w, lit_strnbytes(3), 0, 0, litf);
litf &= ~LITF_FIRST;
}
}
void codeseg_flush(Symstr *strlitname)
{ /* strlitname will usually be 0, but putting a symbol here enables */
/* re-assemblable code on machines whose assemblers change lengths. */
if (strlitname) show_entry(strlitname, xr_code+xr_defloc);
dumplits_inner();
show_code(strlitname);
}
/* the following routine is related to these */
/* One day the nargwords argument may be sensibly the function type info */
int32 codeseg_function_name(Symstr *name, int32 nargwords)
{ int32 result = codebase;
char *sname = symname_(name);
union { char c[4]; int32 i; } w;
int32 p, length;
for (p = w.i = length = 0; *sname;)
{ w.c[p] = *sname++;
++p;
if (p == 4)
{ outcodeword(w.i, LIT_STRING);
p = w.i = 0;
length += 4;
}
}
outcodeword(w.i, LIT_STRING);
#ifndef FORBS_CALL_STANDARD
/*
* This word is intended to let backtrace code (etc) find the string that
* names the current function even though it knows where the string ends
* but not (save for this length word) where it starts.
*/
outcodeword(0xff000000 | (length + 4), LIT_NUMBER);
#endif
show_code(NULL);
IGNORE(nargwords);
return result;
}
int32 stringlength(StringSegList *s)
{ int32 n = 0;
for ( ; s != NULL ; s = s->strsegcdr) n += s->strseglen;
return n;
}
#ifdef TARGET_HAS_BSS
int32 bss_size;
void padbss(int32 align)
{
if (bss_size & (align-1)) bss_size += (-bss_size) & (align-1);
}
static void endbssobject(int32 size)
{
bss_size += size;
padbss(alignof_toplevel_static);
}
int32 addbsssym(Symstr *sym, int32 size, int32 align, bool statik, bool local)
{
if (local) {
int32 offset;
if (bss_size == 0)
obj_symref(bindsym_(bsssegment), xr_bss+xr_defloc, 0);
obj_symref(sym, xr_bss+(statik ? xr_defloc : xr_defext), bss_size);
padbss(align);
offset = bss_size;
endbssobject(size);
return offset;
} else {
padbss(align);
obj_symref(sym, xr_bss+(statik ? xr_defloc : xr_defext), bss_size);
endbssobject(size);
return BINDADDR_UNSET;
}
}
#endif
/* This has to be called before the front-end so that initialised */
/* statics (e.g. pointers to strings) can be put in the code segment. */
void codebuf_reinit1(char *codeseg_label)
{
codebuf_inroutine = NO;
codeveccnt = codep = 0; /* for static inits */
litveccnt = litpoolp = 0;
asm_lablist = NULL;
litlab = (LabelNumber *) DUFF_ADDR;
litalign = 4;
#ifdef TARGET_HAS_MULTIPLE_CODE_AREAS
if (codeseg_label != NULL)
{ Symstr * sv;
localcg_endcode();
sv = bindsym_(codesegment) = sym_insert_id(codeseg_label);
#ifndef NO_OBJECT_OUTPUT
if (objstream) obj_codewrite(NULL);
#endif /* beware reinit, in effect */
#ifndef NO_ASSEMBLER_OUTPUT
if (asmstream) display_assembly_code(NULL);
#endif /* beware reinit, in effect */
obj_symref(sv, xr_code+xr_defloc+xr_dataincode, 0L);
prevpools = NULL;
codebase = 0;
codexrefs = NULL;
}
#endif
}
/* This has to be called before the front-end so that initialised */
/* statics (e.g. pointers to strings) can be put in the code segment. */
void codebuf_reinit(void)
{
codebuf_inroutine = NO;
codeveccnt = codep = 0; /* for static inits */
litveccnt = litpoolp = 0;
asm_lablist = NULL;
litlab = (LabelNumber *) DUFF_ADDR;
litalign = 4;
#ifdef TARGET_HAS_MULTIPLE_CODE_AREAS
if (codebase > 0 &&
((feature & FEATURE_AOF_AREA_PER_FN) ||
(var_aof_code_area > code_area_idx)))
#ifdef PUT_FILE_NAME_IN_AREA_NAME
{ int32 n = var_aof_code_area;
char filename[256];
char name[256];
UnparsedName un;
fname_parse(sourcefile, FNAME_INCLUDE_SUFFIXES, &un);
memcpy(filename, un.root, un.rlen);
filename[un.rlen] = 0;
if (n < code_area_idx) n = code_area_idx;
++code_area_idx;
sprintf(name, "x$c_%s_%lu", filename, n);
codebuf_reinit1(name);
}
#else
{ int32 n = var_aof_code_area;
char name[32];
if (n < code_area_idx) n = code_area_idx;
++code_area_idx;
sprintf(name, "x$code_%lu", n);
codebuf_reinit1(name);
}
#endif
else
#endif
codebuf_reinit1(NULL);
}
void codebuf_reinit2(void)
{ codebuf_inroutine = YES;
codeveccnt = codep = 0; /* for static inits */
litveccnt = litpoolp = 0;
next_label_name = 1;
asm_lablist = NULL;
litlab = nextlabel();
}
void codebuf_init(void)
{
data.head = NULL; data.tail = NULL;
data.size = 0; data.xrefs = NULL; data.xrarea = xr_data;
data.wpos = 0, data.wtype = 0, data.wbuff.w32[0] = 0;
extable.head = NULL; extable.size = 0;
extable.xrefs = NULL; extable.xrarea = xr_constdata;
extable.wpos = 0; extable.wtype = 0; extable.wbuff.w32[0] = 0;
exhandler.head = NULL; exhandler.size = 0;
exhandler.xrefs = NULL; exhandler.xrarea = xr_constdata;
exhandler.wpos = 0; exhandler.wtype = 0; exhandler.wbuff.w32[0] = 0;
#ifdef CONST_DATA_IN_CODE
constdata.head = NULL; constdata.size = 0;
constdata.xrefs = NULL; constdata.xrarea = xr_constdata;
constdata.wpos = 0; constdata.wtype = 0; constdata.wbuff.w32[0] = 0;
#endif
datap = &data;
#ifdef TARGET_CALL_USES_DESCRIPTOR
fnconlab = 0; /* WGD 27-3-88 */
#endif
#ifdef TARGET_HAS_BSS
bss_size = 0;
#endif
codebase = 0;
maxprocsize = 0, maxprocname = "<none>";
codebuf_reinit(); /* in case mcdep_init() is wild */
count_name_pointer = 0;
prevpools = NULL;
code_area_idx = 1;
currentExceptionEnv = 0;
}
void codebuf_tidy(void)
{
if (debugging(DEBUG_STORE)) {
cc_msg( "Code/data generated (%ld,%ld) bytes\n",
(long)codeloc(), (long)data.size);
cc_msg( "Max procedure (%s) size %ld bytes\n",
maxprocname, (long)maxprocsize);
}
}
/* end of codebuf.c */
|
stardot/ncc | cfe/feerrs.h | <filename>cfe/feerrs.h
/*
* cfe/feerrs.h - prototype for front-end error messages file
* 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
* version 3b.
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
#ifndef NLS /* if NLS, miperrs will have included tags */
%O /* Ordinary error messages - mapped onto numeric codes */
/* Preprocessor messages are in miperrs.h */
#define lex_warn_force_unsigned "'%s' treated as '%sul' in 32-bit implementation"
#define lex_warn_force_longlong "'%s' treated as '%sll'"
#define lex_warn_force_ulonglong "'%s' treated as '%sull'"
#define lex_warn_multi_char "non-portable - not 1 char in '...'"
#define lex_warn_cplusplusid "C++ keyword used as identifier: $r"
#define lex_warn_cplusplusimpl \
"Functionality of C++ keyword may not yet be fully implemented: $r"
#define syn_warn_hashif_undef "Undefined macro '%s' in #if - treated as 0"
#define syn_warn_invent_extern "inventing 'extern int %s();'"
#define syn_warn_unary_plus "Unary '+' is a feature of ANSI C"
#define syn_warn_spurious_braces "spurious {} around scalar initialiser"
#define syn_warn_dangling_else "Dangling 'else' indicates possible error"
#define syn_warn_void_return "non-value return in non-void function"
#define syn_warn_use_of_short \
"'short' slower than 'int' on this machine (see manual)"
#define syn_warn_undeclared_parm \
"formal parameter $r not declared - 'int' assumed"
#define syn_warn_old_style "Old-style function $r"
#define syn_warn_give_args "Deprecated declaration %s() - give arg types"
#define syn_warn_ANSI_decl "ANSI style function declaration used, '%s(...)'"
#define syn_warn_archaic_init "Ancient form of initialisation, use '='"
#define syn_warn_untyped_fn "implicit 'int' return type for $r - 'void' intended?"
#define syn_warn_no_named_member "$c has no named member"
#define syn_warn_extra_comma "Superfluous ',' in 'enum' declaration"
#define syn_warn_struct_padded "padding inserted in struct $b"
#define syn_warn_switch_funny "'switch (e)' not followed by '{'"
#define syn_warn_modify_access "access declaration with no effect"
#define syn_warn_storageclass_no_declarator \
"storage-class without declarator is spurious"
#define syn_warn_lacks_storage_type \
"declaration lacks type/storage-class (assuming 'int'): $r"
#define syn_warn_archaic_fnpara "archaic C-style function parameter $l"
#define syn_warn_special_ops "'=', ',' or unary '&' defined as non-member"
#define syn_warn_ineffective_asm_decl "asm(...) ignored: inline assembler not available"
#define syn_warn_insert_sym_anachronism "inserting $r in ':(...)' anachronism"
#define syn_warn_superfluous_prefix \
"superfluous 'union','class', 'struct' or 'enum' prefix"
#define syn_warn_no_default_structor "$b: $c has no default %s"
#define xsyn_info_instantiate_class \
"while instantiating $c"
#define xsyn_info_instantiate_fn \
"while instantiating function $p$r"
#define xsyn_warn_ARM_cctor_suppress \
"$b suppresses default copy constructor under ARM semantics"
#define xsyn_warn_ISO_cctor_no_suppress \
"$b does not suppress default copy constructor under ISO semantics"
#define xsyn_warn_ARM_opeq_suppress \
"$b suppresses default operator= under ARM semantics"
#define xsyn_warn_ISO_opeq_no_suppress \
"$b does not suppress default operator= under ISO semantics"
#define xsyn_warn_delete_undef \
"delete of pointer to undefined $c; no destructor will be called"
#define xsyn_warn_implicit_private_base "base class $c is implicitly private"
#define simp_warn_checkvar "syserr soon: checkvar use %ld"
#define vargen_warn_nonull "omitting trailing '\\0' for %s [%ld]"
#define vargen_warn_unnamed_bitfield \
"Unnamed bit field initialised to 0"
#define vargen_warn_init_non_aggregate \
"Attempt to initialise non-aggregate"
#define lex_err_ioverflow "Number %s too large for 32-bit implementation"
#define lex_err_ioverflow_64 "Number %s too large for 64-bit implementation"
#define lex_err_overlong_fp "Grossly over-long floating point number"
#define lex_err_fp_syntax1 "Digit required after exponent marker"
#define lex_err_overlong_hex "Grossly over-long hexadecimal constant"
#define lex_err_overlong_int "Grossly over-long number"
#define lex_err_need_hex_dig "Hex digit needed after 0x or 0X"
#define lex_err_need_hex_dig1 "Missing hex digit(s) after \\x"
#define lex_err_backslash_blank \
"\\<space> and \\<tab> are invalid string escapes"
#define lex_err_unterminated_string "Newline or end of file within string"
#define lex_err_bad_hash "misplaced preprocessor character '%c'"
#define lex_err_bad_char "illegal character (0x%lx = \'%c\') in source"
#define lex_err_bad_noprint_char "illegal character (hex code 0x%x) in source"
#define lex_err_ellipsis "(...) must have exactly 3 dots"
#define lex_err_illegal_whitespace "$s may not have whitespace in it"
#define syn_err_illdtor "illegal destructor '~$#l'"
#define syn_err_bitsize "bit size %ld illegal - 1 assumed"
#define syn_err_zerobitsize "zero width named bit field - 1 assumed"
#define syn_err_arraysize "Array size %ld illegal - 1 assumed"
#define syn_err_expected "expected $s - inserted before $l"
#define syn_err_expected1 "expected $s - inserted before $l"
#define syn_err_expected1_aftercommand "expected $s after command - inserted before $l"
#define syn_err_expected2 "expected $s or $s - inserted $s before $l"
#define syn_err_expecteda "expected $s"
#define syn_err_expected1a "expected $s"
#define syn_err_expected1a_aftercommand "expected $s after command"
#define syn_err_expected2a "expected $s or $s"
#define syn_err_mix_strings "char and wide (L\"...\") strings do not concatenate"
#define syn_err_expected_expr "<expression> expected but found $l"
#ifdef EXTENSION_VALOF
#define syn_err_valof_block \
"{ following a cast will be treated as VALOF block"
#endif
#define syn_err_typedef "typedef name $r used in expression context"
#define syn_err_assertion "___assert(0, $e)"
#define syn_err_expected_member "Expected <member> but found $l"
#define syn_err_hashif_eof "EOF not newline after #if ..."
#define syn_err_hashif_junk "Junk after #if <expression>"
#define syn_err_initialisers "too many initialisers in {} for aggregate"
#define syn_err_initialisers1 "{} must have 1 element to initialise scalar"
#define syn_rerr_empty_init "Initialiser list must contain at least one expression"
#define syn_err_default "'default' not in switch - ignored"
#define syn_err_default1 "duplicate 'default' case ignored"
#define syn_err_case "'case' not in switch - ignored"
#define syn_err_case1 "duplicated case constant: %ld"
#define syn_err_expected_cmd "<command> expected but found $l"
#define syn_err_expected_stmt "<statement> expected but found $l"
#define syn_err_expected_while "'while' expected after 'do' but found $l"
#define syn_err_else "Misplaced 'else' ignored"
#define syn_err_continue "'continue' not in loop - ignored"
#define syn_err_break "'break' not in loop or switch - ignored"
#define syn_err_no_label "'goto' not followed by label - ignored"
#define syn_err_no_brace "'{' of function body expected - found $l"
#define syn_err_stgclass \
"storage class $s not permitted in context %s - ignored"
#define syn_err_stgclass1 "storage class $s incompatible with $g - ignored"
#define syn_err_typeclash "type $s inconsistent with $m"
#define syn_err_tag_brace \
"'{' or <identifier> expected after $s but found $l"
#define syn_err_expected3 "Expecting <declarator> or <type> but found $l"
#define syn_err_unneeded_id \
"superfluous $l in <abstract declarator> - ignored"
#define syn_err_undef_struct_member(_b,_s) \
"undefined $c member: $r", _b, _s
#define syn_err_undef_struct_object(_b,_s) \
"undefined $c object: $r", _b, _s
#define syn_err_selfdef_struct_member(_b,_s) \
"attempt to include $c member: $r within itself", _b, _s
#define syn_err_selfdef_struct_object(_b,_s) \
"attempt to include $c object: $r within itself", _b, _s
#define syn_err_void_object_member(_s) "illegal 'void' member: $r", _s
#define syn_err_void_object_object(_s) "illegal 'void' object: $r", _s
#define syn_err_duplicate_type \
"duplicate type specification of formal parameter $r"
#define syn_err_not_a_formal "Non-formal $r in parameter-type-specifier"
#define syn_err_cant_init "$g names may not be initialised"
#define syn_err_enumdef \
"<identifier> expected but found $l in 'enum' definition"
#define syn_err_undef_enum "Undefined enum $r"
#define syn_err_misplaced_brace "Misplaced '{' at top level - ignoring block"
#define syn_err_not_friend "not a friend class $r"
#define syn_err_undef_basetag "undefined base: $c"
#define syn_err_missing_basetag "missing base tag: $l"
#define syn_err_incomp_arg_ovld "Incompatible arguments to $b (overload missing?)"
#define syn_err_no_operator_ovld "No operator $s with this type signature"
#define syn_err_multi_overload_call "ambiguous %d-way overload for call to $b"
#define syn_err_multi_operator_ovld "ambiguous %d-way overload for operator $s"
#define syn_err_multi_convfn_ovld \
"ambiguous %d-way choice of conversion from $c to $t"
#define syn_err_multi_ctor_ovld \
"ambiguous %d-way choice of constructor from $t to $c"
#define syn_err_ambiguous_user_defined_conv \
"ambiguous implicit user-defined conversion from $c to $c"
#define syn_err_illegal_asm_decl "illegal asm(...) declaration (ignored)"
#define syn_err_recursive_app_operator_arrow \
"recursive application of operator->() to object of type $c; return type intended?"
#define sem_err_assign_ovld \
"no suitable operator=() for $c: overload missing?"
#define sem_warn_virtual "virtual function call of $b"
#define sem_warn_addr_of_memfn "address of member function $b"
#define xsem_warn_cast_undef_struct \
"cast from ptr/ref to $c to ptr/ref to $c; one is undefined, assuming unrelated"
#define xsem_warn_unreachable_handler "handler is unreachable"
#define syn_err_constructor_init "constructor forbids $r = {...} initialiser"
#define syn_err_no_named_member "$c has no $r member"
#define syn_err_not_found_named_member "member $r not found in $c"
#define syn_err_missing_named_mfn "Missing class member function name"
#define syn_err_classname_not_found "class-name $r not found"
#define syn_err_member_cannot_init "member cannot be initialised: $r"
#define syn_err_lacks_bclass_anachronism "$c lacks base class for ':(...)' anachronism"
#define syn_err_not_member "$l is not a member of struct/class $b"
#define syn_err_try_catch "'try-catch' unimplemented"
#define syn_err_catch_ignored "misplaced 'catch' ignored"
#define syn_err_illegal_simple_types "illegal <simple type>: $m"
#define syn_err_no_member_here "class member $b cannot be defined here"
#define syn_err_template_not_impl "'template' not implemented"
#define syn_err_friend_type "'friend <type>;' needs elaborated-type-specifier"
#define syn_err_linkage_spec "expected <linkage-spec> '}' before $l"
#define syn_err_illegal_operator "'operator $s' is illegal"
#define syn_err_wrong_args_ovld "wrong number of arguments to overload $b"
#define syn_err_cannot_follow_unary_dcolon "$l cannot follow unary '::'"
#define syn_err_cannot_follow_binary_dcolon "$l cannot follow binary '::'"
#define syn_err_expected_dtor_name "expected destructor name after ::~, found $l"
#define syn_err_missing_tlevel_decl "missing top-level declaration: $r"
#define syn_err_no_decl_at_type "no $b declaration at this type"
#define syn_err_lacks_arg_ctor "$t lacks an %ld-argument constructor"
#define syn_err_no_nullary_ctor "no nullary constructor: $b"
#define syn_err_ignored_new_array_ctor "new <array> initialiser ignored"
#define syn_err_requires_pntr_arg "requires pointer argument: $s"
#define syn_err_duplicated_mem_init "duplicate member initialisation: $r"
#define syn_err_init_not_in_ctor "member initialiser not in constructor"
#define syn_err_expected_id_in_mem_init "expecting <identifier> in <member-initialiser>"
#define syn_err_missing_catch_after_try "omitted 'catch' after 'try'"
#define syn_err_ill_this "legal only in member function: $l"
#define syn_err_template_notclassorfunction "'template' not class nor function"
#define syn_err_template_scope "invalid $c scope"
#define syn_err_unspecialized_template "attempt to use template $b"
#define syn_err_asm_not_available "inline assembler not available in strict ANSI mode"
#define sem_err_temp_type_float "floating point type not allowed"
#define sem_err_addr_template "attempt to take address of template $b"
#define sem_err_typededuce_disagree "type deduction fails: $t disagrees with $t"
#define sem_warn_typededuce_arraysize "type deduction fails: array size differs"
#define sem_err_typededuce_ambiguous "type deduction fails: function type %d-way resolvable"
#define sem_err_typededuce_pointer "type deduction fails: $t incompatible to $t"
#define sem_err_typededuce_recognize "type deduction fails: un-recognizable type $t"
#define sem_err_typededuce_type "type deduction fails: free template type arg $r"
#define sem_err_typededuce_const "type deduction fails: free template non-type arg $r"
#define sem_err_typename_not_found "type deduction failed: typename $b not found\n"
#define sem_err_template_ambiguous "Ambiguous class/function templates"
#define sem_err_non_type_arg_linkage "extern linkage expected for template argument $b"
#define sem_err_non_type_arg_value "illegal non-type template arg $e"
#define sem_err_template_arg_linkage "template type arg $t must have extern linkage"
#define sem_err_call_dependency "call to $e not dependent on template args to $c"
#define sem_err_type_arg_expected "template type arg expected"
#define sem_err_typeclash_1 "type $m is inconsistent with $m"
#define sem_err_typeclash_2 "template type expected, found $e"
#define sem_err_typeclash_3 "template type inconsistent with $t"
#define sem_err_lvalue_needed "temporary required for template argument"
#define sem_err_dotdotdot_handler_not_last "handler for '...' must come last"
#define sem_rerr_template_formal_length_class \
"number of template formals for $c differs from a previous declaration"
#define sem_rerr_template_formal_length_function \
"number of template formals for $b differs from a previous declaration"
#define sem_rerr_template_formal_type "template formal type $t inconsistent with $t"
#define vargen_err_long_string "string initialiser longer than %s [%ld]"
#define vargen_err_nonstatic_addr \
"non-static address $b in pointer initialiser"
#define vargen_err_bad_ptr "$s: illegal use in pointer initialiser"
#define vargen_err_init_void "objects of type 'void' can not be initialised"
#define vargen_err_undefined_struct \
"$c must be defined for (static) variable declaration"
#define vargen_err_open_array "Uninitialised static [] arrays illegal"
#define vargen_err_overlarge_reg "invalid global register number"
#define vargen_err_not_int "invalid type for global int register"
#define vargen_err_not_float "invalid type for global float register"
#ifdef TARGET_CALL_USES_DESCRIPTOR
#define vargen_err_badinit "illegal initialisation to $r%+ld"
#endif
#ifdef TARGET_IS_HELIOS
#define vg_err_dynamicinit "Initialised dynamic array with -ZR or -ZL"
#endif
#define vargen_rerr_nonaligned \
"Non-aligned ADCON at data+0x%lx (value $r+0x%lx) set to NULL"
#define vargen_rerr_datadata_reloc \
"RISC OS (or other) reentrant module has static init. to data $r"
#define vargen_rerr_compiler_confused \
"compiler confused: static const with dynamic initialisation"
#define vargen_rerr_local_static_with_dtor \
"unimplemented: local static with destructor: $b"
#define lex_rerr_8_or_9 "digit 8 or 9 found in octal number"
#define lex_rerr_pp_number "number illegally followed by letter"
#define lex_rerr_hex_exponent "hex number cannot have exponent"
#define lex_rerr_esc16_truncated \
"overlarge escape '\\x%s%lx' treated as '\\x%lx'"
#define lex_rerr_esc8_truncated "overlarge escape '\\%o' treated as '\\%o'"
#define lex_rerr_illegal_esc "illegal string escape '\\%c' - treated as %c"
#define lex_rerr_not1wchar "L'...' needs exactly 1 wide character"
#define lex_rerr_empty_char "no chars in character constant ''"
#define lex_rerr_overlong_char "more than 4 chars in character constant"
#define syn_rerr_qualified_void "Return type may not be a void type other than 'void'"
#define syn_rerr_array_0 "array [0] found"
#ifdef EXTENSION_VALOF
#define syn_rerr_void_valof "void valof blocks are not permitted"
#endif
#define syn_rerr_undeclared "undeclared name, inventing 'extern int %s'"
#define syn_rerr_undeclared_fn "undeclared name, inventing 'extern \"C\" int %s(...);'"
#define syn_rerr_insert_parens \
"parentheses (..) inserted around expression following $s"
#define syn_rerr_return_expr_void "return <expr> illegal for void function"
#define syn_rerr_return_expr_ctor "return <expr> illegal for constructor"
#define syn_rerr_return_expr_dtor "return <expr> illegal for destructor"
#define syn_rerr_qualified_typedef(_b,_m) \
"$m typedef $b has $m re-specified", _m, _b, _m
#define syn_rerr_no_quals_allowed \
"only non-static member functions can be const or volatile"
#define syn_rerr_missing_type "missing type specification - 'int' assumed"
#define syn_rerr_missing_type_for "missing type specification for $r - 'int' assumed"
#define syn_rerr_long_float "ANSI C does not support 'long float'"
#define syn_rerr_missing_type1 \
"omitted <type> before formal declarator - 'int' assumed"
#define syn_rerr_missing_type2 \
"function prototype formal $r needs type or class - 'int' assumed"
#define syn_rerr_ellipsis_first "ellipsis (...) cannot be only parameter"
#define syn_rerr_mixed_formals "prototype and old-style parameters mixed"
#define syn_rerr_open_member "illegal [] member: $r"
#define syn_rerr_ref_void "illegal type (void &) treated as (int &)"
#define syn_rerr_ill_ref "$t of reference illegal -- '&' ignored"
#define syn_rerr_fn_returntype "function returning $t illegal -- assuming pointer"
#define syn_rerr_abst_class_rtype(_c)\
"function return abstract $c illegal", _c
#define syn_rerr_array_elttype "array of $t illegal -- assuming pointer"
#define syn_rerr_fn_ptr_member(_s) \
"member $r may not be function -- assuming pointer", _s
#define syn_rerr_fn_ptr_object(_s) \
"object $r may not be function -- assuming pointer", _s
#define syn_rerr_fn_ptr1 \
"function $r may not be initialised - assuming function pointer"
#define syn_rerr_archaic_init "Ancient form of initialisation, use '='"
#define syn_rerr_bitfield "illegal bit field type $t - 'int' assumed"
#define syn_rerr_ANSIbitfield "ANSI C forbids bit field type $t"
#define syn_rerr_missing_formal "formal name missing in function definition"
#define syn_rerr_ineffective "declaration with no effect"
#define syn_rerr_duplicate_member(b) "duplicate member $b", b
#define syn_rerr_duplicate_member2(cl, sv) "duplicate member $p$r", cl, sv
#define syn_rerr_semicolon_in_arglist \
"',' (not ';') separates formal parameters"
#define syn_rerr_no_members "$c has no members"
#define syn_rerr_not_base(mm,cc) "$b is not a base member of $c",mm,cc
#define syn_rerr_badly_placed_access \
"access declarations only in public and protected parts"
#define syn_rerr_modify_access "base access rights cannot be altered"
#define xsyn_rerr_bad_conv "illegal conversion $p$r"
#define xsyn_rerr_zero_params "$p$r must have zero parameters"
#define xsyn_rerr_non_memfn_operator "$p$r must be a non-static member function"
#define xsyn_rerr_no_return_type_allowed "no return type allowed for $p$r"
#define xsyn_rerr_must_be_function "$p$r must be a function"
#define syn_rerr_jump_past_init "jump past initialisation for $b"
#define syn_rerr_ambiguous_qualification "$r is ambiguously qualified"
#define syn_rerr_abstract_class_member(_b,_s) \
"abstract $c member: $r", _b, _s
#define syn_rerr_abstract_class_object(_b,_s) \
"abstract $c object: $r", _b, _s
#define syn_rerr_opaque_class_member(_b,_s) \
"opaque $c member: $r", _b, _s
#define syn_rerr_opaque_class_object(_b,_s) \
"opaque $c object: $r", _b, _s
#define syn_rerr_insert_braces "inserting { } around command after $s"
#define syn_rerr_not_decl_qual(tb,s) \
"Definition of $c not $s: qualifier ignored", tb, s
#define syn_rerr_ignored_non_fn "$g ignored for non-function $r"
#define syn_rerr_global_anon_union "global anonymous union must be static"
#define syn_rerr_defaults_ordering "defaulted parameter $r followed by non-defaulted"
#define syn_rerr_unknown_linkage "unknown linkage: extern $e"
#define syn_rerr_illegal_anon_union_mem "illegal anonymous union member $r"
#define syn_rerr_illegal_nonpub_anon_union_mem "illegal non-public anonymous union member $r"
#define syn_rerr_delete_expr_anachronism "'e' ignored in 'delete [e]' anachronism"
#define syn_rerr_self_copying_ctor "self-copying constructor for $c"
#define syn_rerr_duplicated_base "duplicate base $c ignored"
#define syn_rerr_no_arg_in_template "no arguments in template<>"
#define syn_rerr_superfluous_access_adjuster \
"superfluous type for access adjuster, declaration ignored"
#define syn_rerr_private_bmember_ignored "private overloaded base member ignored"
#define syn_rerr_local_default "$b has auto storage"
#define syn_rerr_declaree_out_of_scope "'$#b::$#r' cannot be declared here"
#define syn_rerr_friend_class_not_definable "friend $c shall not be defined"
#define syn_rerr_expect_dtor "expecting destructor for $c, found $r"
#define syn_rerr_union_w_base "unions may not have bases"
#define syn_rerr_meminit_wrong_args \
"too few/many arguments to initialiser for simple member $b"
#define syn_rerr_ref_not_initialised "reference $b must be initialised"
#define syn_rerr_const_not_initialised "constant $b must be initialised"
#define syn_rerr_addrof_cdtor_taken "can't take address of constructor or destructor"
#define syn_rerr_multi_convfn_bool \
"ambiguous %d-way choice of conversion from $c in Boolean context"
#define syn_rerr_tagdef_in_formals "cannot define within formals: $c"
#define syn_rerr_neg_unsigned_enum "$c cannot have both negative and unsigned enumerators"
#define xsyn_rerr_instantiate_mixup "instantiate don't mix with template or specialization"
#define xsyn_rerr_spurious_instantiate "too many instantiate request"
#define syn_rerr_extra_template_actuals "extra template actual(s) ignored"
/* Split for the NLS */
#define syn_moan_hashif_nonconst "illegal in #if <expression>: <unknown>"
#define syn_moan_hashif_nonconst1 \
"illegal in #if <expression>: non constant $b"
#define syn_moan_hashif_nonconst2 "illegal in #if <expression>: $s"
#define syn_moan_case_nonconst \
"illegal in case expression (ignored): <unknown>"
#define syn_moan_case_nonconst1 \
"illegal in case expression (ignored): non constant $b"
#define syn_moan_case_nonconst2 \
"illegal in case expression (ignored): $s"
%Z /* The following remain as ordinary (uncompressed) strings */
#define syn_moan_hashif "#if <expression>"
#define syn_moan_case "case expression (ignored)"
#define xsyn_constructor_string "constructor"
#define xsyn_copy_constructor_string "copy constructor"
#define xsyn_destructor_string "destructor"
#define xsyn_copy_assign_string "copy assignment"
#endif /* Under NLS these are not tags */
%S /* The next batch of things just get mapped onto syserr codes */
#define syserr_genpointer "genpointer&(%ld)"
#define syserr_initsubstatic "initsubstatic(bit)"
#define syserr_initstatic "initstatic(%ld,%#lx)"
#define syserr_initstatic1 "initstatic(%ld)"
#define syserr_rd_decl_init "rd_decl/init(%#lx)"
#define syserr_rd_typename "rd_typename()=0"
#define syserr_rdinit "syn_rdinit"
#define syserr_rd_declarator "rd_declarator(%ld)"
#define syserr_defaultstgclass "defaultstorageclass(%#x)"
#define syserr_rd_declrhslist "rd_declrhslist confused"
#define syserr_rd_decl2 "rd_decl2(%p,%ld)"
#define syserr_rd_strdecl "rd_strdecl"
#define syserr_lex_string "lex_string"
/* end of cfe/feerrs.h */
|
stardot/ncc | mip/store.c | <filename>mip/store.c
/*
* mip/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.
* 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 *malloc();
extern free();
#endif
#include "globals.h"
#include "store.h"
#include "defs.h"
#include "mcdep.h" /* usrdbg(xxx) */
#include "errors.h"
void ClearToNull(void **a, int32 n) {
while (--n >= 0) a[n] = NULL;
}
/* STORE_TRASHING and CHECKING_TRASH allow building a compiler that */
/* fills all allocations with trash, fills all disposed memory with */
/* trash and checks all allocations to make sure they still contain */
/* trash. @@@ These are yet complete. STORE_TRASHING works but does */
/* not trash memory lost when alloc_unmark and drop_local_store set */
/* {syn,bind}all{2,3} to NULL. Also discard2 & discard3 trash their */
/* blocks in a different way. */
/* CHECKING_TRASH does not work because of the above problems with */
/* STORE_TRASHING. */
/* WATCH_FOR adds code that watches in alloc_unmark and */
/* drop_local_store for blocks being freed that a static varible, */
/* watch_for points into. */
#ifndef WATCH_FOR
#define WATCH_FOR 0
#endif
#ifndef STORE_TRASHING
#define STORE_TRASHING 0
#endif
#ifndef CHECKING_TRASH
#define CHECKING_TRASH 0
#endif
typedef struct AllocHeader AllocHeader;
struct AllocHeader {
AllocHeader *next;
#if STORE_TRASHING
int32 size;
#endif
};
static AllocHeader *alloc_chain; /* see alloc_init(), alloc_dispose() */
static int32 stuse_total, stuse_waste;
static int32 stuse[SU_Other-SU_Data+1];
static int32 maxAEstore;
#if WATCH_FOR
static void* watch_for = 0; /* set from debugger; note: this isn't watched for by discard2, discard3 yet */
static void check_watch_for(const char* base, unsigned32 size, const char* kind)
{
if (watch_for != 0 && base <= (char*)watch_for &&
(char*)watch_for < (base + size))
syserr("Dropped %s containing %p\n", kind, watch_for);
}
#else
#define check_watch_for(b,s,k) ((void)0)
#endif
#if STORE_TRASHING
typedef struct Trasher Trasher;
struct Trasher { int32 a[8]; };
static const Trasher trash =
{ { 0x50ff8001, 0x50ff8001, 0x50ff8001, 0x50ff8001,
0x50ff8001, 0x50ff8001, 0x50ff8001, 0x50ff8001 } };
static void trash_block(VoidStar p, unsigned32 size) {
Trasher *t = (Trasher *)p;
while (sizeof(Trasher) < size)
{
*t++ = trash;
size -= sizeof(Trasher);
}
memcpy(t, &trash, size);
}
#if CHECKING_TRASH
static void check_trashed(VoidStar p, unsigned32 size) {
Trasher *t = (Trasher *)p;
check_watch_for(p, size, "trashed block");
while (sizeof(Trasher) < size)
{
if (memcmp(t++, trash, sizeof(Trasher)) != 0)
syserr("free memory has been altered somewhere between [%p and %p)\n",
t - 1, t);
size -= sizeof(Trasher);
}
if (memcmp(t, trash, size) != 0)
syserr("free memory has been altered somewhere between [%p and %p)\n",
t, (char*)t + size);
}
#else
#define check_trashed(p, size) ((void)0)
#endif
#else
#define trash_block(p, size) ((void)0)
#define check_trashed(p, size) ((void)0)
#endif
static VoidStar cc_alloc(int32 n)
{ AllocHeader *p;
stuse_total += n;
/* The next line's test probably only generates code on a PC. */
p = (sizeof(size_t) < sizeof(int32) &&
(unsigned32)(n+sizeof(AllocHeader)) > 0xffff) ? 0 :
(AllocHeader *)malloc((size_t)(n+sizeof(AllocHeader)));
if (p != 0)
{ p->next = alloc_chain;
#if STORE_TRASHING
p->size = n+sizeof(AllocHeader);
trash_block((VoidStar)((char*)p + sizeof(AllocHeader)), n);
#endif
alloc_chain = p;
return (char*)p + sizeof(AllocHeader);
}
#ifdef TARGET_IS_ARM
if (usrdbg(DBG_ANY))
cc_fatalerr(misc_fatalerr_space2);
else
#endif
cc_fatalerr(misc_fatalerr_space3);
return 0; /* stop compiler wingeing re implicit junk return */
}
void alloc_finalise(void)
{
unsigned32 count = 0;
if (debugging(DEBUG_STORE)) cc_msg("Freeing block(s) at:");
while (alloc_chain != NULL)
{ AllocHeader *next = alloc_chain->next;
if (debugging(DEBUG_STORE))
cc_msg("%s %p", count++ % 8 == 0 ? "\n":"", alloc_chain);
trash_block((VoidStar)alloc_chain, alloc_chain->size);
free(alloc_chain);
alloc_chain = next;
}
if (debugging(DEBUG_STORE)) cc_msg("\n");
}
struct Mark {
struct Mark *prev;
int syn_segno;
char *syn_allp; int32 syn_hwm;
int bind_segno;
char *bind_allp; int32 bind_hwm;
bool unmarked;
};
static Mark *marklist;
static Mark *freemarks;
typedef struct FreeList {
struct FreeList *next;
int32 rest[1];
} FreeList;
typedef struct OverlargeBlockHeader OverlargeBlockHeader;
struct OverlargeBlockHeader {
OverlargeBlockHeader *next;
int32 size;
};
static char *permallp, *permalltop;
static OverlargeBlockHeader *globoschain;
static char **globsegbase; /* list of blocks of 'per file' store */
static int32 *globsegsize;
static int globsegcnt; /* count of segments allocated (int ok) */
static int32 globallxtra; /* oversize global store allocated. */
static char *globallp; /* pointers into symbol table */
static char *globalltop; /* end of symbol table */
struct CurrentFnDetails currentfunction;
/* 'segmax' is the size of the notional arrays synsegbase[] etc. */
static int segmax;
#define SEGMAX_INIT 16
#define SEGMAX_FACTOR 4
/* AM: one day turn segbase/segptr into a struct. */
static char **synsegbase; /* array of blocks of 'per routine' store */
static char **synsegptr; /* array of corresponding free addresses */
static int synsegcnt; /* number thereof 0..segmax */
static char *synallp, *synalltop; /* allocators therein */
static int32 synallhwm, synallmax; /* high water */
static FreeList *synall2; /* and a dispose list */
static FreeList *synall3;
static char **bindsegbase; /* list of blocks of 'per routine' store */
static char **bindsegptr; /* list of corresponding free addresses */
static int bindsegcnt; /* number thereof 0..segmax */
static int bindsegcur; /* next block to use 0..segmax */
static char *bindallp, *bindalltop; /* allocators therein */
static int32 bindallhwm, bindallmax;/* high water */
static FreeList *bindall2; /* and a dispose list */
static FreeList *bindall3;
char *phasename;
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;
}
/* Volatile storage allocation for use within treatment of 1 function. */
/* The following functions avoid a fixed limit on the number of pages */
/* of local allocation without excessive store use. */
/* @@@ make this function more global soon (e.g. for ICODE &c) */
/* The argument sizes are in bytes and old is unexamined if oldsize=0. */
static VoidStar expand_array(VoidStar oldp, int32 oldsize, int32 newsize)
{ /* beware the next line if we ever record GlobAlloc's: */
VoidStar newp = PermAlloc(newsize);
if (oldsize != 0) memcpy(newp, oldp, (size_t)oldsize);
trash_block(oldp, oldsize);
return newp;
}
static void expand_segmax(int newsegmax)
{ int32 osize = (int32)segmax * sizeof(char *),
nsize = (int32)newsegmax * sizeof(char *);
globsegsize = (int32 *)expand_array((VoidStar)globsegsize, osize, nsize);
globsegbase = (char **)expand_array((VoidStar)globsegbase, osize, nsize);
synsegbase = (char **)expand_array((VoidStar)synsegbase, osize, nsize);
synsegptr = (char **)expand_array((VoidStar)synsegptr, osize, nsize);
bindsegbase = (char **)expand_array((VoidStar)bindsegbase, osize, nsize);
bindsegptr = (char **)expand_array((VoidStar)bindsegptr, osize, nsize);
segmax = newsegmax;
}
static char *new_perm_segment(void)
{
char *w;
/* I will recycle a segment that had been used for local space if there */
/* are any such available. */
if (bindsegcur < bindsegcnt)
{ w = bindsegbase[--bindsegcnt];
if (debugging(DEBUG_STORE))
cc_msg("Permanent store %d from binder size %ld at %p\n",
(int)globsegcnt, (long)SEGSIZE, w);
check_trashed((VoidStar)w, SEGSIZE);
}
else
{ w = (char *)cc_alloc(SEGSIZE);
if (debugging(DEBUG_STORE))
cc_msg("Permanent store alloc %d size %ld at %p (in $r)\n",
(int)globsegcnt, (long)SEGSIZE, w, currentfunction.symstr);
}
permallp = w, permalltop = w + SEGSIZE;
return w;
}
/*
* The value RR here is used when rounding store allocations up - it
* is intended to ensure that this code runs properly when hosted on machines
* where sizeof(char *) == 8. Put a pad_to_hosttype() macro in util.h?
*/
#define RR (sizeof(char *) - 1)
VoidStar PermAlloc(int32 n)
{ char *p = permallp;
n = (n + RR) & ~(int32)RR; /* n = pad_to_hosttype(n, IPtr) */
if (n > SEGSIZE) syserr(syserr_overlarge_store1, (long)n);
if (p+n > permalltop)
stuse_waste += permalltop-p,
p = new_perm_segment();
else
check_trashed(p, n);
permallp = p + n;
#ifndef ALLOC_DONT_CLEAR_MEMORY
memset(p, 0xbb, (size_t)n);
#endif
return p;
}
static char *new_global_segment(void)
{
char *w;
int32 size = SEGSIZE;
/* I will recycle a segment that had been used for local space if there */
/* are any such available. */
if (globsegcnt >= segmax) expand_segmax(segmax * SEGMAX_FACTOR);
if (globoschain != NULL)
{ w = (char *)globoschain;
size = globoschain->size;
globoschain = globoschain->next;
if (debugging(DEBUG_STORE))
cc_msg("Global store %d : reused size %ld at %p\n",
(int)globsegcnt, (long)size, w);
}
else if (bindsegcur < bindsegcnt)
{ w = bindsegbase[--bindsegcnt];
if (debugging(DEBUG_STORE))
cc_msg("Global store %d from binder size %ld at %p\n",
(int)globsegcnt, (long)SEGSIZE, w);
check_trashed((VoidStar)w, SEGSIZE);
}
else
{ w = (char *)cc_alloc(SEGSIZE);
if (debugging(DEBUG_STORE))
cc_msg("Global store alloc %d size %ld at %p (in $r)\n",
(int)globsegcnt, (long)SEGSIZE, w, currentfunction.symstr);
}
globallp = w, globalltop = w + size;
globsegsize[globsegcnt] = size;
return globsegbase[globsegcnt++] = w;
}
VoidStar GlobAlloc(StoreUse t, int32 n)
{ char *p = globallp;
n = (n + RR) & ~(int32)RR; /* n = pad_to_hosttype(n, IPtr) */
if (n > SEGSIZE)
{ /* Big global store requests get a single oversize page. */
if (globsegcnt >= segmax) expand_segmax(segmax * SEGMAX_FACTOR);
p = (char *)cc_alloc(n);
globsegsize[globsegcnt] = n;
globsegbase[globsegcnt++] = p;
if (debugging(DEBUG_STORE))
cc_msg("Global overlarge store alloc size %ld at %p (in $r)\n",
(long)n, p, currentfunction.symstr);
globallxtra += n;
}
else
{ if (p+n > globalltop)
stuse_waste += globalltop-p,
p = new_global_segment();
else
check_trashed(p, n);
globallp = p + n;
}
stuse[t] += n;
#ifndef ALLOC_DONT_CLEAR_MEMORY
memset(p, 0xbb, (size_t)n);
#endif
return p;
}
static char *new_bindalloc_segment(void)
{
if (bindsegcur >= bindsegcnt)
{ char *w = (char *)cc_alloc(SEGSIZE);
if (bindsegcnt >= segmax) expand_segmax(segmax * SEGMAX_FACTOR);
if (debugging(DEBUG_STORE))
cc_msg("Binder store alloc %d size %ld at %p (%s in $r)\n",
(int)bindsegcnt, (long)SEGSIZE, w,
phasename, currentfunction.symstr);
bindsegbase[bindsegcnt++] = w;
}
else
check_trashed(bindsegbase[bindsegcur], SEGSIZE);
return bindsegbase[bindsegcur++];
}
static char *new_synalloc_segment(void)
{
char *w;
if (synsegcnt >= segmax) expand_segmax(segmax * SEGMAX_FACTOR);
if (bindsegcur < bindsegcnt)
{ w = bindsegbase[--bindsegcnt];
if (debugging(DEBUG_2STORE) && synsegcnt>0)
cc_msg("Syntax store %d from binder size %ld at %p\n",
(int)synsegcnt, (long)SEGSIZE, w);
check_trashed(w, SEGSIZE);
}
else
{ w = (char *)cc_alloc(SEGSIZE);
if (debugging(DEBUG_STORE))
cc_msg("Syntax store alloc %d size %ld at %p (%s in $r)\n",
(int)synsegcnt, (long)SEGSIZE, w,
phasename, currentfunction.symstr);
}
return synsegbase[synsegcnt++] = w;
}
VoidStar BindAlloc(int32 n)
{
char *p = bindallp;
n = (n + RR) & ~(int32)RR; /* n = pad_to_hosttype(n, IPtr) */
if (n > SEGSIZE) syserr(syserr_overlarge_store1, (long)n);
if (p + n > bindalltop)
{ int i; /* 0..segmax */
if (bindsegcur > 0)
bindsegptr[bindsegcur-1] = p; /* stash highest used */
for (i = bindsegcur;;) /* search for scraps */
{ --i;
if (i < marklist->bind_segno) /* nowhere big enough */
{ p = new_bindalloc_segment();
bindalltop = p + SEGSIZE;
break;
}
p = bindsegptr[i]; /* hope springs eternal */
bindalltop = bindsegbase[i] + SEGSIZE;
if (((size_t)n > 3*sizeof(int32)) && (p+n <= bindalltop))
/* fingers crossed */
{ /* we have scavenged something useful - swap to current */
char *t = bindsegbase[i];
bindsegbase[i] = bindsegbase[bindsegcur-1];
bindsegbase[bindsegcur-1] = t;
bindsegptr[i] = bindsegptr[bindsegcur-1];
if (debugging(DEBUG_2STORE))
{ cc_msg("Scavenge binder %d (%p), %ld left\n",
(int)i, t, (long)(bindalltop-(p+n)));
}
break;
}
}
bindsegptr[bindsegcur-1] = (char *)DUFF_ADDR;
}
check_trashed(p, n);
bindallp = p + n;
if ((bindallhwm += n) > bindallmax) bindallmax = bindallhwm;
#ifndef ALLOC_DONT_CLEAR_MEMORY
memset(p, 0xcc, (size_t)n);
#endif
return p;
}
VoidStar SynAlloc(int32 n)
{ char *p = synallp;
n = (n + RR) & ~(int32)RR; /* n = pad_to_hosttype(n, IPtr) */
if (n > SEGSIZE) syserr(syserr_overlarge_store2, (long)n);
if (p + n > synalltop)
{ int i; /* 0..segmax */
if (synsegcnt > 0)
synsegptr[synsegcnt-1] = p; /* stash highest used */
for (i = synsegcnt;;) /* search for scraps */
{ --i;
if (i < marklist->syn_segno) /* nowhere big enough */
{ p = new_synalloc_segment();
synalltop = p + SEGSIZE;
break;
}
p = synsegptr[i]; /* hope springs eternal */
synalltop = synsegbase[i] + SEGSIZE;
if (((size_t)n > 3*sizeof(int32)) && (p+n <= synalltop))
/* fingers crossed */
{ /* we have scavenged something useful - swap to current */
char *t = synsegbase[i];
synsegbase[i] = synsegbase[synsegcnt-1];
synsegbase[synsegcnt-1] = t;
synsegptr[i] = synsegptr[synsegcnt-1];
if (debugging(DEBUG_2STORE))
{ cc_msg("Scavenge syntax %d (%p), %ld left\n",
(int)i, t, (long)(synalltop-(p+n)));
}
break;
}
}
synsegptr[synsegcnt-1] = (char *)DUFF_ADDR;
}
check_trashed(p, n);
synallp = p + n;
if ((synallhwm += n) > synallmax) synallmax = synallhwm;
#ifndef ALLOC_DONT_CLEAR_MEMORY
memset(p, 0xaa, (size_t)n);
#endif
return p;
}
VoidStar discard2(VoidStar p)
{
/* As cdr_(p) but returns the cell p to freestorage pool. */
/* The freechain has a funny number xored in to help debugging */
FreeList *pp = (FreeList *) p;
VoidStar q = (VoidStar) pp->next;
int i; /* 0..segmax */
pp->rest[0] ^= 0x99990000; /* to help with debugging */
for (i = synsegcnt; i > 0; )
{ --i;
if (synsegbase[i] <= (char *)pp && (char *)pp < synsegbase[i]+SEGSIZE)
{ pp->next = synall2;
synall2 = (FreeList *)(((IPtr)pp) ^ 0x6a6a6a6a);
return q;
}
}
for (i = bindsegcur; i > 0;)
{ --i;
if (bindsegbase[i] <= (char *)pp && (char *)pp < bindsegbase[i]+SEGSIZE)
{ pp->next = bindall2;
bindall2 = (FreeList *)(((IPtr)pp) ^ 0x5a5a5a5a);
return q;
}
}
syserr(syserr_discard2, (VoidStar) pp);
return q;
}
VoidStar xsyn_list2(IPtr a, IPtr b)
{ IPtr *p;
if (synall2==NULL)
p = (IPtr *) SynAlloc(sizeof(IPtr[2]));
else
{ p = (IPtr *)((IPtr) synall2 ^ 0x6a6a6a6a);
synall2 = (FreeList *) p[0];
}
p[0] = a; p[1] = b;
return (VoidStar) p;
}
VoidStar xbinder_list2(IPtr a, IPtr b)
{ if (bindall2==NULL)
{ IPtr *p = (IPtr *) BindAlloc(sizeof(IPtr[2]));
p[0] = a; p[1] = b;
return (VoidStar) p;
}
else
{ IPtr *p = (IPtr *)((IPtr) bindall2 ^ 0x5a5a5a5a);
bindall2 = (FreeList *) p[0];
p[0] = a; p[1] = b;
return (VoidStar) p;
}
}
VoidStar discard3(VoidStar p)
{
/* Returns the cell p to freestorage pool, with a funny number xored in to
* help debugging.
* Return value is (the old value of) p->next */
FreeList *pp = (FreeList *) p;
VoidStar q = (VoidStar) pp->next;
int i; /* 0..segmax */
int32 *ppp = pp->rest;
ppp[0] ^= 0x99990000; /* to help with debugging */
ppp[1] ^= 0x99990000; /* to help with debugging */
for (i = synsegcnt; i > 0;)
{ --i;
if (synsegbase[i] <= (char *)pp && (char *)pp < synsegbase[i]+SEGSIZE)
{ pp->next = synall3;
synall3 = (FreeList *)(((IPtr)pp) ^ 0x6a6a6a6a);
return q;
}
}
for (i = bindsegcur; i > 0;)
{ --i;
if (bindsegbase[i] <= (char *)pp && (char *)pp < bindsegbase[i]+SEGSIZE)
{ pp->next = bindall3;
bindall3 = (FreeList *)(((IPtr)pp) ^ 0x5a5a5a5a);
return q;
}
}
syserr(syserr_discard3, (VoidStar) pp);
return q;
}
VoidStar xbinder_list3(IPtr a, IPtr b, IPtr c)
{
IPtr *p;
if (bindall3 == NULL)
p = (IPtr *) BindAlloc(sizeof(IPtr[3]));
else {
p = (IPtr *)((IPtr) bindall3 ^ 0x5a5a5a5a);
bindall3 = (FreeList *) p[0];
}
p[0] = a; p[1] = b; p[2] = c;
return (VoidStar) p;
}
VoidStar xsyn_list3(IPtr a, IPtr b, IPtr c)
{ IPtr *p;
if (synall3 == NULL)
p = (IPtr *) SynAlloc(sizeof(IPtr[3]));
else {
p = (IPtr *)((IPtr) synall3 ^ 0x6a6a6a6a);
synall3 = (FreeList *) p[0];
}
p[0] = a; p[1] = b; p[2] = c;
return (VoidStar) p;
}
VoidStar xsyn_list4(IPtr a, IPtr b, IPtr c, IPtr d)
{ IPtr *p = (IPtr *) SynAlloc(sizeof(IPtr[4]));
p[0] = a, p[1] = b, p[2] = c, p[3] = d;
return (VoidStar) p;
}
VoidStar xsyn_list5(IPtr a, IPtr b, IPtr c, IPtr d, IPtr e)
{
IPtr *p = (IPtr *) SynAlloc(sizeof(IPtr[5]));
p[0] = a; p[1] = b; p[2] = c; p[3] = d; p[4] = e;
return (VoidStar) p;
}
VoidStar xsyn_list6(IPtr a, IPtr b, IPtr c, IPtr d, IPtr e, IPtr f)
{ IPtr *p = (IPtr *) SynAlloc(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 xsyn_list7(IPtr a, IPtr b, IPtr c, IPtr d, IPtr e, IPtr f,
IPtr g)
{ IPtr *p = (IPtr *) SynAlloc(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;
}
/* @@@ not used essentially for C but it is used for C++ */
Mark* alloc_mark(void)
{
Mark *p;
if ((p = freemarks) != NULL)
{
freemarks = p->prev;
check_trashed(&p->syn_segno, sizeof(Mark) - offsetof(Mark, syn_segno));
}
else
p = (Mark *) GlobAlloc(SU_Other, sizeof(Mark));
p->prev = marklist; marklist = p;
p->syn_segno = synsegcnt;
p->syn_allp = synallp; p->syn_hwm = synallhwm;
p->bind_segno = bindsegcur;
p->bind_allp = bindallp; p->bind_hwm = bindallhwm;
p->unmarked = false;
if (debugging(DEBUG_STORE))
cc_msg("Mark[%p] %d, %p, %lx :: %d, %p, %lx\n",
p, synsegcnt, synallp, (long)synallhwm,
bindsegcur, bindallp, (long)bindallhwm);
return p;
}
/* #ifdef PASCAL_OR_FORTRAN_OR_CPLUSPLUS -- comment out? */
void alloc_unmark(Mark* mark)
{
Mark *p = marklist;
for (; p->prev != NULL && p != mark; p = p->prev)
continue;
if (p->prev == NULL) syserr(syserr_alloc_unmark);
if (mark == marklist) /* unmarking most recent */
{ if (synsegcnt > mark->syn_segno)
syserr(syserr_alloc_unmark1);
for (;;)
{ p = marklist;
#if STORE_TRASHING || WATCH_FOR
{ int i;
for (i = synsegcnt; p->syn_segno < i; --i)
{ check_watch_for(synsegbase[i-1], SEGSIZE, "syntax segment");
trash_block(synsegbase[i-1], SEGSIZE);
}
}
#endif
synsegcnt = p->syn_segno; synallp = p->syn_allp;
if (synallp == DUFF_ADDR)
synalltop = (char *)DUFF_ADDR;
else
{ synalltop = synsegbase[synsegcnt-1] + SEGSIZE;
check_watch_for(synallp, synalltop - synallp, "syntax segment");
trash_block(synallp, synalltop - synallp);
}
synallhwm = p->syn_hwm;
/* NULLing out the free lists like this will lose the blocks */
/* that are between synallp and synalltop until the segment is */
/* recycled but it's considerably cheaper than scanning the free */
/* lists and segment array */
synall2 = NULL; synall3 = NULL;
#if STORE_TRASHING || WATCH_FOR
{ int i;
for (i = bindsegcur; p->bind_segno < i; --i)
{ check_watch_for(bindsegbase[i-1], SEGSIZE, "binder segment");
trash_block(bindsegbase[i-1], SEGSIZE);
}
}
#endif
bindsegcur = p->bind_segno; bindallp = p->bind_allp;
if (bindallp == DUFF_ADDR)
bindalltop = (char *)DUFF_ADDR;
else
{ bindalltop = bindsegbase[bindsegcur-1] + SEGSIZE;
check_watch_for(bindallp, bindalltop - bindallp, "binder segment");
trash_block(bindallp, bindalltop - bindallp);
}
bindallhwm = p->bind_hwm;
bindall2 = NULL; bindall3 = NULL;
if (debugging(DEBUG_STORE))
cc_msg("Unmark[%p] %d, %p, %lx :: %d, %p, %lx\n",
p, synsegcnt, synallp, (long)synallhwm,
bindsegcur, bindallp, (long)bindallhwm);
marklist = p->prev;
p->prev = freemarks;
trash_block(&p->syn_segno, sizeof(Mark) - offsetof(Mark, syn_segno)); /* can't trash p->prev */
freemarks = p;
if (!marklist->unmarked)
break;
}
}
else
{ p->unmarked = true;
if (debugging(DEBUG_STORE))
cc_msg("Unmark[%p] (pending)\n", p);
}
}
/* #endif */
void drop_local_store(void)
{
/* Here the threat issued using SynAlloc or syn_xxx materialises, and a
lot of local store is trampled upon. */
/* N.B. drop_local_store *MUST* be called before reinit_alloc() */
while (synsegcnt > marklist->syn_segno)
{ char *p = synsegbase[--synsegcnt];
#ifdef never
if (debugging(DEBUG_2STORE))
cc_msg("Re-using syntax store %p as binder %d\n",
p, (int)bindsegcnt);
#endif
check_watch_for(p, SEGSIZE, "syntax segment");
trash_block(p, SEGSIZE);
/* we do not need to mess with limits here as set to SEGSIZE when used */
if (bindsegcnt >= segmax) expand_segmax(segmax * SEGMAX_FACTOR);
bindsegbase[bindsegcnt++] = p;
}
synallp = marklist->syn_allp;
if (synallp == DUFF_ADDR)
synalltop = (char *)DUFF_ADDR;
else
{ synalltop = synsegbase[synsegcnt-1] + SEGSIZE;
check_watch_for(synallp, synalltop - synallp, "syntax segment");
trash_block(synallp, synalltop - synallp);
}
if (debugging(DEBUG_2STORE) && synallhwm==synallmax)
cc_msg("Max SynAlloc %ld in $r\n",
(long)synallmax, currentfunction.symstr);
synallhwm = marklist->syn_hwm;
synall2 = NULL; synall3 = NULL; /* see comment in alloc_unmark */
}
void alloc_reinit(void)
{ if (synsegcnt > marklist->syn_segno ||
synallp != marklist->syn_allp ||
synalltop != ((synallp == DUFF_ADDR) ? (char *)DUFF_ADDR
: synsegbase[synsegcnt-1] + SEGSIZE) ||
synall2 != NULL ||
synall3 != NULL
)
syserr(syserr_alloc_reinit);
#if STORE_TRASHING || WATCH_FOR
{ int i;
for (i = bindsegcur; marklist->bind_segno < i; --i)
{ check_watch_for(bindsegbase[i-1], SEGSIZE, "binder segment");
trash_block(bindsegbase[i-1], SEGSIZE);
}
}
#endif
bindallhwm = marklist->bind_hwm;
bindsegcur = marklist->bind_segno; bindallp = marklist->bind_allp;
bindalltop = (bindallp == DUFF_ADDR) ? (char *)DUFF_ADDR
: bindsegbase[bindsegcur-1] + SEGSIZE;
bindall2 = NULL; bindall3 = NULL; /* see comment in alloc_unmark */
}
void alloc_initialise(void)
{
/* Called once per invocation of the compiler */
alloc_chain = NULL;
bindsegcnt = 0;
globsegcnt = 0;
globoschain = NULL;
synsegbase = synsegptr = bindsegbase = bindsegptr = (char **)DUFF_ADDR;
permallp = permalltop = (char *)DUFF_ADDR;
segmax = 0; expand_segmax(SEGMAX_INIT);
}
void alloc_perfileinit(void)
{
/* reset the following vars for each one of a many file compilation */
stuse_total = 0, stuse_waste = 0;
memclr(stuse, sizeof(stuse));
synsegcnt = 0;
synallp = synalltop = (char *)DUFF_ADDR;
synall2 = NULL; synall3 = NULL;
synallhwm = 0, synallmax = 0;
bindsegcur = 0;
bindallp = bindalltop = (char *)DUFF_ADDR;
bindallhwm = 0, bindallmax = 0;
bindall2 = NULL; bindall3 = NULL;
globsegcnt = 0; globallxtra = 0;
globallp = globalltop = (char *)DUFF_ADDR;
marklist = NULL; freemarks = NULL;
maxAEstore = 0;
(void)alloc_mark(); /* alloc_reinit, etc. assume a mark */
}
void alloc_perfilefinalise(void)
{
if (marklist == NULL || marklist->prev != NULL)
syserr("corrupt alloc_marklist");
drop_local_store(); /* for caution's sake: perhaps always already done */
while (globsegcnt > 0)
{ char *p = globsegbase[--globsegcnt];
int32 size = globsegsize[globsegcnt];
if (size == SEGSIZE)
{ if (bindsegcnt >= segmax) expand_segmax(segmax * SEGMAX_FACTOR);
bindsegbase[bindsegcnt++] = p;
}
else
{ OverlargeBlockHeader *h = (OverlargeBlockHeader *)p;
h->next = globoschain;
h->size = size;
globoschain = h;
}
}
}
void alloc_noteAEstoreuse(void)
/* Calculate as blocks allocated minus space unused in (only) LAST BLOCK */
{ int32 n = ((int32)synsegcnt*SEGSIZE - (synalltop - synallp)) +
((int32)bindsegcur*SEGSIZE - (bindalltop - bindallp));
if (n > maxAEstore) maxAEstore = n;
}
void show_store_use(void)
{
#ifdef ENABLE_STORE
cc_msg(
"Total store use (excluding stdio buffers/stack) %ld bytes\n",
(long)stuse_total);
cc_msg("Global store use %ld/%ld + %ld bytes\n",
(long)((int32)globsegcnt*SEGSIZE - (globalltop - globallp)),
(long)((int32)globsegcnt*SEGSIZE),
(long)globallxtra);
cc_msg(
" thereof %ld+%ld bytes pended relocation, %ld bytes pended data\n",
(long)stuse[(int)SU_Xref],
(long)stuse[(int)SU_Xsym],
(long)stuse[(int)SU_Data]);
cc_msg(
" %ld bytes symbols, %ld bytes top-level vars, %ld bytes types\n",
(long)stuse[(int)SU_Sym],
(long)stuse[(int)SU_Bind],
(long)stuse[(int)SU_Type]);
cc_msg(
" %ld bytes constants, %ld bytes pre-processor, %ld bytes wasted\n",
(long)stuse[(int)SU_Const], (long)stuse[(int)SU_PP], (long)stuse_waste);
cc_msg( "Local store use %ld+%ld/%ld bytes - front end max %ld\n",
(long)synallmax, (long)bindallmax,
(long)((int32)(int)(synsegcnt+bindsegcnt)*SEGSIZE),
(long)maxAEstore);
#endif /* ENABLE_STORE */
}
/* end of mip/store.c */
|
stardot/ncc | mip/version.h | /*
* version.h
* Copyright (C) Acorn Computers Ltd., 1988.
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
/*
* Defines the compiler banner. The functional interface is preferable
* to a #define of the string (which in any case isn't possible for a non-Ansi
* compiler) because it saves space for multiple instances of the string,
* at negligible expense in time. Also, it minimises recompilation when
* all that has changed is the version
*/
#ifndef _version_h
#define _version_h 1
extern char *version_banner(void);
#define CC_BANNER version_banner()
/* note that for object file purposes CC_BANNERlen MUST be a multiple of 4
and include the final null in CC_BANNER (which should preferably be
normalised by zero padding in the last word)... */
#define CC_BANNERlen ((strlen(CC_BANNER) + 4L) & ~3L)
#endif
|
stardot/ncc | cppfe/doe.c | <reponame>stardot/ncc
/*
* C++ compiler file doe.c
* Copyright (C) Advanced RISC Machines Ltd., 1995
* SPDX-Licence-Identifier: Apache-2.0
* All rights reserved.
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
/* Parser functions for the declaration sub-grammar.
* Parsing is tuned towards resolving d-o-e ambiguity.
* ::*, CV-qualifiers and a missing expr in [] all
* indicative of a declaration.
* Expressions are not parsed; they are skipped.
* All syntax errors will be reported after the
* ambiguity has been resolved.
* Any ambiguity can be resolved syntactically,
* hence there is no instate declaration, no name lookup.
* Integer results (applicable to all):
* 2: definitely a declaration
* 1: not decided yet
* 0: definitely not a declaration (by implication an expr)
*/
#define DOE_DECL 2
#define DOE_UNDECIDED 1
#define DOE_NOTDECL 0
#ifndef _SYN_H
#include "aeops.h"
#endif
#define cursym (curlex.sym & ~s_qualified)
#define laterm_(s) \
(s == s_semicolon || \
s == s_lbrace)
#define class_cv_starter_(sym) \
(sym == s_class || sym == s_union || \
sym == s_struct || sym == s_enum || \
sym == s_const || sym == s_volatile)
static int rd_cv_seq(void)
{ if (cursym == s_const || cursym == s_volatile)
return DOE_DECL;
return DOE_UNDECIDED;
}
static int skip_match(void)
{ int count = 1;
AEop cur = cursym;
while (!laterm_(cur) && cur != s_eof && count)
{ if (cur == s_lpar ||
cur == s_lbracket ||
cur == s_lbrace) ++count;
if (cur == s_rpar ||
cur == s_rbracket ||
cur == s_rbrace) --count;
if (cur == s_ellipsis ||
cur == s_const ||
cur == s_volatile ||
class_cv_starter_(cur))
return DOE_DECL;
cur = lex_buffersym();
}
return DOE_UNDECIDED;
}
static int rd_nested_name_spec(void)
{ /* no template id yet */
while (cursym == s_identifier)
{ lex_buffersym();
if (cursym == s_coloncolon)
lex_buffersym();
else
return DOE_NOTDECL;
}
return DOE_UNDECIDED;
}
static int rd_type_spec(void)
{
if (istypestarter_(cursym) || cursym == s_typestartsym)
{ lex_buffersym();
return DOE_UNDECIDED;
}
if (class_cv_starter_(cursym))
return DOE_DECL;
if (cursym == s_coloncolon)
lex_buffersym();
if (cursym == s_identifier)
{ int sofar;
if (lex_buffersym() != s_coloncolon)
return DOE_UNDECIDED;
lex_buffersym();
sofar = rd_nested_name_spec();
if (sofar != DOE_UNDECIDED) return sofar;
if (cursym != s_identifier)
return DOE_NOTDECL;
lex_buffersym();
return DOE_UNDECIDED;
}
/* DOE_NOTDECL here means no type spec */
return DOE_NOTDECL;
}
static int rd_type_spec_seq(void)
{ int sofar;
while ((sofar = rd_type_spec()) == DOE_UNDECIDED);
return (sofar == DOE_DECL) ? sofar : DOE_UNDECIDED;
}
static int rd_unqual_id(void)
{
switch (cursym)
{
case s_bitnot:
return (lex_buffersym() == s_identifier) ? DOE_UNDECIDED : DOE_NOTDECL;
case s_operator:
lex_buffersym();
if hastypefield_(cursym)
{ lex_buffersym();
return DOE_UNDECIDED;
}
{ int sofar = rd_type_spec_seq();
AEop sym = cursym;
if (sofar != DOE_UNDECIDED) return sofar;
while (sym == s_times ||
sym == s_and ||
sym == s_coloncolon ||
sym == s_identifier)
{ if (sym == s_times || sym == s_and)
{ lex_buffersym();
if (sym == s_const || sym == s_volatile)
return DOE_DECL;
}
return DOE_DECL;
}
return DOE_UNDECIDED;
}
default:
return (cursym == s_identifier) ?
(lex_buffersym(), DOE_UNDECIDED) : DOE_NOTDECL;
}
}
#if 0
static int rd_id_expr(void)
{ int sofar = rd_unqual_id();
while (sofar == DOE_UNDECIDED && cursym == s_coloncolon)
{ lex_buffersym();
sofar = rd_unqual_id();
}
return sofar;
}
#endif
static int rd_abs_declarator(void);
static int rd_type_id(void)
{ AEop sym = cursym;
if (istypestarter_(sym) || class_cv_starter_(sym) ||
sym == s_coloncolon || sym == s_identifier)
{ int sofar = rd_type_spec_seq();
if (sofar != DOE_UNDECIDED) return sofar;
sym = cursym;
if (sym == s_times ||
sym == s_and ||
sym == s_coloncolon ||
sym == s_lpar)
return rd_abs_declarator();
return DOE_UNDECIDED;
}
else if (sym == s_typestartsym)
return DOE_UNDECIDED;
return DOE_NOTDECL;
}
static int rd_direct_abs_decl(void)
{ AEop sym;
while ((sym = cursym) == s_lpar || cursym == s_lbracket)
{
lex_buffersym();
if (sym == s_lpar)
{ int sofar;
if ((sofar = skip_match()) != DOE_UNDECIDED)
return sofar;
if (cursym == s_const || cursym == s_volatile)
return DOE_DECL;
/* exception spec */
}
else if (sym == s_lbracket)
{ int sofar;
if (cursym == s_rbracket)
return DOE_DECL; /* definite decl */
if ((sofar = skip_match()) != DOE_UNDECIDED)
return sofar;
}
}
return DOE_UNDECIDED;
}
static int rd_ptr_op(void)
{ int sofar = DOE_UNDECIDED;
switch (cursym) {
case s_and:
return DOE_UNDECIDED;
case s_times:
while (cursym == s_times && sofar == DOE_UNDECIDED)
lex_buffersym(), sofar = rd_cv_seq();
return sofar;
case s_coloncolon:
lex_buffersym();
if ((sofar = rd_nested_name_spec()) != DOE_UNDECIDED)
return sofar;
if (cursym != s_times) return DOE_NOTDECL;
lex_buffersym();
return rd_cv_seq();
default:
return DOE_NOTDECL;
}
}
static int rd_doe_declarator(bool concrete)
{ int sofar = DOE_DECL;
switch (cursym)
{
case s_coloncolon:
case s_and:
case s_times:
sofar = rd_ptr_op();
if (sofar != DOE_UNDECIDED) return sofar;
break;
case s_lpar:
lex_buffersym();
sofar = rd_doe_declarator(concrete);
if (sofar != DOE_UNDECIDED) return sofar;
if (cursym != s_rpar)
return DOE_NOTDECL;
lex_buffersym();
concrete = NO;
break;
case s_identifier:
if (!concrete) return DOE_NOTDECL;
break;
case s_typestartsym:
return DOE_DECL;
default:
return DOE_NOTDECL;
}
/* Three possibilities: I must have read a ptr_operator,
a (...) or an identifier.
*/
if (concrete)
{ if (cursym == s_lpar)
return rd_doe_declarator(concrete);
if ((sofar = rd_unqual_id()) != DOE_UNDECIDED)
return sofar;
if (cursym == s_coloncolon)
{ /* seen a "id::" */
while (cursym == s_coloncolon || cursym == s_identifier)
lex_buffersym();
if (cursym != s_times) return DOE_NOTDECL;
lex_buffersym();
if ((sofar = rd_unqual_id()) != DOE_UNDECIDED)
return sofar;
}
}
if (cursym == s_lbracket || cursym == s_lpar)
return rd_direct_abs_decl();
return DOE_UNDECIDED;
}
static int rd_abs_declarator(void)
{ return rd_doe_declarator(NO);
}
static int rd_init_declarator(void)
{ int sofar = rd_doe_declarator(YES);
if (sofar != DOE_UNDECIDED)
return sofar;
if (cursym == s_assign)
{ if (lex_buffersym() == s_lbrace)
return DOE_DECL;
while (!laterm_(cursym) && cursym != s_comma)
lex_buffersym();
return DOE_UNDECIDED;
}
if (cursym == s_lpar)
{ lex_buffersym();
return skip_match();
}
return sofar;
}
static int rd_init_declarator_seq(void)
{ int sofar = DOE_UNDECIDED;
while (sofar == DOE_UNDECIDED && !laterm_(cursym))
{
sofar = rd_init_declarator();
if (cursym == s_comma) lex_buffersym();
}
return sofar;
}
/* this must be preceded by a call to rd_type_name() */
static int is_declaration(int n)
{ int sofar = DOE_UNDECIDED;
lex_buffersym();
if (cursym == s_lpar)
sofar = (n == PASTCOMMA) ? rd_init_declarator_seq() : rd_init_declarator();
lex_endbuffering();
return sofar;
}
static int is_type_id(void)
{ int sofar = rd_type_id();
lex_endbuffering();
return sofar;
}
|
stardot/ncc | arm/ampops.h | <gh_stars>0
/*
* C compiler file arm/ampops.h
* Copyright (C) Advanced Risc Machines Ltd., 1997. All rights reserved.
* SPDX-Licence-Identifier: Apache-2.0
*/
/*
* RCS $Revision$
* Checkin $Date$
* Revising $Author$
*/
#ifndef _ampops_LOADED
#define _ampops_LOADED 1
#define AMP_FADD 0x50
#define AMP_FSUB 0x54
#define AMP_FABS 0x55
#define AMP_FMIN 0x47
#define AMP_FMAX 0x46
#define AMP_FCMPLT 0x44
#define AMP_FCMPEQ 0x41
#define AMP_FCMPLE 0x45
/* 6-2 single precision fp conversion ops */
#define AMP_FCVTFI 0x48
#define AMP_FCVTIF 0x58
#define AMP_FCPS 0x5a
#define AMP_FCPSN 0x5b
#define AMP_FCPSE 0x59
#define AMP_FNORM 0x51
/* 6-3 single precision fp multiply & accumulate ops */
#define AMP_FMAC0 0x52
#define AMP_FMAC1 0x53
#define AMP_FMDC0 0x56
#define AMP_FMDC1 0x57
#define AMP_FMUL0 0x42
#define AMP_FMUL1 0x43
#define AMP_FMTACC0 0x4a
#define AMP_FMTACC1 0x4b
#define AMP_FMFACC0 0x4a
#define AMP_FMFACC1 0x4b
/* 6-4 single precision fp divide sqrt move ops */
#define AMP_FDIV 0x5c
#define AMP_FDIVF 0x5d
#define AMP_FSQRT 0x5e
#define AMP_FSQRTF 0x5f
#define AMP_FMTQ 0x49
#define AMP_FMFQ 0x4c
#define AMP_FMFQN 0x4d
/* 7-1 move operations (nb MBU ops) */
#define AMP_MFCSR 0x2e
#define AMP_MTCSR 0x0e
#define AMP_TCM_EXU(op, rd, rs1, rs2) \
(0x0c000400 | ((op) << 16) | ((rs1) << 11) | ((rs2) << 5) | (rd))
#define AMP_TCM_MBU(op, rd, rs3, disp) \
(0x0d000400 | ((op) << 16) | ((rs3) << 11) | ((disp) << 5) | (rd))
#define MCR_32 0
#define MCR_4 1
#define AMP_MCR(size, r, cr) \
(0x0e000810 | ((size) << 22) | ((r) << 12) \
| 0x40 | (((cr)&0x10)<<1) | ((cr) & 0xf))
#define AMP_MRC(size, r, cr) \
(0x0e100810 | ((size) << 22) | ((r) << 12) \
| 0x40 | (((cr)&0x10)<<1) | ((cr) & 0xf))
#define CPDT_LD (1 << 20)
#define CPDT_ST 0
#define CPDT_PRE (1 << 24)
#define CPDT_POST 0
#define CPDT_WB (1<<21)
#define CPDT_UP (1 << 23)
#define CPDT_DOWN 0
#define AMP_DT(flags, base, fr, offset) \
(0x0c008800 | (flags) | ((base) << 16) \
| (((fr) & 0x3c) << 10) | (((fr) & 3) << 8) \
| ((offset) >> 2))
#define AMP_ZeroReg 31
#define AMP_WorkReg 30
#define AMP_F0 0
#define AMP_FPCR_RND (3<<4)
#define AMP_FPCR_RND_N 0
#define AMP_FPCR_RND_Z (1<<4)
#define AMP_FPCR_RND_U (2<<4)
#define AMP_FPCR_RND_D (3<<4)
#define AMP_FPSR 8
#define AMP_FPCR 11
#endif /* _ampops_loaded */
/* End of ampops.h */
|
fusor-io/fusor-node-connector | src/LocalTimeHandler/LocalTimeHandler.h | <gh_stars>0
#ifndef localtimehandler_h
#define localtimehandler_h
#include <Arduino.h>
// lets update time only if it differs by 2 or more seconds
#define MIN_DIFFERENCE 2
class LocalTimeHandler
{
public:
void update(String);
private:
bool _initialized = false;
unsigned long _lastSyncTime;
uint8_t _translateMonth(String);
time_t _timeDiff(time_t, time_t);
};
#endif
|
fusor-io/fusor-node-connector | src/NodeConnector.h | /*
Wifi Configurator -
web client based configuration for you IOT project
Copyright <NAME> 2020
MIT License
*/
#ifndef nodeconnector_h
#define nodeconnector_h
#ifdef ESP8266
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#else
#include <WiFi.h>
#include <HTTPClient.h>
#endif
#include <TimeLib.h>
#include <ArduinoJson.h>
// See: https://arduinojson.org/v6/api/
#include <WifiConfigurator.h>
#include <StateMachine.h>
#include "HubClient/HubClient.h"
#include "SMHooks/SMHooks.h"
#include "SyncInOptions/SyncInOptions.h"
#include "PersistentStorage/PersistentStorage.h"
#include "Utils/Utils.h"
#include "FileSystem/FileSystem.h"
#define MAX_CONNECT_RETRY 10
#define DEFAULT_STATEM_MACHINE_JSON_SIZE 4096
#define DEFAULT_PARAM_STORE_JSON_SIZE 512
#define MAX_URL_SIZE 256
#define JSON_NESTING_LIMIT 20
#define DEFAULT_NODE_ID "IOT Node"
#define DEFAULT_NODE_PASSWORD "<PASSWORD>"
// Parameters configurable through Wifi setup
const char PARAM_ACCESS_POINT[] = "access_point";
const char PARAM_PASSWORD[] = "password";
const char PARAM_FUSOR_HUB_ADDRESS[] = "Fusor_hub_address";
const char PARAM_NODE_ID[] = "node_ID";
// EEPROM filne names
const char SMD_FILE_PATH[] = "/smd.mpk";
const char LAST_MODIFIED_FILE_PATH[] = "/mod.txt";
// Fusor Hub url paths
const char ENDPOINT_DEFINITIONS[] = "/definitions/sm/";
const char ENDPOINT_NODE[] = "/node/";
const char ENDPOINT_PARAM_BATCH[] = "/batch";
#define NODE_SYNC_OUT_OPTIONS "o"
#define NODE_SYNC_IN_OPTIONS "i"
#define NODE_PERSISTENT_STORAGE "p"
#define NODE_STATE_MACHINE "s"
void _nc_sleepFunction(unsigned long);
unsigned long _nc_getTime();
void _nc_debugPrinter(const char *);
VarStruct _nc_month(ActionContext *);
VarStruct _nc_day(ActionContext *);
VarStruct _nc_weekDay(ActionContext *);
VarStruct _nc_hour(ActionContext *);
VarStruct _nc_now(ActionContext *);
time_t _nc_localTime(ActionContext *);
/*
* Structure of Node Definition JSON
*
* {
* "o": { "field_name_1": <sync options>, ... } - see SyncOutElementConfig.h for outbound sync options details
* "i": { ... } - see SyncInOptions.h for inbound data options (params to read from the hub)
* "p": { "field_name_1": <options>, ... } - see PersistentStorage.h for preserving variables between restarts
* "s": <state machine definition>
* }
*
*/
class NodeConnector
{
public:
NodeConnector(
const char *nodeId = DEFAULT_NODE_ID,
const char *configPassword = <PASSWORD>,
uint16_t stateMachineJsonSize = DEFAULT_STATEM_MACHINE_JSON_SIZE,
uint16_t paramStoreJsonSize = DEFAULT_PARAM_STORE_JSON_SIZE);
bool serveConfigPage();
bool setup(uint16_t, bool activateOnHigh = false, uint16_t waitTimeout = 3000);
void start();
void loop(unsigned long timeOut = 60000);
void loadDefinition();
bool fetchDefinitionFromHub();
bool loadDefinitionFromFlash();
bool saveSmdToFlash();
bool storeSmd();
bool saveLastModifiedTime(const char *);
const char *loadLastModifiedtime();
bool fetchParamsFromHub();
bool isAccessPointConfigured();
bool isSmdLoaded = false;
// wifi client related
void startWiFi();
HubClient hubClient;
const char *nodeId;
StateMachineController sm;
DynamicJsonDocument nodeDefinition;
DynamicJsonDocument paramStore;
JsonVariant stateMachine;
JsonVariant syncOptions;
DeserializationError error;
FileSystem fs;
void disbaleSerialPrint();
private:
WifiConfigurator _configurator;
SMHooks _hooks;
SyncInOptions _syncInConfig;
PersistentStorage _persistentStorage;
const char *_nodeId;
const char *_configPassword;
const char *_hubAddress;
const char *_postUrl; // url to post Node results (eg. sensor data)
const char *_getUrl; // url to get Node inputs (eg. configurations or results of other Nodes)
bool _initSM();
void _addFunctions();
void _initPostUrl();
void _initGetUrl();
bool _fetchMsgPack(const char *,
DynamicJsonDocument *,
const char *ifModifiedSince = nullptr,
uint8_t nestingLimit = JSON_NESTING_LIMIT);
bool _openWiFiConnection();
unsigned long _lastTimeDefinitionChecked = 0;
unsigned long _lastTimeSyncInAttempted = 0;
char _timeStampBuff[HTTP_TIME_STAMP_LENGTH] = {'\0'};
};
#endif
|
fusor-io/fusor-node-connector | src/PersistentStorage/PersistentStorage.h | #ifndef PersistentStorage_h
#define PersistentStorage_h
#include <map>
#include <ArduinoJson.h>
#include <StateMachine.h>
#include <Arduino.h>
#include "../FileSystem/FileSystem.h"
#include "RecordStruct.h"
/*
* Persistent storage is used to save choosen variables to ERPROM and load them
* as default values after the restart,
*
* Options for single field to be stored into EEPROM
* {
* DEFAULT_VALUE: int | float,
* MIN_TIMEOUT: int, // Minimal time in seconds between updates to EEPROM. If not set - defaults to 6 hours.
* // ESP32 should survive at least 10.000 rewrites.
* // Rewriting once per 6 hours will result in ~7 years of service
* // Note: timer is reset on each restart (no RTC)
* AFTER_FIRST_CYCLE: bool, // saves after the first StateMachine cycle
* ON_RESTART: bool, // saves before restart initiated by NodeConnector
* }
*/
// TODO implement list for saving update times
#define DEFAULT_VALUE "d"
#define MIN_TIMEOUT "t"
#define AFTER_FIRST_CYCLE "f"
#define ON_RESTART "r"
// 6 hours in seconds
#define DEFAULT_MIN_TIMEOUT 21600ul
enum StorageEvent {onFirstCycle, onUpdate, onReboot};
const char STORAGE_FILE[] = "/variables.bin";
class PersistentStorage
{
public:
PersistentStorage();
void init(JsonVariant, Store *);
void saveOnUpdate(const char *);
void saveOnReboot();
void saveOnFirstCycle();
void load();
private:
bool _initialized = false;
JsonObject _options;
Store *_store;
FileSystem _fs;
std::map<char *, RecordStruct *, KeyCompare> _tracker;
KeyCreate _keyCreator;
bool _canSave(const char *, StorageEvent);
bool _canSaveAnyOnEvent(StorageEvent);
bool _isFlagOn(const char *, const char *);
unsigned long _minTimeout(const char *);
void _save();
};
#endif
|
fusor-io/fusor-node-connector | src/Utils/Utils.h | <gh_stars>0
#ifndef ncutils_h
#define ncutils_h
#include <Arduino.h>
unsigned long diff(unsigned long, unsigned long);
unsigned long getTimeout(unsigned long);
#endif |
fusor-io/fusor-node-connector | src/HubClient/HubClient.h | <reponame>fusor-io/fusor-node-connector
#ifndef hubclient_h
#define hubclient_h
#include <ArduinoJson.h>
#ifdef ESP8266
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#else
#include <WiFi.h>
#include <HTTPClient.h>
#endif
#include "../LocalTimeHandler/LocalTimeHandler.h"
#define MAX_CONNECT_RETRY 20
#define HTTP_TIME_STAMP_LENGTH 30
// ex. "Wed, 21 Oct 2015 07:28:00 GMT" + /0
const char HEADER_CONTENT_TYPE[] = "content-type";
const char HEADER_ACCEPT[] = "accept";
const char HEADER_IF_MODIFIED_SINCE[] = "if-modified-since";
const char CONTENT_TYPE_MSG_PACK[] = "application/msgpack";
class HubClient
{
public:
HubClient();
void init(const char *, const char *);
bool connect();
void off();
void on();
bool isConnected();
bool ensureConnection();
WiFiClient *openMsgPackStream(const char *, const char *);
void closeMsgPackStream();
void postMsgPack(const char *, const uint8_t *, size_t);
char ip[16];
// see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Date
// see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified
// see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Modified-Since
// <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT
char timeStamp[HTTP_TIME_STAMP_LENGTH];
private:
const char *_ssid;
const char *_password;
// see https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.cpp
HTTPClient _http;
LocalTimeHandler _localTimeHandler;
};
#endif
|
fusor-io/fusor-node-connector | src/SyncInOptions/SyncInOptions.h | <gh_stars>0
#ifndef syncinoptions_h
#define syncinoptions_h
#include <ArduinoJson.h>
/**
* SyncIn options:
* {
* "f": string[]
* "d": number
* }
*
* "f" - array of field names to read from the hub and write to StateMachine store. Field - node-id.field-name
* "d" - ms to delay between updates
*/
#define SYNC_FIELDS "f"
#define SYNC_DELAY "d"
const char HUB_REQUEST_PATH[] = "/aggregate/batch/flat";
class SyncInOptions
{
public:
SyncInOptions();
void init(JsonVariant, const char *);
unsigned long delay = 60000;
const char *requestUrl = nullptr;
private:
void _buildRequestUrl(JsonArray, const char *);
uint16_t _calculateUrlQuerySize(JsonArray);
};
#endif
|
fusor-io/fusor-node-connector | src/PersistentStorage/RecordStruct.h | #ifndef recordstruct_h
#define recordstruct_h
#include <Arduino.h>
#include <StateMachine.h>
typedef struct RecordStruct
{
RecordStruct(VarStruct *value)
: var(value), updatedAt(millis()) {}
VarStruct var;
unsigned long updatedAt;
} RecordStruct;
#endif |
fusor-io/fusor-node-connector | src/SMHooks/SMHooks.h | #ifndef smhooks_h
#define smhooks_h
#include <map>
#include <ArduinoJson.h>
#include <StateMachine.h>
#include "../SyncOutElementConfig/SyncOutElementConfig.h"
#include "../Utils/Utils.h"
#include "../HubClient/HubClient.h"
#include "../PersistentStorage/PersistentStorage.h"
class SMHooks : public Hooks
{
public:
void init(HubClient *, PersistentStorage *, const char *, StateMachineController *, JsonVariant);
void emit(DynamicJsonDocument *output);
void onVarUpdate(const char *, VarStruct *);
void afterCycle(unsigned long);
void setVar(const char *, float);
void setVar(const char *, long int);
private:
JsonVariant _options;
StateMachineController *_sm;
HubClient *_hub;
PersistentStorage *_persistentStorage;
const char *_postUrl;
std::map<const char *, SyncOutElementConfig *, KeyCompare> _registry;
uint16_t _collectedCount();
size_t _collectedSize();
void _onChange(SyncOutElementConfig *, VarStruct *);
void _preprocess(SyncOutElementConfig *, VarStruct *);
void _preprocessCycle(SyncOutElementConfig *, VarStruct *, unsigned long);
void _accumulate(SyncOutElementConfig *, VarStruct *, bool);
void _collect(SyncOutElementConfig *);
void _collect(SyncOutElementConfig *, VarStruct *);
};
#endif |
fusor-io/fusor-node-connector | src/PrintWrapper/PrintWrapper.h | <reponame>fusor-io/fusor-node-connector<gh_stars>0
#ifndef ncprintwrapper_h
#define ncprintwrapper_h
#include <Arduino.h>
extern bool __nc_serial_enabled;
template <class T>
inline Print &operator<<(Print &stream, T arg)
{
if (__nc_serial_enabled)
stream.print(arg);
return stream;
}
#endif |
fusor-io/fusor-node-connector | src/FileSystem/FileSystem.h | #ifndef filesystem_h
#define filesystem_h
#include <Arduino.h>
#ifdef ESP32
#include <SPIFFS.h>
#else
#include <FS.h>
#endif
// https://github.com/espressif/arduino-esp32/blob/master/libraries/SPIFFS/src/SPIFFS.cpp
class FileSystem
{
public:
bool begin(bool formatOnFail = false);
void end();
bool exists(const char *);
size_t totalBytes();
File open(const char *, const char *);
void remove(const char *);
private:
bool _begin(bool formatOnFail = false);
};
#endif |
fusor-io/fusor-node-connector | src/SyncOutElementConfig/SyncOutElementConfig.h | <reponame>fusor-io/fusor-node-connector
#ifndef SyncOutElementConfig_h
#define SyncOutElementConfig_h
#include <ArduinoJson.h>
#include <StateMachine.h>
/*
* Sync out options (defines how variable from state machine is emitted to the hub)
* {
* SYNC_TYPE: "i" | "p" | "c", // i - instant (on update), p - with preprocessing, c - on value change
* PREPROCESSING: "f" | "l" | "a" | "n" | "x", // f - first, l - last, a - average, n - min, x - max
* FRAME_TYPE: "c" | "d", // c - number of state machine cycles, d - approximate duration in ms
* FRAME_LENGTH: <number>
* THRESHOLD: <number>
* }
*/
#define SYNC_TYPE "s"
#define SYNC_TYPE_INSTANT "i"
#define SYNC_TYPE_PREPROCESS "p"
#define SYNC_TYPE_ON_CHANGE "c"
#define SYNC_PREPROCESS "p"
#define SYNC_PREPROCESS_FIRST "f"
#define SYNC_PREPROCESS_LAST "l"
#define SYNC_PREPROCESS_AVERAGE "a"
#define SYNC_PREPROCESS_MIN "n"
#define SYNC_PREPROCESS_MAX "x"
#define SYNC_FRAME_TYPE "f"
#define SYNC_FRAME_TYPE_CYCLE_NUM "c"
#define SYNC_FRAME_TYPE_DURATION "d"
#define SYNC_FRAME_LENGTH "l"
#define SYNC_THRESHOLD "t"
#define T_INSTANT 1
#define T_PREPROCESS 2
#define T_ON_CHANGE 3
#define P_FIRST 1
#define P_LAST 2
#define P_AVERAGE 3
#define P_MIN 4
#define P_MAX 5
#define F_CYCLE_NUM 1
#define F_DURATION 2
class SyncOutElementConfig
{
public:
SyncOutElementConfig(const char *, JsonVariant);
uint8_t syncType = 0;
uint8_t preprocessing = 0;
uint8_t frameType = 0;
unsigned long frameLength = 0;
float threshold = 0.0f;
const char *name;
VarStruct accumulator;
unsigned long updateCounter = 0;
bool canEmit = false;
unsigned long lastEmit = 0;
unsigned long frameNum = 0;
};
#endif |
KornnerStudios/tinycpp | tokenizer.h | #ifndef TOKENIZER_H
#define TOKENIZER_H
#define MAX_TOK_LEN 4096
#define MAX_UNGETC 8
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
struct tokenizer_getc_buf {
int buf[MAX_UNGETC];
size_t cnt, buffered;
};
enum markertype {
MT_SINGLELINE_COMMENT_START = 0,
MT_MULTILINE_COMMENT_START = 1,
MT_MULTILINE_COMMENT_END = 2,
MT_MAX = MT_MULTILINE_COMMENT_END
};
#define MAX_CUSTOM_TOKENS 32
enum tokentype {
TT_IDENTIFIER = 1,
TT_SQSTRING_LIT,
TT_DQSTRING_LIT,
TT_ELLIPSIS,
TT_HEX_INT_LIT,
TT_OCT_INT_LIT,
TT_DEC_INT_LIT,
TT_FLOAT_LIT,
TT_SEP,
/* errors and similar */
TT_UNKNOWN,
TT_OVERFLOW,
TT_WIDECHAR_LIT,
TT_WIDESTRING_LIT,
TT_EOF,
TT_CUSTOM = 1000 /* start user defined tokentype values */
};
const char* tokentype_to_str(enum tokentype tt);
struct token {
enum tokentype type;
int value;
int64_t line;
int64_t column;
};
enum tokenizer_flags {
TF_PARSE_STRINGS = 1 << 0,
TF_PARSE_WIDE_STRINGS = 1 << 1,
};
struct tokenizer {
FILE *input;
int64_t line;
int64_t column;
int flags;
int custom_count;
int peeking;
const char *custom_tokens[MAX_CUSTOM_TOKENS];
char buf[MAX_TOK_LEN];
size_t bufsize;
struct tokenizer_getc_buf getc_buf;
const char* marker[MT_MAX+1];
const char* filename;
struct token peek_token;
};
void tokenizer_init(struct tokenizer *t, FILE* in, int flags);
void tokenizer_set_filename(struct tokenizer *t, const char*);
void tokenizer_set_flags(struct tokenizer *t, int flags);
int tokenizer_get_flags(struct tokenizer *t);
int64_t tokenizer_ftello(struct tokenizer *t);
void tokenizer_register_marker(struct tokenizer*, enum markertype, const char*);
void tokenizer_register_custom_token(struct tokenizer*, int tokentype, const char*);
int tokenizer_next(struct tokenizer *t, struct token* out);
int tokenizer_peek_token(struct tokenizer *t, struct token* out);
int tokenizer_peek(struct tokenizer *t);
void tokenizer_skip_until(struct tokenizer *t, const char *marker);
int tokenizer_skip_chars(struct tokenizer *t, const char *chars, int *count);
int tokenizer_read_until(struct tokenizer *t, const char* marker, int stop_at_nl);
int tokenizer_rewind(struct tokenizer *t);
#endif
|
wungad/libnetconf2 | src/libnetconf.h | <gh_stars>100-1000
/**
* @file libnetconf.h
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
* @brief libnetconf2 main internal header.
*
* Copyright (c) 2015 - 2021 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*/
#ifndef NC_LIBNETCONF_H_
#define NC_LIBNETCONF_H_
#include "config.h"
#include "log_p.h"
#include "messages_p.h"
#include "netconf.h"
#include "session_p.h"
/* Tests whether string is empty or non-empty. */
#define strisempty(str) ((str)[0] == '\0')
#define strnonempty(str) ((str)[0] != '\0')
/**
* @mainpage About
*
* libnetconf2 is a NETCONF library in C handling NETCONF authentication and all NETCONF
* RPC communication both server and client-side. Note that NETCONF datastore implementation
* is not a part of this library. The library supports both NETCONF 1.0
* ([RFC 4741](https://tools.ietf.org/html/rfc4741)) as well as NETCONF 1.1
* ([RFC 6241](https://tools.ietf.org/html/rfc6241)).
*
* @section about-features Main Features
*
* - Creating SSH ([RFC 4742](https://tools.ietf.org/html/rfc4742), [RFC 6242](https://tools.ietf.org/html/rfc6242)),
* using [libssh](https://www.libssh.org/), or TLS ([RFC 7589](https://tools.ietf.org/html/rfc7589)),
* using [OpenSSL](https://www.openssl.org/), authenticated NETCONF sessions.
* - Creating NETCONF sessions with a pre-established transport protocol
* (using this mechanism the communication can be tunneled through sshd(8), for instance).
* - Creating NETCONF Call Home sessions ([RFC 8071](https://tools.ietf.org/html/rfc8071)).
* - Creating, sending, receiving, and replying to RPCs ([RFC 4741](https://tools.ietf.org/html/rfc4741),
* [RFC 6241](https://tools.ietf.org/html/rfc6241)).
* - Creating, sending and receiving NETCONF Event Notifications ([RFC 5277](https://tools.ietf.org/html/rfc5277)),
*
* @section about-license License
*
* Copyright (c) 2015-2021 CESNET, z.s.p.o.
*
* (The BSD 3-Clause License)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name of the Company nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*/
/**
* @page howto How To ...
*
* - @subpage howtoinit
* - @subpage howtoclient
* - @subpage howtoserver
* - @subpage howtoclientcomm
* - @subpage howtoservercomm
* - @subpage howtotimeouts
*/
/**
* @page howtoinit Init and Thread-safety Information
*
* Before working with the library, it must be initialized using ::nc_client_init()
* or ::nc_server_init(). Based on how the library was compiled, also _libssh_ and/or
* _libssh_/_libcrypto_ are initialized (for multi-threaded use) too. To prevent
* any reachable memory at the end of your application, there are complementary
* destroy functions (::nc_server_destroy() and ::nc_client_destroy() available. If your
* application is multi-threaded, call the destroy functions in the main thread,
* after all the other threads have ended. In every other thread you should call
* ::nc_thread_destroy() just before it exits.
*
* If _libnetconf2_ is used in accordance with this information, there should
* not be memory leaks of any kind at program exit. For thread-safety details
* of _libssh_, _libssl_, and _libcrypto_, please refer to the corresponding project
* documentation. _libnetconf2_ thread-safety information is below.
*
* Client
* ------
*
* Optionally, a client can specify two alternative ways to get schemas needed when connecting
* with a server. The primary way is to read local files in searchpath (and its subdirectories)
* specified via ::nc_client_set_schema_searchpath(). Alternatively, _libnetconf2_ can use callback
* provided via ::nc_client_set_schema_callback(). If these ways do not succeed and the server
* implements NETCONF \<get-schema\> operation, the schema is retrieved from the server and stored
* localy into the searchpath (if specified) for a future use. If none of these methods succeed to
* load particular schema, the data from this schema are ignored during the communication with the
* server.
*
* Besides the mentioned setters, there are many other @ref howtoclientssh "SSH", @ref howtoclienttls "TLS"
* and @ref howtoclientch "Call Home" getter/setter functions to manipulate with various settings. All these
* settings are internally placed in a thread-specific context so they are independent and
* initialized to the default values within each new thread. However, the context can be shared among
* the threads using ::nc_client_get_thread_context() and ::nc_client_set_thread_context() functions. In such
* a case, be careful and avoid concurrent execution of the mentioned setters/getters and functions
* creating connection (no matter if it is a standard NETCONF connection or Call Home).
*
* In the client, it is thread-safe to work with distinguish NETCONF sessions since the client
* settings are thread-specific as described above.
*
* Server
* ------
*
* Server is __FULLY__ thread-safe meaning you can set all the (thread-shared in contrast to
* client) options simultaneously while listening for or accepting new sessions or
* polling the existing ones. It is even safe to poll one session in several
* pollsession structures or one pollsession structure in several threads. Generally,
* servers can use more threads without any problems as long as they keep their workflow sane
* (behavior such as freeing sessions only after no thread uses them or similar).
*
* Functions List
* --------------
*
* Available in __nc_client.h__.
*
* - ::nc_client_init()
* - ::nc_client_destroy()
*
* - ::nc_client_set_schema_searchpath()
* - ::nc_client_get_schema_searchpath()
* - ::nc_client_set_schema_callback()
* - ::nc_client_get_schema_callback()
*
* - ::nc_client_set_thread_context()
* - ::nc_client_get_thread_context()
*
* Available in __nc_server.h__.
*
* - ::nc_server_init()
* - ::nc_server_destroy()
*
* Available in both __nc_client.h__ and __nc_server.h__.
*
* - ::nc_thread_destroy()
*/
/**
* @page howtoclient Client sessions
*
* To connect to a NETCONF server, a NETCONF session must be established,
* which requires a working transport session. It is possible to create
* NETCONF sessions with SSH (using _libssh_) or TLS (using _libssl/libcrypto_)
* as the underlying transport protocol. It is also possible to establish
* the transport protocol outside _libnetconf2_ and then provide these file
* descriptors (FD) for full NETCONF session creation.
*
* There are a lot of options for both an SSH and a TLS client. All of them
* have setters and getters so that there is no need to duplicate them in
* a client.
*
* @anchor howtoclientssh
* SSH
* ===
*
* Connecting to a server using SSH does not strictly require to set any
* options, there are sensible default values for all the basic ones.
* Except all the SSH options, optionally some authetication callbacks can be set,
* which are particulary useful in automated clients (passwords cannot be
* asked a user) or simply if any additional information is retrieved some
* other way than from standard terminal input.
*
* Having the default options or changing any unsuitable ones, there are 2 functions
* to use for a new server connection. ::nc_connect_ssh() is the standard function
* that creates sessions using the set options. If there are some options, which
* cannot be changed with the provided API, there is ::nc_connect_libssh() available.
* It requires a _libssh_ session, in which all the SSH options can be modified
* and even the connection established. This allows for full customization and
* should fit any specific situation.
*
* New NETCONF sessions can also be created on existing authenticated SSH sessions.
* There is a new SSH channel needed, on which the NETCONF session is then created.
* Use ::nc_connect_ssh_channel() for this purpose.
*
* Functions List
* --------------
*
* Available in __nc_client.h__.
*
* - ::nc_client_ssh_set_auth_hostkey_check_clb()
* - ::nc_client_ssh_get_auth_hostkey_check_clb()
* - ::nc_client_ssh_set_auth_password_clb()
* - ::nc_client_ssh_get_auth_password_clb()
* - ::nc_client_ssh_set_auth_interactive_clb()
* - ::nc_client_ssh_get_auth_interactive_clb()
* - ::nc_client_ssh_set_auth_privkey_passphrase_clb()
* - ::nc_client_ssh_get_auth_privkey_passphrase_clb()
* - ::nc_client_ssh_add_keypair()
* - ::nc_client_ssh_del_keypair()
* - ::nc_client_ssh_get_keypair_count()
* - ::nc_client_ssh_get_keypair()
* - ::nc_client_ssh_set_auth_pref()
* - ::nc_client_ssh_get_auth_pref()
* - ::nc_client_ssh_set_username()
* - ::nc_client_ssh_get_username()
*
* - ::nc_connect_ssh()
* - ::nc_connect_libssh()
* - ::nc_connect_ssh_channel()
*
* @anchor howtoclienttls
* TLS
* ===
*
* To connect to a server using TLS, there must be some client identification
* options set. Client must specify its certificate with a private key using
* ::nc_client_tls_set_cert_key_paths(). Also, the Certificate Authority of
* a server certificate must be considered trusted. Paths to all the trusted
* CA certificates can be set by ::nc_client_tls_set_trusted_ca_paths().
*
* Then there are again 2 functions for connecting, ::nc_connect_tls() being
* the standard way of connecting. ::nc_connect_libssl() again enables
* to customize the TLS session in every way _libssl_ allows.
*
* Functions List
* --------------
*
* Available in __nc_client.h__.
*
* - ::nc_client_tls_set_cert_key_paths()
* - ::nc_client_tls_get_cert_key_paths()
* - ::nc_client_tls_set_trusted_ca_paths()
* - ::nc_client_tls_get_trusted_ca_paths()
* - ::nc_client_tls_set_crl_paths()
* - ::nc_client_tls_get_crl_paths()
*
* - ::nc_connect_tls()
* - ::nc_connect_libssl()
*
*
* FD and UNIX socket
* ==================
*
* If you authenticated the connection using some tunneling software, you
* can pass its file descriptors to _libnetconf2_ using ::nc_connect_inout(),
* which will continue to establish a full NETCONF session. To connect locally
* on a UNIX socket avoiding all cryptography use ::nc_connect_unix().
*
* Funtions List
* -------------
*
* Available in __nc_client.h__.
*
* - ::nc_connect_inout()
* - ::nc_connect_unix()
*
*
* @anchor howtoclientch
* Call Home
* =========
*
* Call Home needs the same options set as standard SSH or TLS and the functions
* reflect it exactly. However, to accept a connection, the client must first
* specify addresses and ports, which to listen on by ::nc_client_ssh_ch_add_bind_listen()
* and ::nc_client_tls_ch_add_bind_listen(). Then connections can be
* accepted using ::nc_accept_callhome().
*
* Functions List
* --------------
*
* Available in __nc_client.h__.
*
* - ::nc_client_ssh_ch_set_auth_hostkey_check_clb()
* - ::nc_client_ssh_ch_set_auth_password_clb()
* - ::nc_client_ssh_ch_set_auth_interactive_clb()
* - ::nc_client_ssh_ch_set_auth_privkey_passphrase_clb()
* - ::nc_client_ssh_ch_add_bind_listen()
* - ::nc_client_ssh_ch_del_bind()
* - ::nc_client_ssh_ch_add_keypair()
* - ::nc_client_ssh_ch_del_keypair()
* - ::nc_client_ssh_ch_get_keypair_count()
* - ::nc_client_ssh_ch_get_keypair()
* - ::nc_client_ssh_ch_set_auth_pref()
* - ::nc_client_ssh_ch_get_auth_pref()
* - ::nc_client_ssh_ch_set_username()
* - ::nc_client_ssh_ch_get_username()
*
* - ::nc_client_tls_ch_add_bind_listen()
* - ::nc_client_tls_ch_del_bind()
* - ::nc_client_tls_ch_set_cert_key_paths()
* - ::nc_client_tls_ch_get_cert_key_paths()
* - ::nc_client_tls_ch_set_trusted_ca_paths()
* - ::nc_client_tls_ch_get_trusted_ca_paths()
* - ::nc_client_tls_ch_set_crl_paths()
* - ::nc_client_tls_ch_get_crl_paths()
*
* - ::nc_accept_callhome()
*
*
* Cleanup
* =======
*
* These options and the schema searchpath are stored in dynamically
* allocated memory. They are freed as a part of [destroying the client](@ref howtoinit).
*/
/**
* @page howtoserver Server sessions
*
* Init
* ====
*
* Server takes an argument for its [initialization function](@ref howtoinit).
* In it, you set the server context, which determines what modules it
* supports and what capabilities to advertise. Few capabilities that
* cannot be learnt from the context are set with separate functions
* ::nc_server_set_capab_withdefaults() and generally ::nc_server_set_capability().
* Timeout for receiving the _hello_ message on a new session can be set
* by ::nc_server_set_hello_timeout() and the timeout for disconnecting
* an inactive session by ::nc_server_set_idle_timeout().
*
* Context does not only determine server modules, but its overall
* functionality as well. For every RPC the server should support,
* an nc_rpc_clb callback should be set on that node in the context using ::nc_set_rpc_callback().
* Server then calls these as appropriate [during poll](@ref howtoservercomm).
*
* Just like in the [client](@ref howtoclient), you can let _libnetconf2_
* establish SSH or TLS transport or do it yourself and only provide the file
* descriptors of the connection.
*
* Server options can be only set, there are no getters.
*
* To be able to accept any connections, endpoints must first be added
* with ::nc_server_add_endpt() and configured with ::nc_server_endpt_set_address()
* and ::nc_server_endpt_set_port(). For unix sockets, ::nc_server_endpt_set_perms()
* is available to set the unix socket file permissions, and ::nc_server_endpt_set_port()
* is invalid.
*
* Functions List
* --------------
*
* Available in __nc_server.h__.
*
* - ::nc_server_set_capab_withdefaults()
* - ::nc_server_set_capability()
* - ::nc_server_set_hello_timeout()
* - ::nc_server_set_idle_timeout()
*
* - ::nc_server_add_endpt()
* - ::nc_server_del_endpt()
* - ::nc_server_endpt_set_address()
* - ::nc_server_endpt_set_port()
* - ::nc_server_endpt_set_perms()
*
*
* SSH
* ===
*
* To successfully accept an SSH session you must set at least the host key using
* ::nc_server_ssh_endpt_add_hostkey(), which are ordered. This way you simply add
* some hostkey identifier, but the key itself will be retrieved always when needed
* by calling the callback set by ::nc_server_ssh_set_hostkey_clb().
*
* There are also some other optional settings. Note that authorized
* public keys are set for the server as a whole, not endpoint-specifically.
*
* Functions List
* --------------
*
* Available in __nc_server.h__.
*
* - ::nc_server_ssh_endpt_add_hostkey()
* - ::nc_server_ssh_endpt_del_hostkey()
* - ::nc_server_ssh_endpt_mov_hostkey()
* - ::nc_server_ssh_endpt_mod_hostkey()
* - ::nc_server_ssh_endpt_set_auth_methods()
* - ::nc_server_ssh_endpt_set_auth_attempts()
* - ::nc_server_ssh_endpt_set_auth_timeout()
*
* - ::nc_server_ssh_set_hostkey_clb()
*
* - ::nc_server_ssh_add_authkey()
* - ::nc_server_ssh_add_authkey_path()
* - ::nc_server_ssh_del_authkey()
*
*
* TLS
* ===
*
* TLS works with endpoints too, but its options differ
* significantly from the SSH ones, especially in the _cert-to-name_
* options that TLS uses to derive usernames from client certificates.
* So, after starting listening on an endpoint you need to set the server
* certificate (::nc_server_tls_endpt_set_server_cert()). Its actual content
* together with the matching private key will be loaded using a callback
* from ::nc_server_tls_set_server_cert_clb(). Additional certificates needed
* for the client to verify the server's certificate chain can be loaded using
* a callback from ::nc_server_tls_set_server_cert_chain_clb().
*
* To accept client certificates, they must first be considered trusted,
* which you have three ways of achieving. You can add each of their Certificate Authority
* certificates to the trusted ones or mark a specific client certificate
* as trusted. Lastly, you can set paths with all the trusted CA certificates
* with ::nc_server_tls_endpt_set_trusted_ca_paths(). Adding specific certificates
* is also performed only as an arbitrary identificator and later retrieved from
* callback set by ::nc_server_tls_set_trusted_cert_list_clb(). But, you can add
* certficates as whole lists, not one-by-one.
*
* Then, from each trusted client certificate a username must be derived
* for the NETCONF session. This is accomplished by finding a matching
* _cert-to-name_ entry. They are added using ::nc_server_tls_endpt_add_ctn().
*
* If you need to remove trusted certificates, you can do so with ::nc_server_tls_endpt_del_trusted_cert_list().
* To clear all Certificate Revocation Lists use ::nc_server_tls_endpt_clear_crls().
*
* Functions List
* --------------
*
* Available in __nc_server.h__.
*
* - ::nc_server_tls_endpt_set_server_cert()
* - ::nc_server_tls_endpt_add_trusted_cert_list()
* - ::nc_server_tls_endpt_del_trusted_cert_list()
* - ::nc_server_tls_endpt_set_trusted_ca_paths()
* - ::nc_server_tls_endpt_set_crl_paths()
* - ::nc_server_tls_endpt_clear_crls()
* - ::nc_server_tls_endpt_add_ctn()
* - ::nc_server_tls_endpt_del_ctn()
* - ::nc_server_tls_endpt_get_ctn()
*
* - ::nc_server_tls_set_server_cert_clb()
* - ::nc_server_tls_set_server_cert_chain_clb()
* - ::nc_server_tls_set_trusted_cert_list_clb()
*
* FD
* ==
*
* If you used a tunneling software, which does its own authentication,
* you can accept a NETCONF session on its file descriptors with
* ::nc_accept_inout().
*
* Functions List
* --------------
*
* Available in __nc_server.h__.
*
* - ::nc_accept_inout()
*
*
* Call Home
* =========
*
* _Call Home_ works with endpoints just like standard sessions, but
* the options are organized a bit differently and endpoints are added
* for CH clients. However, one important difference is that
* once all the mandatory options are set, _libnetconf2_ __will not__
* immediately start connecting to a client. It will do so only after
* calling ::nc_connect_ch_client_dispatch() in a separate thread.
*
* Lastly, monitoring of these sessions is up to the application.
*
* Functions List
* --------------
*
* Available in __nc_server.h__.
*
* - ::nc_server_ch_add_client()
* - ::nc_server_ch_del_client()
* - ::nc_server_ch_is_client()
* - ::nc_server_ch_client_add_endpt()
* - ::nc_server_ch_client_del_endpt()
* - ::nc_server_ch_client_is_endpt()
* - ::nc_server_ch_client_endpt_set_address()
* - ::nc_server_ch_client_endpt_set_port()
* - ::nc_server_ch_client_endpt_enable_keepalives()
* - ::nc_server_ch_client_endpt_set_keepalives()
* - ::nc_server_ch_client_set_conn_type()
* - ::nc_server_ch_client_periodic_set_period()
* - ::nc_server_ch_client_periodic_set_anchor_time()
* - ::nc_server_ch_client_periodic_set_idle_timeout()
* - ::nc_server_ch_client_set_start_with()
* - ::nc_server_ch_client_set_max_attempts()
* - ::nc_connect_ch_client_dispatch()
*
* - ::nc_server_ssh_ch_client_endpt_add_hostkey()
* - ::nc_server_ssh_ch_client_endpt_del_hostkey()
* - ::nc_server_ssh_ch_client_endpt_mov_hostkey()
* - ::nc_server_ssh_ch_client_endpt_set_auth_methods()
* - ::nc_server_ssh_ch_client_endpt_get_auth_methods()
* - ::nc_server_ssh_ch_client_endpt_set_auth_attempts()
* - ::nc_server_ssh_ch_client_endpt_set_auth_timeout()
*
* - ::nc_server_tls_ch_client_endpt_set_server_cert()
* - ::nc_server_tls_ch_client_endpt_add_trusted_cert_list()
* - ::nc_server_tls_ch_client_endpt_del_trusted_cert_list()
* - ::nc_server_tls_ch_client_endpt_set_trusted_ca_paths()
* - ::nc_server_tls_ch_client_endpt_set_crl_paths()
* - ::nc_server_tls_ch_client_endpt_clear_crls()
* - ::nc_server_tls_ch_client_endpt_add_ctn()
* - ::nc_server_tls_ch_client_endpt_del_ctn()
* - ::nc_server_tls_ch_client_endpt_get_ctn()
*
*
* Connecting And Cleanup
* ======================
*
* When accepting connections with ::nc_accept(), all the endpoints are examined
* and the first with a pending connection is used. To remove all CH clients,
* endpoints, and free any used dynamic memory, [destroy](@ref howtoinit) the server.
*
* Functions List
* --------------
*
* Available in __nc_server.h__.
*
* - ::nc_accept()
*/
/**
* @page howtoclientcomm Client communication
*
* To send RPCs on a session, you simply create an RPC, send it using ::nc_send_rpc(),
* and then wait for a reply using ::nc_recv_reply(). If you are subscribed, there are 2 ways
* of receiving notifications. Either you wait for them the same way
* as for standard replies with ::nc_recv_notif() or you create a dispatcher
* with ::nc_recv_notif_dispatch() that asynchronously (in a separate thread)
* reads notifications and passes them to your callback.
*
* Functions List
* --------------
*
* Available in __nc_client.h__.
*
* - ::nc_rpc_act_generic()
* - ::nc_rpc_act_generic_xml()
* - ::nc_rpc_getconfig()
* - ::nc_rpc_edit()
* - ::nc_rpc_copy()
* - ::nc_rpc_delete()
* - ::nc_rpc_lock()
* - ::nc_rpc_unlock()
* - ::nc_rpc_get()
* - ::nc_rpc_kill()
* - ::nc_rpc_commit()
* - ::nc_rpc_discard()
* - ::nc_rpc_cancel()
* - ::nc_rpc_validate()
* - ::nc_rpc_getschema()
* - ::nc_rpc_subscribe()
* - ::nc_rpc_getdata()
* - ::nc_rpc_editdata()
* - ::nc_rpc_establishsub()
* - ::nc_rpc_modifysub()
* - ::nc_rpc_deletesub()
* - ::nc_rpc_killsub()
* - ::nc_rpc_establishpush_periodic()
* - ::nc_rpc_establishpush_onchange()
* - ::nc_rpc_modifypush_periodic()
* - ::nc_rpc_modifypush_onchange()
* - ::nc_rpc_resyncsub()
*
* - ::nc_send_rpc()
* - ::nc_recv_reply()
* - ::nc_recv_notif()
* - ::nc_recv_notif_dispatch()
*/
/**
* @page howtoservercomm Server communication
*
* Once at least one session is established, an nc_pollsession structure
* should be created with ::nc_ps_new(), filled with the session using
* ::nc_ps_add_session() and finally polled with ::nc_ps_poll(). Based on
* the return value from the poll, further actions can be taken. More
* sessions can be polled at the same time and any requests received on
* the sessions are [handled internally](@ref howtoserver).
*
* If an SSH NETCONF session asks for a new channel, you can accept
* this request with ::nc_ps_accept_ssh_channel() or ::nc_session_accept_ssh_channel()
* depending on the structure you want to use as the argument.
*
* Functions List
* --------------
*
* Available in __nc_server.h__.
*
* - ::nc_ps_new()
* - ::nc_ps_add_session()
* - ::nc_ps_del_session()
* - ::nc_ps_session_count()
* - ::nc_ps_free()
*
* - ::nc_ps_poll()
* - ::nc_ps_clear()
* - ::nc_ps_accept_ssh_channel()
* - ::nc_session_accept_ssh_channel()
*/
/**
* @page howtotimeouts Timeouts
*
* There are several timeouts which are used throughout _libnetconf2_ to
* assure that it will never indefinitely hang on any operation. Normally,
* you should not need to worry about them much necause they are set by
* default to reasonable values for common systems. However, if your
* platform is not common (embedded, ...), adjusting these timeouts may
* save a lot of debugging and time.
*
* Compile Options
* ---------------
*
* You can adjust active and inactive read timeout using `cmake` variables.
* For details look into `README.md`.
*
* API Functions
* -------------
*
* Once a new connection is established including transport protocol negotiations,
* _hello_ message is exchanged. You can set how long will the server wait for
* receiving this message from a client before dropping it.
*
* Having a NETCONF session working, it may not communicate for a longer time.
* To free up some resources, it is possible to adjust the maximum idle period
* of a session before it is disconnected. In _Call Home_, for both a persistent
* and periodic connection can this idle timeout be specified separately for each
* client using corresponding functions.
*
* Lastly, SSH user authentication timeout can be also modified. It is the time
* a client has to successfully authenticate after connecting before it is disconnected.
*
* Functions List
* --------------
*
* Available in __nc_server.h__.
*
* - ::nc_server_set_hello_timeout()
* - ::nc_server_get_hello_timeout()
* - ::nc_server_set_idle_timeout()
* - ::nc_server_get_idle_timeout()
* - ::nc_server_ch_client_periodic_set_idle_timeout()
* - ::nc_server_ssh_ch_client_endpt_set_auth_timeout()
* - ::nc_server_ssh_ch_client_endpt_set_auth_timeout()
*/
/**
* @defgroup misc Miscellaneous
* @brief Miscellaneous macros, types, structure and functions for a generic use by both server and client applications.
*/
/**
* @defgroup client Client
* @brief NETCONF client functionality.
*/
/**
* @defgroup server Server
* @brief NETCONF server functionality.
*/
#endif /* NC_LIBNETCONF_H_ */
|
wungad/libnetconf2 | src/messages_server.c | /**
* \file messages_server.c
* \author <NAME> <<EMAIL>>
* \brief libnetconf2 - server NETCONF messages functions
*
* Copyright (c) 2015 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*/
#include <ctype.h>
#include <inttypes.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <libyang/libyang.h>
#include "compat.h"
#include "libnetconf.h"
#include "session_server.h"
extern struct nc_server_opts server_opts;
API struct nc_server_reply *
nc_server_reply_ok(void)
{
struct nc_server_reply *ret;
ret = malloc(sizeof *ret);
if (!ret) {
ERRMEM;
return NULL;
}
ret->type = NC_RPL_OK;
return ret;
}
API struct nc_server_reply *
nc_server_reply_data(struct lyd_node *data, NC_WD_MODE wd, NC_PARAMTYPE paramtype)
{
struct nc_server_reply_data *ret;
if (!data) {
ERRARG("data");
return NULL;
}
ret = malloc(sizeof *ret);
if (!ret) {
ERRMEM;
return NULL;
}
ret->type = NC_RPL_DATA;
ret->wd = wd;
if (paramtype == NC_PARAMTYPE_DUP_AND_FREE) {
if (lyd_dup_single(data, NULL, LYD_DUP_RECURSIVE, &ret->data)) {
free(ret);
return NULL;
}
} else {
ret->data = data;
}
if (paramtype != NC_PARAMTYPE_CONST) {
ret->free = 1;
} else {
ret->free = 0;
}
return (struct nc_server_reply *)ret;
}
API struct nc_server_reply *
nc_server_reply_err(struct lyd_node *err)
{
struct nc_server_reply_error *ret;
if (!err) {
ERRARG("err");
return NULL;
}
ret = malloc(sizeof *ret);
if (!ret) {
ERRMEM;
return NULL;
}
ret->type = NC_RPL_ERROR;
ret->err = err;
return (struct nc_server_reply *)ret;
}
API int
nc_server_reply_add_err(struct nc_server_reply *reply, struct lyd_node *err)
{
struct nc_server_reply_error *err_rpl;
if (!reply || (reply->type != NC_RPL_ERROR)) {
ERRARG("reply");
return -1;
} else if (!err) {
ERRARG("err");
return -1;
}
err_rpl = (struct nc_server_reply_error *)reply;
lyd_insert_sibling(err_rpl->err, err, &err_rpl->err);
return 0;
}
API const struct lyd_node *
nc_server_reply_get_last_err(const struct nc_server_reply *reply)
{
struct nc_server_reply_error *err_rpl;
if (!reply || (reply->type != NC_RPL_ERROR)) {
ERRARG("reply");
return NULL;
}
err_rpl = (struct nc_server_reply_error *)reply;
if (!err_rpl->err) {
return NULL;
}
return err_rpl->err->prev;
}
static const char *
nc_err_tag2str(NC_ERR tag)
{
switch (tag) {
case NC_ERR_IN_USE:
return "in-use";
case NC_ERR_INVALID_VALUE:
return "invalid-value";
case NC_ERR_ACCESS_DENIED:
return "access-denied";
case NC_ERR_ROLLBACK_FAILED:
return "rollback-failed";
case NC_ERR_OP_NOT_SUPPORTED:
return "operation-not-supported";
case NC_ERR_TOO_BIG:
return "too-big";
case NC_ERR_RES_DENIED:
return "resource-denied";
case NC_ERR_MISSING_ATTR:
return "missing-attribute";
case NC_ERR_BAD_ATTR:
return "bad-attribute";
case NC_ERR_UNKNOWN_ATTR:
return "unknown-attribute";
case NC_ERR_MISSING_ELEM:
return "missing-element";
case NC_ERR_BAD_ELEM:
return "bad-element";
case NC_ERR_UNKNOWN_ELEM:
return "unknown-element";
case NC_ERR_UNKNOWN_NS:
return "unknown-namespace";
case NC_ERR_LOCK_DENIED:
return "lock-denied";
case NC_ERR_DATA_EXISTS:
return "data-exists";
case NC_ERR_DATA_MISSING:
return "data-missing";
case NC_ERR_OP_FAILED:
return "operation-failed";
case NC_ERR_MALFORMED_MSG:
return "malformed-message";
default:
break;
}
return NULL;
}
static NC_ERR
nc_err_str2tag(const char *str)
{
if (!strcmp(str, "in-use")) {
return NC_ERR_IN_USE;
} else if (!strcmp(str, "invalid-value")) {
return NC_ERR_INVALID_VALUE;
} else if (!strcmp(str, "access-denied")) {
return NC_ERR_ACCESS_DENIED;
} else if (!strcmp(str, "rollback-failed")) {
return NC_ERR_ROLLBACK_FAILED;
} else if (!strcmp(str, "operation-not-supported")) {
return NC_ERR_OP_NOT_SUPPORTED;
} else if (!strcmp(str, "too-big")) {
return NC_ERR_TOO_BIG;
} else if (!strcmp(str, "resource-denied")) {
return NC_ERR_RES_DENIED;
} else if (!strcmp(str, "missing-attribute")) {
return NC_ERR_MISSING_ATTR;
} else if (!strcmp(str, "bad-attribute")) {
return NC_ERR_BAD_ATTR;
} else if (!strcmp(str, "unknown-attribute")) {
return NC_ERR_UNKNOWN_ATTR;
} else if (!strcmp(str, "missing-element")) {
return NC_ERR_MISSING_ELEM;
} else if (!strcmp(str, "bad-element")) {
return NC_ERR_BAD_ELEM;
} else if (!strcmp(str, "unknown-element")) {
return NC_ERR_UNKNOWN_ELEM;
} else if (!strcmp(str, "unknown-namespace")) {
return NC_ERR_UNKNOWN_NS;
} else if (!strcmp(str, "lock-denied")) {
return NC_ERR_LOCK_DENIED;
} else if (!strcmp(str, "data-exists")) {
return NC_ERR_DATA_EXISTS;
} else if (!strcmp(str, "data-missing")) {
return NC_ERR_DATA_MISSING;
} else if (!strcmp(str, "operation-failed")) {
return NC_ERR_OP_FAILED;
} else if (!strcmp(str, "malformed-message")) {
return NC_ERR_MALFORMED_MSG;
}
return 0;
}
static const char *
nc_err_type2str(NC_ERR_TYPE type)
{
switch (type) {
case NC_ERR_TYPE_TRAN:
return "transport";
case NC_ERR_TYPE_RPC:
return "rpc";
case NC_ERR_TYPE_PROT:
return "protocol";
case NC_ERR_TYPE_APP:
return "application";
default:
break;
}
return NULL;
}
static NC_ERR_TYPE
nc_err_str2type(const char *str)
{
if (!strcmp(str, "transport")) {
return NC_ERR_TYPE_TRAN;
} else if (!strcmp(str, "rpc")) {
return NC_ERR_TYPE_RPC;
} else if (!strcmp(str, "protocol")) {
return NC_ERR_TYPE_PROT;
} else if (!strcmp(str, "application")) {
return NC_ERR_TYPE_APP;
}
return 0;
}
API struct lyd_node *
nc_err(const struct ly_ctx *ctx, NC_ERR tag, ...)
{
va_list ap;
struct lyd_node *err = NULL;
NC_ERR_TYPE type;
const char *arg1, *arg2;
uint32_t sid;
if (!tag) {
ERRARG("tag");
return NULL;
}
/* rpc-error */
if (lyd_new_opaq2(NULL, ctx, "rpc-error", NULL, NULL, NC_NS_BASE, &err)) {
return NULL;
}
va_start(ap, tag);
/* error-type */
switch (tag) {
case NC_ERR_IN_USE:
case NC_ERR_INVALID_VALUE:
case NC_ERR_ACCESS_DENIED:
case NC_ERR_ROLLBACK_FAILED:
case NC_ERR_OP_NOT_SUPPORTED:
type = (NC_ERR_TYPE)va_arg(ap, int); /* NC_ERR_TYPE enum is automatically promoted to int */
if ((type != NC_ERR_TYPE_PROT) && (type != NC_ERR_TYPE_APP)) {
ERRARG("type");
goto fail;
}
break;
case NC_ERR_TOO_BIG:
case NC_ERR_RES_DENIED:
type = (NC_ERR_TYPE)va_arg(ap, int);
break;
case NC_ERR_MISSING_ATTR:
case NC_ERR_BAD_ATTR:
case NC_ERR_UNKNOWN_ATTR:
type = (NC_ERR_TYPE)va_arg(ap, int);
if (type == NC_ERR_TYPE_TRAN) {
ERRARG("type");
goto fail;
}
break;
case NC_ERR_MISSING_ELEM:
case NC_ERR_BAD_ELEM:
case NC_ERR_UNKNOWN_ELEM:
type = (NC_ERR_TYPE)va_arg(ap, int);
if ((type != NC_ERR_TYPE_PROT) && (type != NC_ERR_TYPE_APP)) {
ERRARG("type");
goto fail;
}
break;
case NC_ERR_UNKNOWN_NS:
type = (NC_ERR_TYPE)va_arg(ap, int);
if ((type != NC_ERR_TYPE_PROT) && (type != NC_ERR_TYPE_APP)) {
ERRARG("type");
goto fail;
}
break;
case NC_ERR_LOCK_DENIED:
type = NC_ERR_TYPE_PROT;
break;
case NC_ERR_DATA_EXISTS:
case NC_ERR_DATA_MISSING:
type = NC_ERR_TYPE_APP;
break;
case NC_ERR_OP_FAILED:
type = (NC_ERR_TYPE)va_arg(ap, int);
if (type == NC_ERR_TYPE_TRAN) {
ERRARG("type");
goto fail;
}
break;
case NC_ERR_MALFORMED_MSG:
type = NC_ERR_TYPE_RPC;
break;
default:
ERRARG("tag");
goto fail;
}
if (lyd_new_opaq2(err, NULL, "error-type", nc_err_type2str(type), NULL, NC_NS_BASE, NULL)) {
goto fail;
}
/* error-tag */
if (lyd_new_opaq2(err, NULL, "error-tag", nc_err_tag2str(tag), NULL, NC_NS_BASE, NULL)) {
goto fail;
}
/* error-severity */
if (lyd_new_opaq2(err, NULL, "error-severity", "error", NULL, NC_NS_BASE, NULL)) {
goto fail;
}
/* error-message */
switch (tag) {
case NC_ERR_IN_USE:
nc_err_set_msg(err, "The request requires a resource that already is in use.", "en");
break;
case NC_ERR_INVALID_VALUE:
nc_err_set_msg(err, "The request specifies an unacceptable value for one or more parameters.", "en");
break;
case NC_ERR_TOO_BIG:
nc_err_set_msg(err, "The request or response (that would be generated) is too large for the implementation to handle.", "en");
break;
case NC_ERR_MISSING_ATTR:
nc_err_set_msg(err, "An expected attribute is missing.", "en");
break;
case NC_ERR_BAD_ATTR:
nc_err_set_msg(err, "An attribute value is not correct.", "en");
break;
case NC_ERR_UNKNOWN_ATTR:
nc_err_set_msg(err, "An unexpected attribute is present.", "en");
break;
case NC_ERR_MISSING_ELEM:
nc_err_set_msg(err, "An expected element is missing.", "en");
break;
case NC_ERR_BAD_ELEM:
nc_err_set_msg(err, "An element value is not correct.", "en");
break;
case NC_ERR_UNKNOWN_ELEM:
nc_err_set_msg(err, "An unexpected element is present.", "en");
break;
case NC_ERR_UNKNOWN_NS:
nc_err_set_msg(err, "An unexpected namespace is present.", "en");
break;
case NC_ERR_ACCESS_DENIED:
nc_err_set_msg(err, "Access to the requested protocol operation or data model is denied because authorization failed.", "en");
break;
case NC_ERR_LOCK_DENIED:
nc_err_set_msg(err, "Access to the requested lock is denied because the lock is currently held by another entity.", "en");
break;
case NC_ERR_RES_DENIED:
nc_err_set_msg(err, "Request could not be completed because of insufficient resources.", "en");
break;
case NC_ERR_ROLLBACK_FAILED:
nc_err_set_msg(err, "Request to roll back some configuration change was not completed for some reason.", "en");
break;
case NC_ERR_DATA_EXISTS:
nc_err_set_msg(err, "Request could not be completed because the relevant data model content already exists.", "en");
break;
case NC_ERR_DATA_MISSING:
nc_err_set_msg(err, "Request could not be completed because the relevant data model content does not exist.", "en");
break;
case NC_ERR_OP_NOT_SUPPORTED:
nc_err_set_msg(err, "Request could not be completed because the requested operation is not supported by this implementation.", "en");
break;
case NC_ERR_OP_FAILED:
nc_err_set_msg(err, "Request could not be completed because the requested operation failed for a non-specific reason.", "en");
break;
case NC_ERR_MALFORMED_MSG:
nc_err_set_msg(err, "A message could not be handled because it failed to be parsed correctly.", "en");
break;
default:
ERRARG("tag");
goto fail;
}
/* error-info */
switch (tag) {
case NC_ERR_IN_USE:
case NC_ERR_INVALID_VALUE:
case NC_ERR_ACCESS_DENIED:
case NC_ERR_ROLLBACK_FAILED:
case NC_ERR_OP_NOT_SUPPORTED:
case NC_ERR_TOO_BIG:
case NC_ERR_RES_DENIED:
case NC_ERR_DATA_EXISTS:
case NC_ERR_DATA_MISSING:
case NC_ERR_OP_FAILED:
case NC_ERR_MALFORMED_MSG:
break;
case NC_ERR_MISSING_ATTR:
case NC_ERR_BAD_ATTR:
case NC_ERR_UNKNOWN_ATTR:
arg1 = va_arg(ap, const char *);
arg2 = va_arg(ap, const char *);
nc_err_add_bad_attr(err, arg1);
nc_err_add_bad_elem(err, arg2);
break;
case NC_ERR_MISSING_ELEM:
case NC_ERR_BAD_ELEM:
case NC_ERR_UNKNOWN_ELEM:
arg1 = va_arg(ap, const char *);
nc_err_add_bad_elem(err, arg1);
break;
case NC_ERR_UNKNOWN_NS:
arg1 = va_arg(ap, const char *);
arg2 = va_arg(ap, const char *);
nc_err_add_bad_elem(err, arg1);
nc_err_add_bad_ns(err, arg2);
break;
case NC_ERR_LOCK_DENIED:
sid = va_arg(ap, uint32_t);
nc_err_set_sid(err, sid);
break;
default:
ERRARG("tag");
goto fail;
}
va_end(ap);
return err;
fail:
va_end(ap);
lyd_free_siblings(err);
return NULL;
}
API NC_ERR_TYPE
nc_err_get_type(const struct lyd_node *err)
{
struct lyd_node *match;
if (!err) {
ERRARG("err");
return 0;
}
lyd_find_sibling_opaq_next(lyd_child(err), "error-type", &match);
if (match) {
return nc_err_str2type(((struct lyd_node_opaq *)match)->value);
}
return 0;
}
API NC_ERR
nc_err_get_tag(const struct lyd_node *err)
{
struct lyd_node *match;
if (!err) {
ERRARG("err");
return 0;
}
lyd_find_sibling_opaq_next(lyd_child(err), "error-tag", &match);
if (match) {
return nc_err_str2tag(((struct lyd_node_opaq *)match)->value);
}
return 0;
}
API int
nc_err_set_app_tag(struct lyd_node *err, const char *error_app_tag)
{
struct lyd_node *match;
if (!err) {
ERRARG("err");
return -1;
} else if (!error_app_tag) {
ERRARG("error_app_tag");
return -1;
}
/* remove previous node */
lyd_find_sibling_opaq_next(lyd_child(err), "error-app-tag", &match);
if (match) {
lyd_free_tree(match);
}
if (lyd_new_opaq2(err, NULL, "error-app-tag", error_app_tag, NULL, NC_NS_BASE, NULL)) {
return -1;
}
return 0;
}
API const char *
nc_err_get_app_tag(const struct lyd_node *err)
{
struct lyd_node *match;
if (!err) {
ERRARG("err");
return NULL;
}
lyd_find_sibling_opaq_next(lyd_child(err), "error-app-tag", &match);
if (match) {
return ((struct lyd_node_opaq *)match)->value;
}
return NULL;
}
API int
nc_err_set_path(struct lyd_node *err, const char *error_path)
{
struct lyd_node *match;
if (!err) {
ERRARG("err");
return -1;
} else if (!error_path) {
ERRARG("error_path");
return -1;
}
/* remove previous node */
lyd_find_sibling_opaq_next(lyd_child(err), "error-path", &match);
if (match) {
lyd_free_tree(match);
}
if (lyd_new_opaq2(err, NULL, "error-path", error_path, NULL, NC_NS_BASE, NULL)) {
return -1;
}
return 0;
}
API const char *
nc_err_get_path(const struct lyd_node *err)
{
struct lyd_node *match;
if (!err) {
ERRARG("err");
return 0;
}
lyd_find_sibling_opaq_next(lyd_child(err), "error-path", &match);
if (match) {
return ((struct lyd_node_opaq *)match)->value;
}
return NULL;
}
API int
nc_err_set_msg(struct lyd_node *err, const char *error_message, const char *lang)
{
struct lyd_node *match;
struct lyd_attr *attr;
if (!err) {
ERRARG("err");
return -1;
} else if (!error_message) {
ERRARG("error_message");
return -1;
}
/* remove previous message */
lyd_find_sibling_opaq_next(lyd_child(err), "error-message", &match);
if (match) {
lyd_free_tree(match);
}
if (lyd_new_opaq2(err, NULL, "error-message", error_message, NULL, NC_NS_BASE, &match)) {
return -1;
}
if (lang && lyd_new_attr(match, NULL, "xml:lang", lang, &attr)) {
lyd_free_tree(match);
return -1;
}
return 0;
}
API const char *
nc_err_get_msg(const struct lyd_node *err)
{
struct lyd_node *match;
if (!err) {
ERRARG("err");
return NULL;
}
lyd_find_sibling_opaq_next(lyd_child(err), "error-message", &match);
if (match) {
return ((struct lyd_node_opaq *)match)->value;
}
return NULL;
}
API int
nc_err_set_sid(struct lyd_node *err, uint32_t session_id)
{
struct lyd_node *match, *info;
char buf[22];
if (!err) {
ERRARG("err");
return -1;
}
/* find error-info */
lyd_find_sibling_opaq_next(lyd_child(err), "error-info", &info);
if (!info && lyd_new_opaq2(err, NULL, "error-info", NULL, NULL, NC_NS_BASE, &info)) {
return -1;
}
/* remove previous node */
lyd_find_sibling_opaq_next(lyd_child(info), "session-id", &match);
if (match) {
lyd_free_tree(match);
}
sprintf(buf, "%" PRIu32, session_id);
if (lyd_new_opaq2(info, NULL, "session-id", buf, NULL, NC_NS_BASE, NULL)) {
return -1;
}
return 0;
}
API int
nc_err_add_bad_attr(struct lyd_node *err, const char *attr_name)
{
struct lyd_node *info;
if (!err) {
ERRARG("err");
return -1;
} else if (!attr_name) {
ERRARG("attr_name");
return -1;
}
/* find error-info */
lyd_find_sibling_opaq_next(lyd_child(err), "error-info", &info);
if (!info && lyd_new_opaq2(err, NULL, "error-info", NULL, NULL, NC_NS_BASE, &info)) {
return -1;
}
if (lyd_new_opaq2(info, NULL, "bad-attribute", attr_name, NULL, NC_NS_BASE, NULL)) {
return -1;
}
return 0;
}
API int
nc_err_add_bad_elem(struct lyd_node *err, const char *elem_name)
{
struct lyd_node *info;
if (!err) {
ERRARG("err");
return -1;
} else if (!elem_name) {
ERRARG("elem_name");
return -1;
}
/* find error-info */
lyd_find_sibling_opaq_next(lyd_child(err), "error-info", &info);
if (!info && lyd_new_opaq2(err, NULL, "error-info", NULL, NULL, NC_NS_BASE, &info)) {
return -1;
}
if (lyd_new_opaq2(info, NULL, "bad-element", elem_name, NULL, NC_NS_BASE, NULL)) {
return -1;
}
return 0;
}
API int
nc_err_add_bad_ns(struct lyd_node *err, const char *ns_name)
{
struct lyd_node *info;
if (!err) {
ERRARG("err");
return -1;
} else if (!ns_name) {
ERRARG("ns_name");
return -1;
}
/* find error-info */
lyd_find_sibling_opaq_next(lyd_child(err), "error-info", &info);
if (!info && lyd_new_opaq2(err, NULL, "error-info", NULL, NULL, NC_NS_BASE, &info)) {
return -1;
}
if (lyd_new_opaq2(info, NULL, "bad-namespace", ns_name, NULL, NC_NS_BASE, NULL)) {
return -1;
}
return 0;
}
API int
nc_err_add_info_other(struct lyd_node *err, struct lyd_node *other)
{
struct lyd_node *info;
if (!err) {
ERRARG("err");
return -1;
} else if (!other) {
ERRARG("other");
return -1;
}
/* find error-info */
lyd_find_sibling_opaq_next(lyd_child(err), "error-info", &info);
if (!info && lyd_new_opaq2(err, NULL, "error-info", NULL, NULL, NC_NS_BASE, &info)) {
return -1;
}
lyd_insert_child(info, other);
return 0;
}
void
nc_server_rpc_free(struct nc_server_rpc *rpc)
{
if (!rpc) {
return;
}
lyd_free_tree(rpc->envp);
/* may be action */
lyd_free_all(rpc->rpc);
free(rpc);
}
API void
nc_server_reply_free(struct nc_server_reply *reply)
{
struct nc_server_reply_data *data_rpl;
struct nc_server_reply_error *error_rpl;
if (!reply) {
return;
}
switch (reply->type) {
case NC_RPL_DATA:
data_rpl = (struct nc_server_reply_data *)reply;
if (data_rpl->free) {
lyd_free_siblings(data_rpl->data);
}
break;
case NC_RPL_OK:
/* nothing to free */
break;
case NC_RPL_ERROR:
error_rpl = (struct nc_server_reply_error *)reply;
lyd_free_siblings(error_rpl->err);
break;
default:
break;
}
free(reply);
}
API struct nc_server_notif *
nc_server_notif_new(struct lyd_node *event, char *eventtime, NC_PARAMTYPE paramtype)
{
struct nc_server_notif *ntf;
struct lyd_node *elem;
int found;
if (!event) {
ERRARG("event");
return NULL;
} else if (!eventtime) {
ERRARG("eventtime");
return NULL;
}
/* check that there is a notification */
found = 0;
LYD_TREE_DFS_BEGIN(event, elem) {
if (elem->schema->nodetype == LYS_NOTIF) {
found = 1;
break;
}
LYD_TREE_DFS_END(event, elem);
}
if (!found) {
ERRARG("event");
return NULL;
}
ntf = malloc(sizeof *ntf);
if (paramtype == NC_PARAMTYPE_DUP_AND_FREE) {
ntf->eventtime = strdup(eventtime);
if (lyd_dup_single(event, NULL, LYD_DUP_RECURSIVE, &ntf->ntf)) {
free(ntf);
return NULL;
}
} else {
ntf->eventtime = eventtime;
ntf->ntf = event;
}
ntf->free = (paramtype == NC_PARAMTYPE_CONST ? 0 : 1);
return ntf;
}
API void
nc_server_notif_free(struct nc_server_notif *notif)
{
if (!notif) {
return;
}
if (notif->free) {
lyd_free_tree(notif->ntf);
free(notif->eventtime);
}
free(notif);
}
API const char *
nc_server_notif_get_time(const struct nc_server_notif *notif)
{
if (!notif) {
ERRARG("notif");
return NULL;
}
return notif->eventtime;
}
|
wungad/libnetconf2 | tests/client/test_client.c | #include <errno.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <cmocka.h>
#include <libyang/libyang.h>
#include <log.h>
#include <session_client.h>
#include "tests/config.h"
static int
setup_f(void **state)
{
(void)state;
nc_verbosity(NC_VERB_VERBOSE);
return 0;
}
static int
teardown_f(void **state)
{
(void)state;
return 0;
}
static void
test_nc_client_setting_schema_searchpath(void **state)
{
(void)state;
const char *path;
int ret;
/* initiate client */
nc_client_init();
path = nc_client_get_schema_searchpath();
assert_null(path);
ret = nc_client_set_schema_searchpath("path");
assert_int_equal(ret, 0);
path = nc_client_get_schema_searchpath();
assert_string_equal(path, "path");
ret = nc_client_set_schema_searchpath("path1");
assert_int_equal(ret, 0);
path = nc_client_get_schema_searchpath();
assert_string_equal(path, "path1");
}
LY_ERR
test_clb(const char *mod_name, const char *mod_rev, const char *submod_name, const char *sub_rev, void *user_data,
LYS_INFORMAT *format, const char **model_data, void (**free_module_data)(void *model_data, void *user_data))
{
(void)mod_name;
(void)mod_rev;
(void)submod_name;
(void)sub_rev;
(void)user_data;
(void)format;
(void)model_data;
(void)free_module_data;
return LY_SUCCESS;
}
LY_ERR
test_clb1(const char *mod_name, const char *mod_rev, const char *submod_name, const char *sub_rev, void *user_data,
LYS_INFORMAT *format, const char **model_data, void (**free_module_data)(void *model_data, void *user_data))
{
(void)mod_name;
(void)mod_rev;
(void)submod_name;
(void)sub_rev;
(void)user_data;
(void)format;
(void)model_data;
(void)free_module_data;
return LY_SUCCESS;
}
static void
test_nc_client_setting_schema_callback(void **state)
{
(void)state;
ly_module_imp_clb ret_f;
char *data_ret;
int ret;
ret_f = nc_client_get_schema_callback((void **)&data_ret);
assert_null(ret_f);
assert_null(data_ret);
ret = nc_client_set_schema_callback(test_clb, "DATA");
assert_int_equal(ret, 0);
ret_f = nc_client_get_schema_callback((void **)&data_ret);
assert_ptr_equal(test_clb, ret_f);
assert_string_equal("DATA", data_ret);
ret = nc_client_set_schema_callback(test_clb1, "DATA1");
assert_int_equal(ret, 0);
ret_f = nc_client_get_schema_callback((void **)&data_ret);
assert_ptr_equal(test_clb1, ret_f);
assert_string_equal("DATA1", data_ret);
/* destroy client */
nc_client_destroy();
}
int
main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test_setup_teardown(test_nc_client_setting_schema_searchpath, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_client_setting_schema_callback, setup_f, teardown_f),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
|
wungad/libnetconf2 | src/log_p.h | <reponame>wungad/libnetconf2
/**
* @file log.h
* @author <NAME> <<EMAIL>>
* @brief libnetconf2 logger
*
* Copyright (c) 2015 - 2021 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*/
#ifndef NC_LOG_PRIVATE_H_
#define NC_LOG_PRIVATE_H_
#include <stdint.h>
#include "log.h"
/*
* libnetconf's message printing
*/
/**
* @brief Internal printing function
*
* @param[in] session Optional NETCONF session that generated the message
* @param[in] level Verbose level
* @param[in] format Formatting string
*/
void prv_printf(const struct nc_session *session, NC_VERB_LEVEL level, const char *format, ...);
/**
* @brief Verbose level variable
*/
extern volatile uint8_t verbose_level;
/*
* Verbose printing macros
*/
#define ERR(session, format, args ...) prv_printf(session,NC_VERB_ERROR,format,##args)
#define WRN(session, format, args ...) if(verbose_level>=NC_VERB_WARNING){prv_printf(session,NC_VERB_WARNING,format,##args);}
#define VRB(session, format, args ...) if(verbose_level>=NC_VERB_VERBOSE){prv_printf(session,NC_VERB_VERBOSE,format,##args);}
#define DBG(session, format, args ...) if(verbose_level>=NC_VERB_DEBUG){prv_printf(session,NC_VERB_DEBUG,format,##args);}
#define DBL(session, format, args ...) if(verbose_level>=NC_VERB_DEBUG_LOWLVL){prv_printf(session,NC_VERB_DEBUG_LOWLVL,format,##args);}
#define ERRMEM ERR(NULL, "%s: memory reallocation failed (%s:%d).", __func__, __FILE__, __LINE__)
#define ERRARG(arg) ERR(NULL, "%s: invalid argument (%s).", __func__, arg)
#define ERRINIT ERR(NULL, "%s: libnetconf2 not initialized.", __func__)
#define ERRINT ERR(NULL, "%s: internal error (%s:%d).", __func__, __FILE__, __LINE__)
#endif /* NC_LOG_PRIVATE_H_ */
|
wungad/libnetconf2 | modules/ietf_netconf_monitoring@2010-10-04_yang.h | char ietf_netconf_monitoring_2010_10_04_yang[] = {
0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x20, 0x69, 0x65, 0x74, 0x66, 0x2d,
0x6e, 0x65, 0x74, 0x63, 0x6f, 0x6e, 0x66, 0x2d, 0x6d, 0x6f, 0x6e, 0x69,
0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x20, 0x7b, 0x0a, 0x0a, 0x20, 0x20,
0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x22, 0x75,
0x72, 0x6e, 0x3a, 0x69, 0x65, 0x74, 0x66, 0x3a, 0x70, 0x61, 0x72, 0x61,
0x6d, 0x73, 0x3a, 0x78, 0x6d, 0x6c, 0x3a, 0x6e, 0x73, 0x3a, 0x79, 0x61,
0x6e, 0x67, 0x3a, 0x69, 0x65, 0x74, 0x66, 0x2d, 0x6e, 0x65, 0x74, 0x63,
0x6f, 0x6e, 0x66, 0x2d, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69,
0x6e, 0x67, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x70, 0x72, 0x65, 0x66, 0x69,
0x78, 0x20, 0x22, 0x6e, 0x63, 0x6d, 0x22, 0x3b, 0x0a, 0x0a, 0x20, 0x20,
0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x20, 0x69, 0x65, 0x74, 0x66, 0x2d,
0x79, 0x61, 0x6e, 0x67, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x73, 0x20, 0x7b,
0x20, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x20, 0x79, 0x61, 0x6e, 0x67,
0x3b, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74,
0x20, 0x69, 0x65, 0x74, 0x66, 0x2d, 0x69, 0x6e, 0x65, 0x74, 0x2d, 0x74,
0x79, 0x70, 0x65, 0x73, 0x20, 0x7b, 0x20, 0x70, 0x72, 0x65, 0x66, 0x69,
0x78, 0x20, 0x69, 0x6e, 0x65, 0x74, 0x3b, 0x20, 0x7d, 0x0a, 0x0a, 0x20,
0x20, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f,
0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x49, 0x45, 0x54, 0x46, 0x20,
0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20, 0x28, 0x4e, 0x65, 0x74,
0x77, 0x6f, 0x72, 0x6b, 0x20, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75,
0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x29, 0x20, 0x57, 0x6f, 0x72, 0x6b,
0x69, 0x6e, 0x67, 0x20, 0x47, 0x72, 0x6f, 0x75, 0x70, 0x22, 0x3b, 0x0a,
0x0a, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x63, 0x74, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x22, 0x57, 0x47, 0x20, 0x57, 0x65, 0x62, 0x3a, 0x20,
0x20, 0x20, 0x3c, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x74, 0x6f,
0x6f, 0x6c, 0x73, 0x2e, 0x69, 0x65, 0x74, 0x66, 0x2e, 0x6f, 0x72, 0x67,
0x2f, 0x77, 0x67, 0x2f, 0x6e, 0x65, 0x74, 0x63, 0x6f, 0x6e, 0x66, 0x2f,
0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x57, 0x47, 0x20, 0x4c, 0x69,
0x73, 0x74, 0x3a, 0x20, 0x20, 0x3c, 0x6d, 0x61, 0x69, 0x6c, 0x74, 0x6f,
0x3a, 0x6e, 0x65, 0x74, 0x63, 0x6f, 0x6e, 0x66, 0x40, 0x69, 0x65, 0x74,
0x66, 0x2e, 0x6f, 0x72, 0x67, 0x3e, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x57, 0x47, 0x20, 0x43, 0x68, 0x61, 0x69, 0x72, 0x3a, 0x20, 0x4d,
0x65, 0x68, 0x6d, 0x65, 0x74, 0x20, 0x45, 0x72, 0x73, 0x75, 0x65, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x3c, 0x6d, 0x61, 0x69, 0x6c, 0x74, 0x6f, 0x3a, 0x6d,
0x65, 0x68, 0x6d, 0x65, 0x74, 0x2e, 0x65, 0x72, 0x73, 0x75, 0x65, 0x40,
0x6e, 0x73, 0x6e, 0x2e, 0x63, 0x6f, 0x6d, 0x3e, 0x0a, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x57, 0x47, 0x20, 0x43, 0x68, 0x61, 0x69, 0x72, 0x3a,
0x20, 0x42, 0x65, 0x72, 0x74, 0x20, 0x57, 0x69, 0x6a, 0x6e, 0x65, 0x6e,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x3c, 0x6d, 0x61, 0x69, 0x6c, 0x74, 0x6f, 0x3a,
0x62, 0x65, 0x72, 0x74, 0x69, 0x65, 0x74, 0x66, 0x40, 0x62, 0x77, 0x69,
0x6a, 0x6e, 0x65, 0x6e, 0x2e, 0x6e, 0x65, 0x74, 0x3e, 0x0a, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x45, 0x64, 0x69, 0x74, 0x6f, 0x72, 0x3a, 0x20,
0x20, 0x20, 0x4d, 0x61, 0x72, 0x6b, 0x20, 0x53, 0x63, 0x6f, 0x74, 0x74,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x3c, 0x6d, 0x61, 0x69, 0x6c, 0x74, 0x6f, 0x3a,
0x6d, 0x61, 0x72, 0x6b, 0x2e, 0x73, 0x63, 0x6f, 0x74, 0x74, 0x40, 0x65,
0x72, 0x69, 0x63, 0x73, 0x73, 0x6f, 0x6e, 0x2e, 0x63, 0x6f, 0x6d, 0x3e,
0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x45, 0x64, 0x69, 0x74, 0x6f,
0x72, 0x3a, 0x20, 0x20, 0x20, 0x4d, 0x61, 0x72, 0x74, 0x69, 0x6e, 0x20,
0x42, 0x6a, 0x6f, 0x72, 0x6b, 0x6c, 0x75, 0x6e, 0x64, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x3c, 0x6d, 0x61, 0x69, 0x6c, 0x74, 0x6f, 0x3a, 0x6d, 0x62, 0x6a,
0x40, 0x74, 0x61, 0x69, 0x6c, 0x2d, 0x66, 0x2e, 0x63, 0x6f, 0x6d, 0x3e,
0x22, 0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69,
0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x22, 0x4e,
0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20, 0x4d, 0x6f, 0x6e, 0x69, 0x74,
0x6f, 0x72, 0x69, 0x6e, 0x67, 0x20, 0x4d, 0x6f, 0x64, 0x75, 0x6c, 0x65,
0x2e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x41, 0x6c, 0x6c, 0x20, 0x65,
0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x20, 0x69, 0x6e, 0x20, 0x74,
0x68, 0x69, 0x73, 0x20, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x20, 0x61,
0x72, 0x65, 0x20, 0x72, 0x65, 0x61, 0x64, 0x2d, 0x6f, 0x6e, 0x6c, 0x79,
0x2e, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x43, 0x6f, 0x70, 0x79,
0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x28, 0x63, 0x29, 0x20, 0x32, 0x30,
0x31, 0x30, 0x20, 0x49, 0x45, 0x54, 0x46, 0x20, 0x54, 0x72, 0x75, 0x73,
0x74, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x65,
0x72, 0x73, 0x6f, 0x6e, 0x73, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69,
0x66, 0x69, 0x65, 0x64, 0x20, 0x61, 0x73, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x73, 0x20, 0x6f, 0x66, 0x20,
0x74, 0x68, 0x65, 0x20, 0x63, 0x6f, 0x64, 0x65, 0x2e, 0x20, 0x41, 0x6c,
0x6c, 0x20, 0x72, 0x69, 0x67, 0x68, 0x74, 0x73, 0x20, 0x72, 0x65, 0x73,
0x65, 0x72, 0x76, 0x65, 0x64, 0x2e, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x52, 0x65, 0x64, 0x69, 0x73, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74,
0x69, 0x6f, 0x6e, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x75, 0x73, 0x65, 0x20,
0x69, 0x6e, 0x20, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x20, 0x61, 0x6e,
0x64, 0x20, 0x62, 0x69, 0x6e, 0x61, 0x72, 0x79, 0x20, 0x66, 0x6f, 0x72,
0x6d, 0x73, 0x2c, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x6f, 0x72, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x77, 0x69, 0x74, 0x68, 0x6f, 0x75, 0x74,
0x20, 0x6d, 0x6f, 0x64, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f,
0x6e, 0x2c, 0x20, 0x69, 0x73, 0x20, 0x70, 0x65, 0x72, 0x6d, 0x69, 0x74,
0x74, 0x65, 0x64, 0x20, 0x70, 0x75, 0x72, 0x73, 0x75, 0x61, 0x6e, 0x74,
0x20, 0x74, 0x6f, 0x2c, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x73, 0x75, 0x62,
0x6a, 0x65, 0x63, 0x74, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x6f,
0x20, 0x74, 0x68, 0x65, 0x20, 0x6c, 0x69, 0x63, 0x65, 0x6e, 0x73, 0x65,
0x20, 0x74, 0x65, 0x72, 0x6d, 0x73, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x61,
0x69, 0x6e, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x2c, 0x20, 0x74, 0x68, 0x65,
0x20, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x69, 0x66, 0x69, 0x65, 0x64, 0x20,
0x42, 0x53, 0x44, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x4c, 0x69, 0x63,
0x65, 0x6e, 0x73, 0x65, 0x20, 0x73, 0x65, 0x74, 0x20, 0x66, 0x6f, 0x72,
0x74, 0x68, 0x20, 0x69, 0x6e, 0x20, 0x53, 0x65, 0x63, 0x74, 0x69, 0x6f,
0x6e, 0x20, 0x34, 0x2e, 0x63, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65,
0x20, 0x49, 0x45, 0x54, 0x46, 0x20, 0x54, 0x72, 0x75, 0x73, 0x74, 0x27,
0x73, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x4c, 0x65, 0x67, 0x61, 0x6c,
0x20, 0x50, 0x72, 0x6f, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x20,
0x52, 0x65, 0x6c, 0x61, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x74, 0x6f, 0x20,
0x49, 0x45, 0x54, 0x46, 0x20, 0x44, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e,
0x74, 0x73, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x28, 0x68, 0x74, 0x74,
0x70, 0x3a, 0x2f, 0x2f, 0x74, 0x72, 0x75, 0x73, 0x74, 0x65, 0x65, 0x2e,
0x69, 0x65, 0x74, 0x66, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x6c, 0x69, 0x63,
0x65, 0x6e, 0x73, 0x65, 0x2d, 0x69, 0x6e, 0x66, 0x6f, 0x29, 0x2e, 0x0a,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x54, 0x68, 0x69, 0x73, 0x20, 0x76,
0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68,
0x69, 0x73, 0x20, 0x59, 0x41, 0x4e, 0x47, 0x20, 0x6d, 0x6f, 0x64, 0x75,
0x6c, 0x65, 0x20, 0x69, 0x73, 0x20, 0x70, 0x61, 0x72, 0x74, 0x20, 0x6f,
0x66, 0x20, 0x52, 0x46, 0x43, 0x20, 0x36, 0x30, 0x32, 0x32, 0x3b, 0x20,
0x73, 0x65, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x65,
0x20, 0x52, 0x46, 0x43, 0x20, 0x69, 0x74, 0x73, 0x65, 0x6c, 0x66, 0x20,
0x66, 0x6f, 0x72, 0x20, 0x66, 0x75, 0x6c, 0x6c, 0x20, 0x6c, 0x65, 0x67,
0x61, 0x6c, 0x20, 0x6e, 0x6f, 0x74, 0x69, 0x63, 0x65, 0x73, 0x2e, 0x22,
0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x72, 0x65, 0x76, 0x69, 0x73, 0x69, 0x6f,
0x6e, 0x20, 0x32, 0x30, 0x31, 0x30, 0x2d, 0x31, 0x30, 0x2d, 0x30, 0x34,
0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72,
0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x22, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x20, 0x72, 0x65,
0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x52, 0x46, 0x43, 0x20, 0x36,
0x30, 0x32, 0x32, 0x3a, 0x20, 0x59, 0x41, 0x4e, 0x47, 0x20, 0x4d, 0x6f,
0x64, 0x75, 0x6c, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x4e, 0x45, 0x54,
0x43, 0x4f, 0x4e, 0x46, 0x20, 0x4d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72,
0x69, 0x6e, 0x67, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x7d, 0x0a, 0x0a, 0x20,
0x20, 0x74, 0x79, 0x70, 0x65, 0x64, 0x65, 0x66, 0x20, 0x6e, 0x65, 0x74,
0x63, 0x6f, 0x6e, 0x66, 0x2d, 0x64, 0x61, 0x74, 0x61, 0x73, 0x74, 0x6f,
0x72, 0x65, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x20, 0x7b, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x65, 0x6e, 0x75, 0x6d, 0x65,
0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x65, 0x6e, 0x75, 0x6d, 0x20, 0x72, 0x75, 0x6e, 0x6e,
0x69, 0x6e, 0x67, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x65,
0x6e, 0x75, 0x6d, 0x20, 0x63, 0x61, 0x6e, 0x64, 0x69, 0x64, 0x61, 0x74,
0x65, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x65, 0x6e, 0x75,
0x6d, 0x20, 0x73, 0x74, 0x61, 0x72, 0x74, 0x75, 0x70, 0x3b, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73,
0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x22, 0x45, 0x6e, 0x75, 0x6d, 0x65, 0x72, 0x61, 0x74,
0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x70, 0x6f, 0x73, 0x73, 0x69,
0x62, 0x6c, 0x65, 0x20, 0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20,
0x64, 0x61, 0x74, 0x61, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x20, 0x74, 0x79,
0x70, 0x65, 0x73, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72,
0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x22, 0x52, 0x46, 0x43, 0x20, 0x34, 0x37, 0x34, 0x31,
0x3a, 0x20, 0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20, 0x43, 0x6f,
0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20,
0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x3b, 0x0a, 0x20,
0x20, 0x7d, 0x0a, 0x0a, 0x20, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69,
0x74, 0x79, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74,
0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72,
0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x22, 0x42, 0x61, 0x73, 0x65, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74,
0x69, 0x74, 0x79, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x4e, 0x45, 0x54, 0x43,
0x4f, 0x4e, 0x46, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72,
0x74, 0x20, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e, 0x22, 0x3b, 0x0a, 0x20,
0x20, 0x7d, 0x0a, 0x0a, 0x20, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69,
0x74, 0x79, 0x20, 0x6e, 0x65, 0x74, 0x63, 0x6f, 0x6e, 0x66, 0x2d, 0x73,
0x73, 0x68, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x62, 0x61, 0x73,
0x65, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x3b,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70,
0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22,
0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20, 0x6f, 0x76, 0x65, 0x72,
0x20, 0x53, 0x65, 0x63, 0x75, 0x72, 0x65, 0x20, 0x53, 0x68, 0x65, 0x6c,
0x6c, 0x20, 0x28, 0x53, 0x53, 0x48, 0x29, 0x2e, 0x22, 0x3b, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x52, 0x46, 0x43, 0x20,
0x34, 0x37, 0x34, 0x32, 0x3a, 0x20, 0x55, 0x73, 0x69, 0x6e, 0x67, 0x20,
0x74, 0x68, 0x65, 0x20, 0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20,
0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f,
0x6e, 0x20, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x6f, 0x76, 0x65, 0x72, 0x20, 0x53, 0x65, 0x63,
0x75, 0x72, 0x65, 0x20, 0x53, 0x48, 0x65, 0x6c, 0x6c, 0x20, 0x28, 0x53,
0x53, 0x48, 0x29, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x7d, 0x0a, 0x0a, 0x20,
0x20, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x20, 0x6e, 0x65,
0x74, 0x63, 0x6f, 0x6e, 0x66, 0x2d, 0x73, 0x6f, 0x61, 0x70, 0x2d, 0x6f,
0x76, 0x65, 0x72, 0x2d, 0x62, 0x65, 0x65, 0x70, 0x20, 0x7b, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x62, 0x61, 0x73, 0x65, 0x20, 0x74, 0x72, 0x61, 0x6e,
0x73, 0x70, 0x6f, 0x72, 0x74, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x64,
0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e,
0x46, 0x20, 0x6f, 0x76, 0x65, 0x72, 0x20, 0x53, 0x69, 0x6d, 0x70, 0x6c,
0x65, 0x20, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x20, 0x41, 0x63, 0x63,
0x65, 0x73, 0x73, 0x20, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c,
0x20, 0x28, 0x53, 0x4f, 0x41, 0x50, 0x29, 0x20, 0x6f, 0x76, 0x65, 0x72,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x42, 0x6c, 0x6f, 0x63,
0x6b, 0x73, 0x20, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73, 0x69, 0x62, 0x6c,
0x65, 0x20, 0x45, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x20, 0x50,
0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x20, 0x28, 0x42, 0x45, 0x45,
0x50, 0x29, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65,
0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x22, 0x52, 0x46, 0x43, 0x20, 0x34, 0x37, 0x34, 0x33, 0x3a,
0x20, 0x55, 0x73, 0x69, 0x6e, 0x67, 0x20, 0x4e, 0x45, 0x54, 0x43, 0x4f,
0x4e, 0x46, 0x20, 0x6f, 0x76, 0x65, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20,
0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x20, 0x4f, 0x62, 0x6a, 0x65, 0x63,
0x74, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x41, 0x63, 0x63, 0x65, 0x73,
0x73, 0x20, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x20, 0x28,
0x53, 0x4f, 0x41, 0x50, 0x29, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x7d, 0x0a,
0x0a, 0x20, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x20,
0x6e, 0x65, 0x74, 0x63, 0x6f, 0x6e, 0x66, 0x2d, 0x73, 0x6f, 0x61, 0x70,
0x2d, 0x6f, 0x76, 0x65, 0x72, 0x2d, 0x68, 0x74, 0x74, 0x70, 0x73, 0x20,
0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x62, 0x61, 0x73, 0x65, 0x20, 0x74,
0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x3b, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f,
0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x4e, 0x45, 0x54,
0x43, 0x4f, 0x4e, 0x46, 0x20, 0x6f, 0x76, 0x65, 0x72, 0x20, 0x53, 0x69,
0x6d, 0x70, 0x6c, 0x65, 0x20, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x20,
0x41, 0x63, 0x63, 0x65, 0x73, 0x73, 0x20, 0x50, 0x72, 0x6f, 0x74, 0x6f,
0x63, 0x6f, 0x6c, 0x20, 0x28, 0x53, 0x4f, 0x41, 0x50, 0x29, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x76, 0x65, 0x72, 0x20, 0x48, 0x79,
0x70, 0x65, 0x72, 0x74, 0x65, 0x78, 0x74, 0x20, 0x54, 0x72, 0x61, 0x6e,
0x73, 0x66, 0x65, 0x72, 0x20, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f,
0x6c, 0x20, 0x53, 0x65, 0x63, 0x75, 0x72, 0x65, 0x20, 0x28, 0x48, 0x54,
0x54, 0x50, 0x53, 0x29, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x22, 0x52, 0x46, 0x43, 0x20, 0x34, 0x37, 0x34,
0x33, 0x3a, 0x20, 0x55, 0x73, 0x69, 0x6e, 0x67, 0x20, 0x4e, 0x45, 0x54,
0x43, 0x4f, 0x4e, 0x46, 0x20, 0x6f, 0x76, 0x65, 0x72, 0x20, 0x74, 0x68,
0x65, 0x20, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x20, 0x4f, 0x62, 0x6a,
0x65, 0x63, 0x74, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x41, 0x63, 0x63,
0x65, 0x73, 0x73, 0x20, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c,
0x20, 0x28, 0x53, 0x4f, 0x41, 0x50, 0x29, 0x22, 0x3b, 0x0a, 0x20, 0x20,
0x7d, 0x0a, 0x0a, 0x20, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74,
0x79, 0x20, 0x6e, 0x65, 0x74, 0x63, 0x6f, 0x6e, 0x66, 0x2d, 0x62, 0x65,
0x65, 0x70, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x62, 0x61, 0x73,
0x65, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x3b,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70,
0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22,
0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20, 0x6f, 0x76, 0x65, 0x72,
0x20, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x20, 0x45, 0x78, 0x74, 0x65,
0x6e, 0x73, 0x69, 0x62, 0x6c, 0x65, 0x20, 0x45, 0x78, 0x63, 0x68, 0x61,
0x6e, 0x67, 0x65, 0x20, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c,
0x20, 0x28, 0x42, 0x45, 0x45, 0x50, 0x29, 0x2e, 0x22, 0x3b, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x52, 0x46, 0x43, 0x20,
0x34, 0x37, 0x34, 0x34, 0x3a, 0x20, 0x55, 0x73, 0x69, 0x6e, 0x67, 0x20,
0x74, 0x68, 0x65, 0x20, 0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20,
0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x20, 0x6f, 0x76, 0x65,
0x72, 0x20, 0x74, 0x68, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x42,
0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x20, 0x45, 0x78, 0x74, 0x65, 0x6e, 0x73,
0x69, 0x62, 0x6c, 0x65, 0x20, 0x45, 0x78, 0x63, 0x68, 0x61, 0x6e, 0x67,
0x65, 0x20, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x20, 0x28,
0x42, 0x45, 0x45, 0x50, 0x29, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x7d, 0x0a,
0x0a, 0x20, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x20,
0x6e, 0x65, 0x74, 0x63, 0x6f, 0x6e, 0x66, 0x2d, 0x74, 0x6c, 0x73, 0x20,
0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x62, 0x61, 0x73, 0x65, 0x20, 0x74,
0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x3b, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f,
0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x4e, 0x45, 0x54,
0x43, 0x4f, 0x4e, 0x46, 0x20, 0x6f, 0x76, 0x65, 0x72, 0x20, 0x54, 0x72,
0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x20, 0x4c, 0x61, 0x79, 0x65,
0x72, 0x20, 0x53, 0x65, 0x63, 0x75, 0x72, 0x69, 0x74, 0x79, 0x20, 0x28,
0x54, 0x4c, 0x53, 0x29, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x22, 0x52, 0x46, 0x43, 0x20, 0x35, 0x35, 0x33,
0x39, 0x3a, 0x20, 0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20, 0x6f,
0x76, 0x65, 0x72, 0x20, 0x54, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72,
0x74, 0x20, 0x4c, 0x61, 0x79, 0x65, 0x72, 0x20, 0x53, 0x65, 0x63, 0x75,
0x72, 0x69, 0x74, 0x79, 0x20, 0x28, 0x54, 0x4c, 0x53, 0x29, 0x22, 0x3b,
0x0a, 0x20, 0x20, 0x7d, 0x0a, 0x0a, 0x20, 0x20, 0x69, 0x64, 0x65, 0x6e,
0x74, 0x69, 0x74, 0x79, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x2d,
0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x42, 0x61, 0x73, 0x65,
0x20, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x20, 0x66, 0x6f,
0x72, 0x20, 0x64, 0x61, 0x74, 0x61, 0x20, 0x6d, 0x6f, 0x64, 0x65, 0x6c,
0x20, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x20, 0x6c, 0x61, 0x6e, 0x67,
0x75, 0x61, 0x67, 0x65, 0x73, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x7d,
0x0a, 0x0a, 0x20, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79,
0x20, 0x78, 0x73, 0x64, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x62,
0x61, 0x73, 0x65, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x2d, 0x66,
0x6f, 0x72, 0x6d, 0x61, 0x74, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x64,
0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x57, 0x33, 0x43, 0x20, 0x58, 0x4d,
0x4c, 0x20, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x20, 0x44, 0x65, 0x66,
0x69, 0x6e, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x22, 0x3b, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x57, 0x33, 0x43, 0x20,
0x52, 0x45, 0x43, 0x20, 0x52, 0x45, 0x43, 0x2d, 0x78, 0x6d, 0x6c, 0x73,
0x63, 0x68, 0x65, 0x6d, 0x61, 0x2d, 0x31, 0x2d, 0x32, 0x30, 0x30, 0x34,
0x31, 0x30, 0x32, 0x38, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x58, 0x4d, 0x4c, 0x20, 0x53, 0x63, 0x68, 0x65, 0x6d,
0x61, 0x20, 0x50, 0x61, 0x72, 0x74, 0x20, 0x31, 0x3a, 0x20, 0x53, 0x74,
0x72, 0x75, 0x63, 0x74, 0x75, 0x72, 0x65, 0x73, 0x22, 0x3b, 0x0a, 0x20,
0x20, 0x7d, 0x0a, 0x0a, 0x20, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69,
0x74, 0x79, 0x20, 0x79, 0x61, 0x6e, 0x67, 0x20, 0x7b, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x62, 0x61, 0x73, 0x65, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d,
0x61, 0x2d, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x3b, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f,
0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x54, 0x68, 0x65,
0x20, 0x59, 0x41, 0x4e, 0x47, 0x20, 0x64, 0x61, 0x74, 0x61, 0x20, 0x6d,
0x6f, 0x64, 0x65, 0x6c, 0x69, 0x6e, 0x67, 0x20, 0x6c, 0x61, 0x6e, 0x67,
0x75, 0x61, 0x67, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x4e, 0x45, 0x54,
0x43, 0x4f, 0x4e, 0x46, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x22, 0x52, 0x46, 0x43, 0x20, 0x36, 0x30, 0x32,
0x30, 0x3a, 0x20, 0x20, 0x59, 0x41, 0x4e, 0x47, 0x20, 0x2d, 0x20, 0x41,
0x20, 0x44, 0x61, 0x74, 0x61, 0x20, 0x4d, 0x6f, 0x64, 0x65, 0x6c, 0x69,
0x6e, 0x67, 0x20, 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x20,
0x66, 0x6f, 0x72, 0x20, 0x74, 0x68, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x20, 0x43, 0x6f,
0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20,
0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x20, 0x28, 0x4e, 0x45,
0x54, 0x43, 0x4f, 0x4e, 0x46, 0x29, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x7d,
0x0a, 0x0a, 0x20, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79,
0x20, 0x79, 0x69, 0x6e, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x62,
0x61, 0x73, 0x65, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x2d, 0x66,
0x6f, 0x72, 0x6d, 0x61, 0x74, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x64,
0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x54, 0x68, 0x65, 0x20, 0x59, 0x49,
0x4e, 0x20, 0x73, 0x79, 0x6e, 0x74, 0x61, 0x78, 0x20, 0x66, 0x6f, 0x72,
0x20, 0x59, 0x41, 0x4e, 0x47, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x52, 0x46, 0x43, 0x20, 0x36, 0x30,
0x32, 0x30, 0x3a, 0x20, 0x20, 0x59, 0x41, 0x4e, 0x47, 0x20, 0x2d, 0x20,
0x41, 0x20, 0x44, 0x61, 0x74, 0x61, 0x20, 0x4d, 0x6f, 0x64, 0x65, 0x6c,
0x69, 0x6e, 0x67, 0x20, 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65,
0x20, 0x66, 0x6f, 0x72, 0x20, 0x74, 0x68, 0x65, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x20, 0x43,
0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e,
0x20, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x20, 0x28, 0x4e,
0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x29, 0x22, 0x3b, 0x0a, 0x20, 0x20,
0x7d, 0x0a, 0x0a, 0x20, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74,
0x79, 0x20, 0x72, 0x6e, 0x67, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x62, 0x61, 0x73, 0x65, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x2d,
0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x52, 0x65, 0x67, 0x75, 0x6c,
0x61, 0x72, 0x20, 0x4c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x20,
0x66, 0x6f, 0x72, 0x20, 0x58, 0x4d, 0x4c, 0x20, 0x4e, 0x65, 0x78, 0x74,
0x20, 0x47, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20,
0x28, 0x52, 0x45, 0x4c, 0x41, 0x58, 0x20, 0x4e, 0x47, 0x29, 0x2e, 0x22,
0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65,
0x6e, 0x63, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x49,
0x53, 0x4f, 0x2f, 0x49, 0x45, 0x43, 0x20, 0x31, 0x39, 0x37, 0x35, 0x37,
0x2d, 0x32, 0x3a, 0x32, 0x30, 0x30, 0x38, 0x3a, 0x20, 0x52, 0x45, 0x4c,
0x41, 0x58, 0x20, 0x4e, 0x47, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x7d, 0x0a,
0x0a, 0x20, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x20,
0x72, 0x6e, 0x63, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x62, 0x61,
0x73, 0x65, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x2d, 0x66, 0x6f,
0x72, 0x6d, 0x61, 0x74, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65,
0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x22, 0x52, 0x65, 0x6c, 0x61, 0x78, 0x20, 0x4e,
0x47, 0x20, 0x43, 0x6f, 0x6d, 0x70, 0x61, 0x63, 0x74, 0x20, 0x53, 0x79,
0x6e, 0x74, 0x61, 0x78, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72,
0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x22, 0x49, 0x53, 0x4f, 0x2f, 0x49, 0x45, 0x43, 0x20,
0x31, 0x39, 0x37, 0x35, 0x37, 0x2d, 0x32, 0x3a, 0x32, 0x30, 0x30, 0x38,
0x3a, 0x20, 0x52, 0x45, 0x4c, 0x41, 0x58, 0x20, 0x4e, 0x47, 0x22, 0x3b,
0x0a, 0x20, 0x20, 0x7d, 0x0a, 0x0a, 0x20, 0x20, 0x67, 0x72, 0x6f, 0x75,
0x70, 0x69, 0x6e, 0x67, 0x20, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x2d,
0x63, 0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x73, 0x20, 0x7b, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69,
0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x43, 0x6f,
0x75, 0x6e, 0x74, 0x65, 0x72, 0x73, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20,
0x65, 0x78, 0x69, 0x73, 0x74, 0x20, 0x62, 0x6f, 0x74, 0x68, 0x20, 0x70,
0x65, 0x72, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x2c, 0x20,
0x61, 0x6e, 0x64, 0x20, 0x61, 0x6c, 0x73, 0x6f, 0x20, 0x67, 0x6c, 0x6f,
0x62, 0x61, 0x6c, 0x6c, 0x79, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x61, 0x63, 0x63, 0x75, 0x6d, 0x75, 0x6c, 0x61, 0x74, 0x65,
0x64, 0x20, 0x66, 0x72, 0x6f, 0x6d, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x73,
0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x22, 0x3b, 0x0a, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x6c, 0x65, 0x61, 0x66, 0x20, 0x69, 0x6e, 0x2d,
0x72, 0x70, 0x63, 0x73, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x79, 0x61, 0x6e, 0x67, 0x3a, 0x7a,
0x65, 0x72, 0x6f, 0x2d, 0x62, 0x61, 0x73, 0x65, 0x64, 0x2d, 0x63, 0x6f,
0x75, 0x6e, 0x74, 0x65, 0x72, 0x33, 0x32, 0x3b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69,
0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22,
0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x20, 0x6f, 0x66, 0x20, 0x63, 0x6f,
0x72, 0x72, 0x65, 0x63, 0x74, 0x20, 0x3c, 0x72, 0x70, 0x63, 0x3e, 0x20,
0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x20, 0x72, 0x65, 0x63,
0x65, 0x69, 0x76, 0x65, 0x64, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x65, 0x61, 0x66, 0x20,
0x69, 0x6e, 0x2d, 0x62, 0x61, 0x64, 0x2d, 0x72, 0x70, 0x63, 0x73, 0x20,
0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x79, 0x70, 0x65,
0x20, 0x79, 0x61, 0x6e, 0x67, 0x3a, 0x7a, 0x65, 0x72, 0x6f, 0x2d, 0x62,
0x61, 0x73, 0x65, 0x64, 0x2d, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72,
0x33, 0x32, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65,
0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x4e, 0x75, 0x6d, 0x62, 0x65,
0x72, 0x20, 0x6f, 0x66, 0x20, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65,
0x73, 0x20, 0x72, 0x65, 0x63, 0x65, 0x69, 0x76, 0x65, 0x64, 0x20, 0x77,
0x68, 0x65, 0x6e, 0x20, 0x61, 0x6e, 0x20, 0x3c, 0x72, 0x70, 0x63, 0x3e,
0x20, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x20, 0x77, 0x61, 0x73,
0x20, 0x65, 0x78, 0x70, 0x65, 0x63, 0x74, 0x65, 0x64, 0x2c, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x61, 0x74,
0x20, 0x77, 0x65, 0x72, 0x65, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x63, 0x6f,
0x72, 0x72, 0x65, 0x63, 0x74, 0x20, 0x3c, 0x72, 0x70, 0x63, 0x3e, 0x20,
0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x2e, 0x20, 0x20, 0x54,
0x68, 0x69, 0x73, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x73,
0x20, 0x58, 0x4d, 0x4c, 0x20, 0x70, 0x61, 0x72, 0x73, 0x65, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x65, 0x72, 0x72, 0x6f,
0x72, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x65, 0x72, 0x72, 0x6f, 0x72,
0x73, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20, 0x72, 0x70, 0x63,
0x20, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x65, 0x61, 0x66,
0x20, 0x6f, 0x75, 0x74, 0x2d, 0x72, 0x70, 0x63, 0x2d, 0x65, 0x72, 0x72,
0x6f, 0x72, 0x73, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x74, 0x79, 0x70, 0x65, 0x20, 0x79, 0x61, 0x6e, 0x67, 0x3a, 0x7a, 0x65,
0x72, 0x6f, 0x2d, 0x62, 0x61, 0x73, 0x65, 0x64, 0x2d, 0x63, 0x6f, 0x75,
0x6e, 0x74, 0x65, 0x72, 0x33, 0x32, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f,
0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x4e,
0x75, 0x6d, 0x62, 0x65, 0x72, 0x20, 0x6f, 0x66, 0x20, 0x3c, 0x72, 0x70,
0x63, 0x2d, 0x72, 0x65, 0x70, 0x6c, 0x79, 0x3e, 0x20, 0x6d, 0x65, 0x73,
0x73, 0x61, 0x67, 0x65, 0x73, 0x20, 0x73, 0x65, 0x6e, 0x74, 0x20, 0x74,
0x68, 0x61, 0x74, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65,
0x64, 0x20, 0x61, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x3c, 0x72, 0x70, 0x63, 0x2d, 0x65, 0x72, 0x72, 0x6f, 0x72,
0x3e, 0x20, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x2e, 0x22, 0x3b,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x6c,
0x65, 0x61, 0x66, 0x20, 0x6f, 0x75, 0x74, 0x2d, 0x6e, 0x6f, 0x74, 0x69,
0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x7b, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x79,
0x61, 0x6e, 0x67, 0x3a, 0x7a, 0x65, 0x72, 0x6f, 0x2d, 0x62, 0x61, 0x73,
0x65, 0x64, 0x2d, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x33, 0x32,
0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63,
0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x22, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x20,
0x6f, 0x66, 0x20, 0x3c, 0x6e, 0x6f, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61,
0x74, 0x69, 0x6f, 0x6e, 0x3e, 0x20, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67,
0x65, 0x73, 0x20, 0x73, 0x65, 0x6e, 0x74, 0x2e, 0x22, 0x3b, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x7d, 0x0a, 0x0a, 0x20, 0x20,
0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x20, 0x6e, 0x65,
0x74, 0x63, 0x6f, 0x6e, 0x66, 0x2d, 0x73, 0x74, 0x61, 0x74, 0x65, 0x20,
0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67,
0x20, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x54, 0x68, 0x65, 0x20, 0x6e,
0x65, 0x74, 0x63, 0x6f, 0x6e, 0x66, 0x2d, 0x73, 0x74, 0x61, 0x74, 0x65,
0x20, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x20, 0x69,
0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x72, 0x6f, 0x6f, 0x74, 0x20, 0x6f,
0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6d, 0x6f, 0x6e, 0x69, 0x74, 0x6f,
0x72, 0x69, 0x6e, 0x67, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x64, 0x61, 0x74, 0x61, 0x20, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x2e, 0x22,
0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x61,
0x69, 0x6e, 0x65, 0x72, 0x20, 0x63, 0x61, 0x70, 0x61, 0x62, 0x69, 0x6c,
0x69, 0x74, 0x69, 0x65, 0x73, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f,
0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x43,
0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20,
0x6c, 0x69, 0x73, 0x74, 0x20, 0x6f, 0x66, 0x20, 0x4e, 0x45, 0x54, 0x43,
0x4f, 0x4e, 0x46, 0x20, 0x63, 0x61, 0x70, 0x61, 0x62, 0x69, 0x6c, 0x69,
0x74, 0x69, 0x65, 0x73, 0x20, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74,
0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x74, 0x68, 0x65, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65,
0x72, 0x2e, 0x22, 0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x6c, 0x65, 0x61, 0x66, 0x2d, 0x6c, 0x69, 0x73, 0x74, 0x20, 0x63, 0x61,
0x70, 0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x20, 0x7b, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x20,
0x69, 0x6e, 0x65, 0x74, 0x3a, 0x75, 0x72, 0x69, 0x3b, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69,
0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x22, 0x4c, 0x69, 0x73, 0x74, 0x20, 0x6f, 0x66,
0x20, 0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20, 0x63, 0x61, 0x70,
0x61, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x69, 0x65, 0x73, 0x20, 0x73, 0x75,
0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x74,
0x68, 0x65, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2e, 0x22, 0x3b,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x7d, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x74,
0x61, 0x69, 0x6e, 0x65, 0x72, 0x20, 0x64, 0x61, 0x74, 0x61, 0x73, 0x74,
0x6f, 0x72, 0x65, 0x73, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x43, 0x6f,
0x6e, 0x74, 0x61, 0x69, 0x6e, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6c,
0x69, 0x73, 0x74, 0x20, 0x6f, 0x66, 0x20, 0x4e, 0x45, 0x54, 0x43, 0x4f,
0x4e, 0x46, 0x20, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61,
0x74, 0x69, 0x6f, 0x6e, 0x20, 0x64, 0x61, 0x74, 0x61, 0x73, 0x74, 0x6f,
0x72, 0x65, 0x73, 0x2e, 0x22, 0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x6c, 0x69, 0x73, 0x74, 0x20, 0x64, 0x61, 0x74, 0x61, 0x73,
0x74, 0x6f, 0x72, 0x65, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x6b, 0x65, 0x79, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x3b,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73,
0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x4c, 0x69, 0x73, 0x74,
0x20, 0x6f, 0x66, 0x20, 0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20,
0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f,
0x6e, 0x20, 0x64, 0x61, 0x74, 0x61, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x73,
0x20, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x20, 0x62,
0x79, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x74, 0x68, 0x65, 0x20, 0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46,
0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x61, 0x6e, 0x64, 0x20,
0x72, 0x65, 0x6c, 0x61, 0x74, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x66, 0x6f,
0x72, 0x6d, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x22, 0x3b, 0x0a, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x65, 0x61, 0x66,
0x20, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x6e,
0x65, 0x74, 0x63, 0x6f, 0x6e, 0x66, 0x2d, 0x64, 0x61, 0x74, 0x61, 0x73,
0x74, 0x6f, 0x72, 0x65, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x3b, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73,
0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x4e, 0x61,
0x6d, 0x65, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x64, 0x61,
0x74, 0x61, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x20, 0x61, 0x73, 0x73, 0x6f,
0x63, 0x69, 0x61, 0x74, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20,
0x74, 0x68, 0x69, 0x73, 0x20, 0x6c, 0x69, 0x73, 0x74, 0x20, 0x65, 0x6e,
0x74, 0x72, 0x79, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x20, 0x6c,
0x6f, 0x63, 0x6b, 0x73, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x70, 0x72, 0x65, 0x73, 0x65, 0x6e, 0x63,
0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x22, 0x54, 0x68, 0x69, 0x73, 0x20, 0x63, 0x6f, 0x6e, 0x74,
0x61, 0x69, 0x6e, 0x65, 0x72, 0x20, 0x69, 0x73, 0x20, 0x70, 0x72, 0x65,
0x73, 0x65, 0x6e, 0x74, 0x20, 0x6f, 0x6e, 0x6c, 0x79, 0x20, 0x69, 0x66,
0x20, 0x74, 0x68, 0x65, 0x20, 0x64, 0x61, 0x74, 0x61, 0x73, 0x74, 0x6f,
0x72, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x69, 0x73, 0x20, 0x6c, 0x6f, 0x63, 0x6b, 0x65,
0x64, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69,
0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x22, 0x54, 0x68, 0x65, 0x20, 0x4e, 0x45, 0x54, 0x43,
0x4f, 0x4e, 0x46, 0x20, 0x3c, 0x6c, 0x6f, 0x63, 0x6b, 0x3e, 0x20, 0x61,
0x6e, 0x64, 0x20, 0x3c, 0x70, 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, 0x2d,
0x6c, 0x6f, 0x63, 0x6b, 0x3e, 0x20, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74,
0x69, 0x6f, 0x6e, 0x73, 0x20, 0x61, 0x6c, 0x6c, 0x6f, 0x77, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x61, 0x20, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20,
0x6c, 0x6f, 0x63, 0x6b, 0x20, 0x73, 0x70, 0x65, 0x63, 0x69, 0x66, 0x69,
0x63, 0x20, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x20,
0x69, 0x6e, 0x20, 0x61, 0x20, 0x64, 0x61, 0x74, 0x61, 0x73, 0x74, 0x6f,
0x72, 0x65, 0x2e, 0x20, 0x20, 0x54, 0x68, 0x65, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x4e, 0x45,
0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72,
0x20, 0x77, 0x69, 0x6c, 0x6c, 0x20, 0x70, 0x72, 0x65, 0x76, 0x65, 0x6e,
0x74, 0x20, 0x63, 0x68, 0x61, 0x6e, 0x67, 0x65, 0x73, 0x20, 0x74, 0x6f,
0x20, 0x74, 0x68, 0x65, 0x20, 0x6c, 0x6f, 0x63, 0x6b, 0x65, 0x64, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x73, 0x20, 0x62,
0x79, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f,
0x6e, 0x73, 0x20, 0x65, 0x78, 0x63, 0x65, 0x70, 0x74, 0x20, 0x74, 0x68,
0x65, 0x20, 0x6f, 0x6e, 0x65, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x61,
0x63, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x65,
0x20, 0x6c, 0x6f, 0x63, 0x6b, 0x28, 0x73, 0x29, 0x2e, 0x0a, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x4d, 0x6f, 0x6e, 0x69, 0x74, 0x6f, 0x72, 0x69, 0x6e, 0x67, 0x20, 0x69,
0x6e, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x69,
0x73, 0x20, 0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x64, 0x20, 0x66,
0x6f, 0x72, 0x20, 0x65, 0x61, 0x63, 0x68, 0x20, 0x64, 0x61, 0x74, 0x61,
0x73, 0x74, 0x6f, 0x72, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x65, 0x6e, 0x74, 0x72, 0x79,
0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x69, 0x6e, 0x67, 0x20, 0x64,
0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x20, 0x73, 0x75, 0x63, 0x68, 0x20,
0x61, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69,
0x6f, 0x6e, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x61, 0x63, 0x71, 0x75,
0x69, 0x72, 0x65, 0x64, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6c, 0x6f,
0x63, 0x6b, 0x2c, 0x20, 0x74, 0x68, 0x65, 0x20, 0x74, 0x79, 0x70, 0x65,
0x20, 0x6f, 0x66, 0x20, 0x6c, 0x6f, 0x63, 0x6b, 0x20, 0x28, 0x67, 0x6c,
0x6f, 0x62, 0x61, 0x6c, 0x20, 0x6f, 0x72, 0x20, 0x70, 0x61, 0x72, 0x74,
0x69, 0x61, 0x6c, 0x29, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x74, 0x68, 0x65,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x6c, 0x69, 0x73, 0x74, 0x20, 0x6f, 0x66, 0x20, 0x6c, 0x6f,
0x63, 0x6b, 0x65, 0x64, 0x20, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63,
0x65, 0x73, 0x2e, 0x20, 0x20, 0x4d, 0x75, 0x6c, 0x74, 0x69, 0x70, 0x6c,
0x65, 0x20, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x20, 0x70, 0x65, 0x72, 0x20,
0x64, 0x61, 0x74, 0x61, 0x73, 0x74, 0x6f, 0x72, 0x65, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x61,
0x72, 0x65, 0x20, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64,
0x2e, 0x22, 0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x67, 0x72, 0x6f, 0x75, 0x70, 0x69, 0x6e, 0x67, 0x20,
0x6c, 0x6f, 0x63, 0x6b, 0x2d, 0x69, 0x6e, 0x66, 0x6f, 0x20, 0x7b, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x22, 0x4c, 0x6f, 0x63, 0x6b, 0x20, 0x72, 0x65, 0x6c, 0x61,
0x74, 0x65, 0x64, 0x20, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65,
0x72, 0x73, 0x2c, 0x20, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e, 0x20, 0x74,
0x6f, 0x20, 0x62, 0x6f, 0x74, 0x68, 0x20, 0x67, 0x6c, 0x6f, 0x62, 0x61,
0x6c, 0x20, 0x61, 0x6e, 0x64, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x70, 0x61, 0x72,
0x74, 0x69, 0x61, 0x6c, 0x20, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x2e, 0x22,
0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x6c, 0x65, 0x61, 0x66, 0x20, 0x6c, 0x6f, 0x63, 0x6b,
0x65, 0x64, 0x2d, 0x62, 0x79, 0x2d, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f,
0x6e, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x75,
0x69, 0x6e, 0x74, 0x33, 0x32, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6d, 0x61, 0x6e,
0x64, 0x61, 0x74, 0x6f, 0x72, 0x79, 0x20, 0x74, 0x72, 0x75, 0x65, 0x3b,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69,
0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x54, 0x68, 0x65, 0x20,
0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x49, 0x44, 0x20, 0x6f,
0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f,
0x6e, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x68, 0x61, 0x73, 0x20, 0x6c,
0x6f, 0x63, 0x6b, 0x65, 0x64, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74,
0x68, 0x69, 0x73, 0x20, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65,
0x2e, 0x20, 0x20, 0x42, 0x6f, 0x74, 0x68, 0x20, 0x61, 0x20, 0x67, 0x6c,
0x6f, 0x62, 0x61, 0x6c, 0x20, 0x6c, 0x6f, 0x63, 0x6b, 0x20, 0x61, 0x6e,
0x64, 0x20, 0x61, 0x20, 0x70, 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x6f, 0x63, 0x6b, 0x20, 0x4d, 0x55,
0x53, 0x54, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x20, 0x74,
0x68, 0x65, 0x20, 0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20, 0x73,
0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x2d, 0x69, 0x64, 0x2e, 0x0a, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x49, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20,
0x6c, 0x6f, 0x63, 0x6b, 0x20, 0x69, 0x73, 0x20, 0x68, 0x65, 0x6c, 0x64,
0x20, 0x62, 0x79, 0x20, 0x61, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f,
0x6e, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x69, 0x73, 0x20, 0x6e, 0x6f,
0x74, 0x20, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x62, 0x79, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4e, 0x45,
0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72,
0x20, 0x28, 0x65, 0x2e, 0x67, 0x2e, 0x2c, 0x20, 0x61, 0x20, 0x43, 0x4c,
0x49, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x29, 0x2c, 0x20,
0x61, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x69, 0x64, 0x20, 0x6f, 0x66, 0x20, 0x30, 0x20, 0x28,
0x7a, 0x65, 0x72, 0x6f, 0x29, 0x20, 0x69, 0x73, 0x20, 0x72, 0x65, 0x70,
0x6f, 0x72, 0x74, 0x65, 0x64, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72,
0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x22, 0x52, 0x46, 0x43, 0x20, 0x34, 0x37, 0x34, 0x31, 0x3a, 0x20,
0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20, 0x43, 0x6f, 0x6e, 0x66,
0x69, 0x67, 0x75, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x50, 0x72,
0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c,
0x65, 0x61, 0x66, 0x20, 0x6c, 0x6f, 0x63, 0x6b, 0x65, 0x64, 0x2d, 0x74,
0x69, 0x6d, 0x65, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x79, 0x70, 0x65,
0x20, 0x79, 0x61, 0x6e, 0x67, 0x3a, 0x64, 0x61, 0x74, 0x65, 0x2d, 0x61,
0x6e, 0x64, 0x2d, 0x74, 0x69, 0x6d, 0x65, 0x3b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6d,
0x61, 0x6e, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x79, 0x20, 0x74, 0x72, 0x75,
0x65, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70,
0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x54, 0x68,
0x65, 0x20, 0x64, 0x61, 0x74, 0x65, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x74,
0x69, 0x6d, 0x65, 0x20, 0x6f, 0x66, 0x20, 0x77, 0x68, 0x65, 0x6e, 0x20,
0x74, 0x68, 0x65, 0x20, 0x72, 0x65, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65,
0x20, 0x77, 0x61, 0x73, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x6f,
0x63, 0x6b, 0x65, 0x64, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x63, 0x68, 0x6f,
0x69, 0x63, 0x65, 0x20, 0x6c, 0x6f, 0x63, 0x6b, 0x2d, 0x74, 0x79, 0x70,
0x65, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74,
0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x49, 0x6e, 0x64, 0x69, 0x63,
0x61, 0x74, 0x65, 0x73, 0x20, 0x69, 0x66, 0x20, 0x61, 0x20, 0x67, 0x6c,
0x6f, 0x62, 0x61, 0x6c, 0x20, 0x6c, 0x6f, 0x63, 0x6b, 0x20, 0x6f, 0x72,
0x20, 0x61, 0x20, 0x73, 0x65, 0x74, 0x20, 0x6f, 0x66, 0x20, 0x70, 0x61,
0x72, 0x74, 0x69, 0x61, 0x6c, 0x20, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x61, 0x72, 0x65, 0x20, 0x73, 0x65, 0x74, 0x2e, 0x22,
0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72,
0x20, 0x67, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x2d, 0x6c, 0x6f, 0x63, 0x6b,
0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70,
0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x50, 0x72,
0x65, 0x73, 0x65, 0x6e, 0x74, 0x20, 0x69, 0x66, 0x20, 0x74, 0x68, 0x65,
0x20, 0x67, 0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x20, 0x6c, 0x6f, 0x63, 0x6b,
0x20, 0x69, 0x73, 0x20, 0x73, 0x65, 0x74, 0x2e, 0x22, 0x3b, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x75, 0x73, 0x65, 0x73, 0x20, 0x6c, 0x6f, 0x63, 0x6b, 0x2d, 0x69,
0x6e, 0x66, 0x6f, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x69, 0x73, 0x74,
0x20, 0x70, 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, 0x2d, 0x6c, 0x6f, 0x63,
0x6b, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6b, 0x65, 0x79, 0x20, 0x6c, 0x6f,
0x63, 0x6b, 0x2d, 0x69, 0x64, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73,
0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x22, 0x4c, 0x69, 0x73, 0x74, 0x20, 0x6f, 0x66, 0x20, 0x70, 0x61,
0x72, 0x74, 0x69, 0x61, 0x6c, 0x20, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x2e,
0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e,
0x63, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x52, 0x46, 0x43, 0x20,
0x35, 0x37, 0x31, 0x37, 0x3a, 0x20, 0x50, 0x61, 0x72, 0x74, 0x69, 0x61,
0x6c, 0x20, 0x4c, 0x6f, 0x63, 0x6b, 0x20, 0x52, 0x65, 0x6d, 0x6f, 0x74,
0x65, 0x20, 0x50, 0x72, 0x6f, 0x63, 0x65, 0x64, 0x75, 0x72, 0x65, 0x20,
0x43, 0x61, 0x6c, 0x6c, 0x20, 0x28, 0x52, 0x50, 0x43, 0x29, 0x20, 0x66,
0x6f, 0x72, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e,
0x46, 0x22, 0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x65, 0x61, 0x66, 0x20,
0x6c, 0x6f, 0x63, 0x6b, 0x2d, 0x69, 0x64, 0x20, 0x7b, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x75, 0x69, 0x6e, 0x74, 0x33,
0x32, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72,
0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x22, 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68,
0x65, 0x20, 0x6c, 0x6f, 0x63, 0x6b, 0x20, 0x69, 0x64, 0x20, 0x72, 0x65,
0x74, 0x75, 0x72, 0x6e, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68,
0x65, 0x20, 0x3c, 0x70, 0x61, 0x72, 0x74, 0x69, 0x61, 0x6c, 0x2d, 0x6c,
0x6f, 0x63, 0x6b, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x22, 0x3b, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x75, 0x73, 0x65, 0x73, 0x20, 0x6c,
0x6f, 0x63, 0x6b, 0x2d, 0x69, 0x6e, 0x66, 0x6f, 0x3b, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x6c, 0x65, 0x61, 0x66, 0x2d, 0x6c, 0x69, 0x73, 0x74, 0x20, 0x73, 0x65,
0x6c, 0x65, 0x63, 0x74, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74,
0x79, 0x70, 0x65, 0x20, 0x79, 0x61, 0x6e, 0x67, 0x3a, 0x78, 0x70, 0x61,
0x74, 0x68, 0x31, 0x2e, 0x30, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6d,
0x69, 0x6e, 0x2d, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x20,
0x31, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72,
0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x22, 0x54, 0x68, 0x65, 0x20, 0x78, 0x70, 0x61, 0x74, 0x68, 0x20,
0x65, 0x78, 0x70, 0x72, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x74,
0x68, 0x61, 0x74, 0x20, 0x77, 0x61, 0x73, 0x20, 0x75, 0x73, 0x65, 0x64,
0x20, 0x74, 0x6f, 0x20, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6c,
0x6f, 0x63, 0x6b, 0x2e, 0x20, 0x20, 0x54, 0x68, 0x65, 0x20, 0x73, 0x65,
0x6c, 0x65, 0x63, 0x74, 0x20, 0x65, 0x78, 0x70, 0x72, 0x65, 0x73, 0x73,
0x69, 0x6f, 0x6e, 0x20, 0x69, 0x6e, 0x64, 0x69, 0x63, 0x61, 0x74, 0x65,
0x73, 0x20, 0x74, 0x68, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x6f, 0x72, 0x69, 0x67, 0x69, 0x6e, 0x61, 0x6c, 0x20, 0x69, 0x6e,
0x74, 0x65, 0x6e, 0x64, 0x65, 0x64, 0x20, 0x73, 0x63, 0x6f, 0x70, 0x65,
0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6c, 0x6f, 0x63, 0x6b,
0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x65,
0x61, 0x66, 0x2d, 0x6c, 0x69, 0x73, 0x74, 0x20, 0x6c, 0x6f, 0x63, 0x6b,
0x65, 0x64, 0x2d, 0x6e, 0x6f, 0x64, 0x65, 0x20, 0x7b, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x69, 0x6e, 0x73, 0x74, 0x61,
0x6e, 0x63, 0x65, 0x2d, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69,
0x65, 0x72, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63,
0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x22, 0x54, 0x68, 0x65, 0x20, 0x6c, 0x69, 0x73, 0x74, 0x20,
0x6f, 0x66, 0x20, 0x69, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x2d,
0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x73, 0x20,
0x28, 0x69, 0x2e, 0x65, 0x2e, 0x2c, 0x20, 0x74, 0x68, 0x65, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x6f, 0x63, 0x6b, 0x65, 0x64,
0x20, 0x6e, 0x6f, 0x64, 0x65, 0x73, 0x29, 0x2e, 0x0a, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x54, 0x68, 0x65, 0x20, 0x73, 0x63, 0x6f,
0x70, 0x65, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x61,
0x72, 0x74, 0x69, 0x61, 0x6c, 0x20, 0x6c, 0x6f, 0x63, 0x6b, 0x20, 0x69,
0x73, 0x20, 0x64, 0x65, 0x66, 0x69, 0x6e, 0x65, 0x64, 0x20, 0x62, 0x79,
0x20, 0x74, 0x68, 0x65, 0x20, 0x6c, 0x69, 0x73, 0x74, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x6f, 0x66, 0x20, 0x6c, 0x6f, 0x63, 0x6b,
0x65, 0x64, 0x20, 0x6e, 0x6f, 0x64, 0x65, 0x73, 0x2e, 0x22, 0x3b, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63,
0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x20, 0x73, 0x63, 0x68,
0x65, 0x6d, 0x61, 0x73, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x43, 0x6f,
0x6e, 0x74, 0x61, 0x69, 0x6e, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6c,
0x69, 0x73, 0x74, 0x20, 0x6f, 0x66, 0x20, 0x64, 0x61, 0x74, 0x61, 0x20,
0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61,
0x73, 0x20, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x20,
0x62, 0x79, 0x20, 0x74, 0x68, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2e, 0x22,
0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x69, 0x73,
0x74, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x20, 0x7b, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6b, 0x65, 0x79, 0x20, 0x22,
0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x20, 0x76,
0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61,
0x74, 0x22, 0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22,
0x4c, 0x69, 0x73, 0x74, 0x20, 0x6f, 0x66, 0x20, 0x64, 0x61, 0x74, 0x61,
0x20, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d,
0x61, 0x73, 0x20, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64,
0x20, 0x62, 0x79, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x65, 0x72, 0x76,
0x65, 0x72, 0x2e, 0x22, 0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x6c, 0x65, 0x61, 0x66, 0x20, 0x69, 0x64, 0x65, 0x6e,
0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x20,
0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69,
0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x49, 0x64, 0x65, 0x6e, 0x74,
0x69, 0x66, 0x69, 0x65, 0x72, 0x20, 0x74, 0x6f, 0x20, 0x75, 0x6e, 0x69,
0x71, 0x75, 0x65, 0x6c, 0x79, 0x20, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65,
0x6e, 0x63, 0x65, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x63, 0x68, 0x65,
0x6d, 0x61, 0x2e, 0x20, 0x20, 0x54, 0x68, 0x65, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x64,
0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x20, 0x69, 0x73, 0x20,
0x75, 0x73, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20,
0x3c, 0x67, 0x65, 0x74, 0x2d, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x3e,
0x20, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61,
0x6e, 0x64, 0x20, 0x6d, 0x61, 0x79, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x62, 0x65, 0x20, 0x75,
0x73, 0x65, 0x64, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x6f, 0x74, 0x68, 0x65,
0x72, 0x20, 0x70, 0x75, 0x72, 0x70, 0x6f, 0x73, 0x65, 0x73, 0x20, 0x73,
0x75, 0x63, 0x68, 0x20, 0x61, 0x73, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x20,
0x72, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x61, 0x6c, 0x2e, 0x0a, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x46, 0x6f, 0x72, 0x20, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x69, 0x6e,
0x67, 0x20, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x73, 0x20,
0x74, 0x68, 0x61, 0x74, 0x20, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74,
0x20, 0x6f, 0x72, 0x20, 0x72, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x20,
0x61, 0x20, 0x64, 0x61, 0x74, 0x61, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6d, 0x6f, 0x64, 0x65,
0x6c, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x28, 0x65, 0x2e, 0x67, 0x2e,
0x2c, 0x20, 0x59, 0x41, 0x4e, 0x47, 0x20, 0x6d, 0x6f, 0x64, 0x75, 0x6c,
0x65, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x29, 0x20, 0x74, 0x68, 0x65, 0x20,
0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x20, 0x4d,
0x55, 0x53, 0x54, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x20, 0x74,
0x68, 0x61, 0x74, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x2e, 0x20, 0x20, 0x46,
0x6f, 0x72, 0x20, 0x59, 0x41, 0x4e, 0x47, 0x20, 0x64, 0x61, 0x74, 0x61,
0x20, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x73, 0x2c, 0x20, 0x74, 0x68, 0x65,
0x20, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x20,
0x69, 0x73, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6e, 0x61, 0x6d, 0x65,
0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6d, 0x6f, 0x64, 0x75,
0x6c, 0x65, 0x20, 0x6f, 0x72, 0x20, 0x73, 0x75, 0x62, 0x6d, 0x6f, 0x64,
0x75, 0x6c, 0x65, 0x2e, 0x20, 0x20, 0x49, 0x6e, 0x20, 0x6f, 0x74, 0x68,
0x65, 0x72, 0x20, 0x63, 0x61, 0x73, 0x65, 0x73, 0x2c, 0x20, 0x61, 0x6e,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72,
0x20, 0x73, 0x75, 0x63, 0x68, 0x20, 0x61, 0x73, 0x20, 0x61, 0x20, 0x66,
0x69, 0x6c, 0x65, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x4d, 0x41, 0x59, 0x20,
0x62, 0x65, 0x20, 0x75, 0x73, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x73, 0x74,
0x65, 0x61, 0x64, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x6c, 0x65, 0x61, 0x66, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f,
0x6e, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e,
0x67, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x22, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66,
0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x20,
0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x2e, 0x20, 0x20,
0x4d, 0x75, 0x6c, 0x74, 0x69, 0x70, 0x6c, 0x65, 0x20, 0x76, 0x65, 0x72,
0x73, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x4d, 0x41, 0x59, 0x20, 0x62, 0x65,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x20,
0x73, 0x69, 0x6d, 0x75, 0x6c, 0x74, 0x61, 0x6e, 0x65, 0x6f, 0x75, 0x73,
0x6c, 0x79, 0x20, 0x62, 0x79, 0x20, 0x61, 0x20, 0x4e, 0x45, 0x54, 0x43,
0x4f, 0x4e, 0x46, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2e, 0x20,
0x20, 0x45, 0x61, 0x63, 0x68, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69,
0x6f, 0x6e, 0x20, 0x4d, 0x55, 0x53, 0x54, 0x20, 0x62, 0x65, 0x20, 0x72,
0x65, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x64, 0x69,
0x76, 0x69, 0x64, 0x75, 0x61, 0x6c, 0x6c, 0x79, 0x20, 0x69, 0x6e, 0x20,
0x74, 0x68, 0x65, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x20, 0x6c,
0x69, 0x73, 0x74, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x2e, 0x65, 0x2e, 0x2c, 0x20,
0x77, 0x69, 0x74, 0x68, 0x20, 0x73, 0x61, 0x6d, 0x65, 0x20, 0x69, 0x64,
0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x2c, 0x20, 0x70, 0x6f,
0x73, 0x73, 0x69, 0x62, 0x6c, 0x79, 0x20, 0x64, 0x69, 0x66, 0x66, 0x65,
0x72, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f,
0x6e, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x62, 0x75, 0x74, 0x20, 0x64, 0x69, 0x66, 0x66,
0x65, 0x72, 0x65, 0x6e, 0x74, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f,
0x6e, 0x2e, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x46, 0x6f, 0x72, 0x20, 0x59, 0x41, 0x4e,
0x47, 0x20, 0x64, 0x61, 0x74, 0x61, 0x20, 0x6d, 0x6f, 0x64, 0x65, 0x6c,
0x73, 0x2c, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x69,
0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x20,
0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6d, 0x6f, 0x73, 0x74, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x72, 0x65, 0x63, 0x65, 0x6e, 0x74, 0x20, 0x59, 0x41, 0x4e, 0x47,
0x20, 0x27, 0x72, 0x65, 0x76, 0x69, 0x73, 0x69, 0x6f, 0x6e, 0x27, 0x20,
0x73, 0x74, 0x61, 0x74, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x69, 0x6e,
0x20, 0x74, 0x68, 0x65, 0x20, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x20,
0x6f, 0x72, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x73, 0x75, 0x62, 0x6d, 0x6f, 0x64, 0x75, 0x6c,
0x65, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x65, 0x6d,
0x70, 0x74, 0x79, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x20, 0x69,
0x66, 0x20, 0x6e, 0x6f, 0x20, 0x27, 0x72, 0x65, 0x76, 0x69, 0x73, 0x69,
0x6f, 0x6e, 0x27, 0x20, 0x73, 0x74, 0x61, 0x74, 0x65, 0x6d, 0x65, 0x6e,
0x74, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x69, 0x73, 0x20, 0x70, 0x72, 0x65, 0x73, 0x65, 0x6e,
0x74, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c,
0x65, 0x61, 0x66, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x7b,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74,
0x79, 0x70, 0x65, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79,
0x72, 0x65, 0x66, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x62, 0x61, 0x73, 0x65, 0x20, 0x73,
0x63, 0x68, 0x65, 0x6d, 0x61, 0x2d, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74,
0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x22, 0x54, 0x68, 0x65, 0x20, 0x64, 0x61, 0x74, 0x61, 0x20, 0x6d, 0x6f,
0x64, 0x65, 0x6c, 0x69, 0x6e, 0x67, 0x20, 0x6c, 0x61, 0x6e, 0x67, 0x75,
0x61, 0x67, 0x65, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x63, 0x68, 0x65,
0x6d, 0x61, 0x20, 0x69, 0x73, 0x20, 0x77, 0x72, 0x69, 0x74, 0x74, 0x65,
0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x69, 0x6e, 0x20, 0x28, 0x63, 0x75, 0x72, 0x72, 0x65,
0x6e, 0x74, 0x6c, 0x79, 0x20, 0x78, 0x73, 0x64, 0x2c, 0x20, 0x79, 0x61,
0x6e, 0x67, 0x2c, 0x20, 0x79, 0x69, 0x6e, 0x2c, 0x20, 0x72, 0x6e, 0x67,
0x2c, 0x20, 0x6f, 0x72, 0x20, 0x72, 0x6e, 0x63, 0x29, 0x2e, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x46, 0x6f, 0x72, 0x20, 0x59, 0x41, 0x4e, 0x47, 0x20, 0x64, 0x61, 0x74,
0x61, 0x20, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x73, 0x2c, 0x20, 0x27, 0x79,
0x61, 0x6e, 0x67, 0x27, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20,
0x4d, 0x55, 0x53, 0x54, 0x20, 0x62, 0x65, 0x20, 0x73, 0x75, 0x70, 0x70,
0x6f, 0x72, 0x74, 0x65, 0x64, 0x20, 0x61, 0x6e, 0x64, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x27,
0x79, 0x69, 0x6e, 0x27, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20,
0x4d, 0x41, 0x59, 0x20, 0x61, 0x6c, 0x73, 0x6f, 0x20, 0x62, 0x65, 0x20,
0x70, 0x72, 0x6f, 0x76, 0x69, 0x64, 0x65, 0x64, 0x2e, 0x22, 0x3b, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x65, 0x61, 0x66, 0x20, 0x6e,
0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x7b, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x79, 0x70,
0x65, 0x20, 0x69, 0x6e, 0x65, 0x74, 0x3a, 0x75, 0x72, 0x69, 0x3b, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6d, 0x61,
0x6e, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x79, 0x20, 0x74, 0x72, 0x75, 0x65,
0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x22, 0x54, 0x68, 0x65, 0x20, 0x58, 0x4d, 0x4c, 0x20, 0x6e, 0x61, 0x6d,
0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x64, 0x65, 0x66, 0x69, 0x6e,
0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x74, 0x68, 0x65, 0x20, 0x64, 0x61,
0x74, 0x61, 0x20, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x2e, 0x0a, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x46, 0x6f, 0x72, 0x20, 0x59, 0x41, 0x4e, 0x47, 0x20, 0x64, 0x61, 0x74,
0x61, 0x20, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x73, 0x2c, 0x20, 0x74, 0x68,
0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6d, 0x6f,
0x64, 0x75, 0x6c, 0x65, 0x27, 0x73, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x73,
0x70, 0x61, 0x63, 0x65, 0x2e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x49, 0x66, 0x20, 0x74, 0x68,
0x65, 0x20, 0x6c, 0x69, 0x73, 0x74, 0x20, 0x65, 0x6e, 0x74, 0x72, 0x79,
0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x73, 0x20, 0x61,
0x20, 0x73, 0x75, 0x62, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x2c, 0x20,
0x74, 0x68, 0x69, 0x73, 0x20, 0x66, 0x69, 0x65, 0x6c, 0x64, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x73, 0x20, 0x74, 0x68, 0x65,
0x20, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x6f,
0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65,
0x20, 0x74, 0x6f, 0x20, 0x77, 0x68, 0x69, 0x63, 0x68, 0x20, 0x74, 0x68,
0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x73, 0x75, 0x62, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65,
0x20, 0x62, 0x65, 0x6c, 0x6f, 0x6e, 0x67, 0x73, 0x2e, 0x22, 0x3b, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x65, 0x61, 0x66, 0x2d, 0x6c,
0x69, 0x73, 0x74, 0x20, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e,
0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x75, 0x6e, 0x69, 0x6f, 0x6e, 0x20,
0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x65, 0x6e, 0x75, 0x6d, 0x65,
0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x65,
0x6e, 0x75, 0x6d, 0x20, 0x22, 0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46,
0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x69, 0x6e,
0x65, 0x74, 0x3a, 0x75, 0x72, 0x69, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69,
0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x4f, 0x6e, 0x65, 0x20, 0x6f,
0x72, 0x20, 0x6d, 0x6f, 0x72, 0x65, 0x20, 0x6c, 0x6f, 0x63, 0x61, 0x74,
0x69, 0x6f, 0x6e, 0x73, 0x20, 0x66, 0x72, 0x6f, 0x6d, 0x20, 0x77, 0x68,
0x69, 0x63, 0x68, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x63, 0x68, 0x65,
0x6d, 0x61, 0x20, 0x63, 0x61, 0x6e, 0x20, 0x62, 0x65, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72,
0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x65, 0x64, 0x2e, 0x20, 0x20, 0x54,
0x68, 0x69, 0x73, 0x20, 0x6c, 0x69, 0x73, 0x74, 0x20, 0x53, 0x48, 0x4f,
0x55, 0x4c, 0x44, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x20,
0x61, 0x74, 0x20, 0x6c, 0x65, 0x61, 0x73, 0x74, 0x20, 0x6f, 0x6e, 0x65,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x65, 0x6e, 0x74, 0x72, 0x79, 0x20, 0x70, 0x65, 0x72, 0x20,
0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x2e, 0x0a, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x41, 0x20,
0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x20, 0x65, 0x6e, 0x74, 0x72, 0x79,
0x20, 0x6d, 0x61, 0x79, 0x20, 0x62, 0x65, 0x20, 0x6c, 0x6f, 0x63, 0x61,
0x74, 0x65, 0x64, 0x20, 0x6f, 0x6e, 0x20, 0x61, 0x20, 0x72, 0x65, 0x6d,
0x6f, 0x74, 0x65, 0x20, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x73, 0x79, 0x73,
0x74, 0x65, 0x6d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x28, 0x65, 0x2e, 0x67, 0x2e, 0x2c, 0x20,
0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x20, 0x74, 0x6f,
0x20, 0x66, 0x69, 0x6c, 0x65, 0x20, 0x73, 0x79, 0x73, 0x74, 0x65, 0x6d,
0x20, 0x66, 0x6f, 0x72, 0x20, 0x66, 0x74, 0x70, 0x20, 0x72, 0x65, 0x74,
0x72, 0x69, 0x65, 0x76, 0x61, 0x6c, 0x29, 0x20, 0x6f, 0x72, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x72, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x65, 0x64, 0x20, 0x64, 0x69,
0x72, 0x65, 0x63, 0x74, 0x6c, 0x79, 0x20, 0x66, 0x72, 0x6f, 0x6d, 0x20,
0x61, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20, 0x73, 0x75, 0x70,
0x70, 0x6f, 0x72, 0x74, 0x69, 0x6e, 0x67, 0x20, 0x74, 0x68, 0x65, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x3c, 0x67, 0x65, 0x74, 0x2d, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61,
0x3e, 0x20, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20,
0x28, 0x64, 0x65, 0x6e, 0x6f, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20,
0x74, 0x68, 0x65, 0x20, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x20, 0x27, 0x4e,
0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x27, 0x29, 0x2e, 0x22, 0x3b, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e,
0x65, 0x72, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x20,
0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63,
0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x22, 0x54, 0x68, 0x65, 0x20, 0x73, 0x65, 0x73,
0x73, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69,
0x6e, 0x65, 0x72, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x73,
0x20, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x2d, 0x73, 0x70, 0x65,
0x63, 0x69, 0x66, 0x69, 0x63, 0x20, 0x64, 0x61, 0x74, 0x61, 0x20, 0x66,
0x6f, 0x72, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20, 0x6d, 0x61, 0x6e, 0x61,
0x67, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69,
0x6f, 0x6e, 0x73, 0x2e, 0x20, 0x20, 0x54, 0x68, 0x65, 0x20, 0x73, 0x65,
0x73, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x6c, 0x69, 0x73, 0x74, 0x20, 0x4d,
0x55, 0x53, 0x54, 0x20, 0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x61, 0x6c, 0x6c,
0x20, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74, 0x6c, 0x79, 0x20, 0x61,
0x63, 0x74, 0x69, 0x76, 0x65, 0x20, 0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e,
0x46, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x22,
0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x69, 0x73,
0x74, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x7b, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6b, 0x65, 0x79, 0x20,
0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x2d, 0x69, 0x64, 0x3b, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63,
0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x41, 0x6c, 0x6c, 0x20, 0x4e,
0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69,
0x6f, 0x6e, 0x73, 0x20, 0x6d, 0x61, 0x6e, 0x61, 0x67, 0x65, 0x64, 0x20,
0x62, 0x79, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4e, 0x45, 0x54, 0x43, 0x4f,
0x4e, 0x46, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x4d, 0x55, 0x53,
0x54, 0x20, 0x62, 0x65, 0x20, 0x72, 0x65, 0x70, 0x6f, 0x72, 0x74, 0x65,
0x64, 0x20, 0x69, 0x6e, 0x20, 0x74, 0x68, 0x69, 0x73, 0x20, 0x6c, 0x69,
0x73, 0x74, 0x2e, 0x22, 0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x6c, 0x65, 0x61, 0x66, 0x20, 0x73, 0x65, 0x73, 0x73,
0x69, 0x6f, 0x6e, 0x2d, 0x69, 0x64, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x20,
0x75, 0x69, 0x6e, 0x74, 0x33, 0x32, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x61, 0x6e,
0x67, 0x65, 0x20, 0x22, 0x31, 0x2e, 0x2e, 0x6d, 0x61, 0x78, 0x22, 0x3b,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64,
0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22,
0x55, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74,
0x69, 0x66, 0x69, 0x65, 0x72, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x74, 0x68,
0x65, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x2e, 0x20, 0x20,
0x54, 0x68, 0x69, 0x73, 0x20, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x20, 0x69,
0x73, 0x20, 0x74, 0x68, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x4e, 0x45, 0x54, 0x43, 0x4f,
0x4e, 0x46, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x69,
0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x2c, 0x20, 0x61,
0x73, 0x20, 0x64, 0x65, 0x66, 0x69, 0x6e, 0x65, 0x64, 0x20, 0x69, 0x6e,
0x20, 0x52, 0x46, 0x43, 0x20, 0x34, 0x37, 0x34, 0x31, 0x2e, 0x22, 0x3b,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72,
0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x52, 0x46,
0x43, 0x20, 0x34, 0x37, 0x34, 0x31, 0x3a, 0x20, 0x4e, 0x45, 0x54, 0x43,
0x4f, 0x4e, 0x46, 0x20, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x75, 0x72,
0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x63,
0x6f, 0x6c, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c,
0x65, 0x61, 0x66, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72,
0x74, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74,
0x69, 0x74, 0x79, 0x72, 0x65, 0x66, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x62, 0x61, 0x73,
0x65, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x3b,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6d,
0x61, 0x6e, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x79, 0x20, 0x74, 0x72, 0x75,
0x65, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x22, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x73,
0x20, 0x74, 0x68, 0x65, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f,
0x72, 0x74, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x65, 0x61, 0x63, 0x68, 0x20,
0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x2c, 0x20, 0x65, 0x2e, 0x67,
0x2e, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x27, 0x6e, 0x65, 0x74, 0x63, 0x6f, 0x6e, 0x66, 0x2d,
0x73, 0x73, 0x68, 0x27, 0x2c, 0x20, 0x27, 0x6e, 0x65, 0x74, 0x63, 0x6f,
0x6e, 0x66, 0x2d, 0x73, 0x6f, 0x61, 0x70, 0x27, 0x2c, 0x20, 0x65, 0x74,
0x63, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c,
0x65, 0x61, 0x66, 0x20, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65,
0x20, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e,
0x67, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x6d, 0x61, 0x6e, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x79, 0x20, 0x74,
0x72, 0x75, 0x65, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69,
0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x22, 0x54, 0x68, 0x65, 0x20, 0x75, 0x73, 0x65, 0x72,
0x6e, 0x61, 0x6d, 0x65, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20,
0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74,
0x69, 0x74, 0x79, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x77, 0x61, 0x73,
0x20, 0x61, 0x75, 0x74, 0x68, 0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74,
0x65, 0x64, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x62, 0x79, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4e, 0x45,
0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70,
0x6f, 0x72, 0x74, 0x20, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c,
0x2e, 0x20, 0x20, 0x54, 0x68, 0x65, 0x20, 0x61, 0x6c, 0x67, 0x6f, 0x72,
0x69, 0x74, 0x68, 0x6d, 0x20, 0x75, 0x73, 0x65, 0x64, 0x20, 0x74, 0x6f,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x64, 0x65, 0x72, 0x69, 0x76, 0x65, 0x20, 0x74, 0x68, 0x65, 0x20,
0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x69, 0x73, 0x20,
0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20, 0x74, 0x72, 0x61, 0x6e,
0x73, 0x70, 0x6f, 0x72, 0x74, 0x20, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63,
0x6f, 0x6c, 0x20, 0x73, 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x63, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x61, 0x6e, 0x64, 0x20, 0x69, 0x6e, 0x20, 0x61, 0x64, 0x64, 0x69, 0x74,
0x69, 0x6f, 0x6e, 0x20, 0x73, 0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x63,
0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x61, 0x75, 0x74, 0x68,
0x65, 0x6e, 0x74, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6d,
0x65, 0x63, 0x68, 0x61, 0x6e, 0x69, 0x73, 0x6d, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x75, 0x73, 0x65,
0x64, 0x20, 0x62, 0x79, 0x20, 0x74, 0x68, 0x65, 0x20, 0x4e, 0x45, 0x54,
0x43, 0x4f, 0x4e, 0x46, 0x20, 0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f,
0x72, 0x74, 0x20, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x2e,
0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x65, 0x61,
0x66, 0x20, 0x73, 0x6f, 0x75, 0x72, 0x63, 0x65, 0x2d, 0x68, 0x6f, 0x73,
0x74, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x69, 0x6e, 0x65, 0x74, 0x3a,
0x68, 0x6f, 0x73, 0x74, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74,
0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x22, 0x48, 0x6f, 0x73, 0x74, 0x20, 0x69, 0x64,
0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x20, 0x6f, 0x66, 0x20,
0x74, 0x68, 0x65, 0x20, 0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20,
0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x20, 0x20, 0x54, 0x68, 0x65,
0x20, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75,
0x72, 0x6e, 0x65, 0x64, 0x20, 0x69, 0x73, 0x20, 0x69, 0x6d, 0x70, 0x6c,
0x65, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x73,
0x70, 0x65, 0x63, 0x69, 0x66, 0x69, 0x63, 0x20, 0x28, 0x65, 0x2e, 0x67,
0x2e, 0x2c, 0x20, 0x68, 0x6f, 0x73, 0x74, 0x6e, 0x61, 0x6d, 0x65, 0x2c,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x49, 0x50, 0x76, 0x34, 0x20, 0x61, 0x64, 0x64, 0x72, 0x65,
0x73, 0x73, 0x2c, 0x20, 0x49, 0x50, 0x76, 0x36, 0x20, 0x61, 0x64, 0x64,
0x72, 0x65, 0x73, 0x73, 0x29, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x6c, 0x65, 0x61, 0x66, 0x20, 0x6c, 0x6f, 0x67, 0x69, 0x6e,
0x2d, 0x74, 0x69, 0x6d, 0x65, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x79,
0x61, 0x6e, 0x67, 0x3a, 0x64, 0x61, 0x74, 0x65, 0x2d, 0x61, 0x6e, 0x64,
0x2d, 0x74, 0x69, 0x6d, 0x65, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x6d, 0x61, 0x6e, 0x64, 0x61, 0x74, 0x6f,
0x72, 0x79, 0x20, 0x74, 0x72, 0x75, 0x65, 0x3b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72,
0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x54, 0x69, 0x6d, 0x65,
0x20, 0x61, 0x74, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x65, 0x72, 0x76,
0x65, 0x72, 0x20, 0x61, 0x74, 0x20, 0x77, 0x68, 0x69, 0x63, 0x68, 0x20,
0x74, 0x68, 0x65, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x20,
0x77, 0x61, 0x73, 0x20, 0x65, 0x73, 0x74, 0x61, 0x62, 0x6c, 0x69, 0x73,
0x68, 0x65, 0x64, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x75, 0x73, 0x65, 0x73, 0x20, 0x63, 0x6f, 0x6d, 0x6d, 0x6f, 0x6e,
0x2d, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x73, 0x20, 0x7b, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65,
0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x50,
0x65, 0x72, 0x2d, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x63,
0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x73, 0x2e, 0x20, 0x20, 0x5a, 0x65,
0x72, 0x6f, 0x20, 0x62, 0x61, 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74,
0x68, 0x20, 0x66, 0x6f, 0x6c, 0x6c, 0x6f, 0x77, 0x69, 0x6e, 0x67, 0x20,
0x72, 0x65, 0x73, 0x65, 0x74, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x62, 0x65, 0x68, 0x61, 0x76,
0x69, 0x6f, 0x75, 0x72, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x2d, 0x20, 0x61,
0x74, 0x20, 0x73, 0x74, 0x61, 0x72, 0x74, 0x20, 0x6f, 0x66, 0x20, 0x61,
0x20, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x2d, 0x20, 0x77, 0x68, 0x65, 0x6e, 0x20, 0x6d, 0x61, 0x78, 0x20, 0x76,
0x61, 0x6c, 0x75, 0x65, 0x20, 0x69, 0x73, 0x20, 0x72, 0x65, 0x61, 0x63,
0x68, 0x65, 0x64, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63,
0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x20, 0x73, 0x74, 0x61,
0x74, 0x69, 0x73, 0x74, 0x69, 0x63, 0x73, 0x20, 0x7b, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74,
0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x22, 0x53, 0x74, 0x61, 0x74, 0x69, 0x73, 0x74, 0x69, 0x63, 0x61, 0x6c,
0x20, 0x64, 0x61, 0x74, 0x61, 0x20, 0x70, 0x65, 0x72, 0x74, 0x61, 0x69,
0x6e, 0x69, 0x6e, 0x67, 0x20, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20,
0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20, 0x73, 0x65, 0x72, 0x76,
0x65, 0x72, 0x2e, 0x22, 0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x6c, 0x65, 0x61, 0x66, 0x20, 0x6e, 0x65, 0x74, 0x63, 0x6f, 0x6e,
0x66, 0x2d, 0x73, 0x74, 0x61, 0x72, 0x74, 0x2d, 0x74, 0x69, 0x6d, 0x65,
0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74,
0x79, 0x70, 0x65, 0x20, 0x79, 0x61, 0x6e, 0x67, 0x3a, 0x64, 0x61, 0x74,
0x65, 0x2d, 0x61, 0x6e, 0x64, 0x2d, 0x74, 0x69, 0x6d, 0x65, 0x3b, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63,
0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x44, 0x61, 0x74, 0x65, 0x20,
0x61, 0x6e, 0x64, 0x20, 0x74, 0x69, 0x6d, 0x65, 0x20, 0x61, 0x74, 0x20,
0x77, 0x68, 0x69, 0x63, 0x68, 0x20, 0x74, 0x68, 0x65, 0x20, 0x6d, 0x61,
0x6e, 0x61, 0x67, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x73, 0x75, 0x62,
0x73, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x20, 0x77, 0x61, 0x73, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x74,
0x61, 0x72, 0x74, 0x65, 0x64, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c,
0x65, 0x61, 0x66, 0x20, 0x69, 0x6e, 0x2d, 0x62, 0x61, 0x64, 0x2d, 0x68,
0x65, 0x6c, 0x6c, 0x6f, 0x73, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x79, 0x61, 0x6e,
0x67, 0x3a, 0x7a, 0x65, 0x72, 0x6f, 0x2d, 0x62, 0x61, 0x73, 0x65, 0x64,
0x2d, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x33, 0x32, 0x3b, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63,
0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x4e, 0x75, 0x6d, 0x62, 0x65,
0x72, 0x20, 0x6f, 0x66, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e,
0x73, 0x20, 0x73, 0x69, 0x6c, 0x65, 0x6e, 0x74, 0x6c, 0x79, 0x20, 0x64,
0x72, 0x6f, 0x70, 0x70, 0x65, 0x64, 0x20, 0x62, 0x65, 0x63, 0x61, 0x75,
0x73, 0x65, 0x20, 0x61, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x20,
0x3c, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x3e, 0x20, 0x6d, 0x65, 0x73, 0x73,
0x61, 0x67, 0x65, 0x20, 0x77, 0x61, 0x73, 0x20, 0x72, 0x65, 0x63, 0x65,
0x69, 0x76, 0x65, 0x64, 0x2e, 0x20, 0x20, 0x54, 0x68, 0x69, 0x73, 0x20,
0x69, 0x6e, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x73, 0x20, 0x3c, 0x68, 0x65,
0x6c, 0x6c, 0x6f, 0x3e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x73, 0x20,
0x77, 0x69, 0x74, 0x68, 0x20, 0x61, 0x20, 0x27, 0x73, 0x65, 0x73, 0x73,
0x69, 0x6f, 0x6e, 0x2d, 0x69, 0x64, 0x27, 0x20, 0x61, 0x74, 0x74, 0x72,
0x69, 0x62, 0x75, 0x74, 0x65, 0x2c, 0x20, 0x62, 0x61, 0x64, 0x20, 0x6e,
0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x2c, 0x20, 0x61, 0x6e,
0x64, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x62, 0x61, 0x64, 0x20, 0x63, 0x61, 0x70, 0x61, 0x62, 0x69, 0x6c, 0x69,
0x74, 0x79, 0x20, 0x64, 0x65, 0x63, 0x6c, 0x61, 0x72, 0x61, 0x74, 0x69,
0x6f, 0x6e, 0x73, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x65, 0x61,
0x66, 0x20, 0x69, 0x6e, 0x2d, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e,
0x73, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x74, 0x79, 0x70, 0x65, 0x20, 0x79, 0x61, 0x6e, 0x67, 0x3a, 0x7a, 0x65,
0x72, 0x6f, 0x2d, 0x62, 0x61, 0x73, 0x65, 0x64, 0x2d, 0x63, 0x6f, 0x75,
0x6e, 0x74, 0x65, 0x72, 0x33, 0x32, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74,
0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x22, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x20, 0x6f, 0x66,
0x20, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x73, 0x74,
0x61, 0x72, 0x74, 0x65, 0x64, 0x2e, 0x20, 0x20, 0x54, 0x68, 0x69, 0x73,
0x20, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x20, 0x69, 0x73, 0x20,
0x69, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x65, 0x64, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x77,
0x68, 0x65, 0x6e, 0x20, 0x61, 0x20, 0x3c, 0x68, 0x65, 0x6c, 0x6c, 0x6f,
0x3e, 0x20, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x20, 0x77, 0x69,
0x74, 0x68, 0x20, 0x61, 0x20, 0x3c, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f,
0x6e, 0x2d, 0x69, 0x64, 0x3e, 0x20, 0x69, 0x73, 0x20, 0x73, 0x65, 0x6e,
0x74, 0x2e, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x27, 0x69, 0x6e, 0x2d, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f,
0x6e, 0x73, 0x27, 0x20, 0x2d, 0x20, 0x27, 0x69, 0x6e, 0x2d, 0x62, 0x61,
0x64, 0x2d, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x73, 0x27, 0x20, 0x3d, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x27, 0x6e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x20, 0x6f, 0x66,
0x20, 0x63, 0x6f, 0x72, 0x72, 0x65, 0x63, 0x74, 0x6c, 0x79, 0x20, 0x73,
0x74, 0x61, 0x72, 0x74, 0x65, 0x64, 0x20, 0x6e, 0x65, 0x74, 0x63, 0x6f,
0x6e, 0x66, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x27,
0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x65, 0x61, 0x66, 0x20, 0x64, 0x72,
0x6f, 0x70, 0x70, 0x65, 0x64, 0x2d, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f,
0x6e, 0x73, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x79, 0x61, 0x6e, 0x67, 0x3a, 0x7a,
0x65, 0x72, 0x6f, 0x2d, 0x62, 0x61, 0x73, 0x65, 0x64, 0x2d, 0x63, 0x6f,
0x75, 0x6e, 0x74, 0x65, 0x72, 0x33, 0x32, 0x3b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70,
0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x22, 0x4e, 0x75, 0x6d, 0x62, 0x65, 0x72, 0x20, 0x6f,
0x66, 0x20, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x20, 0x74,
0x68, 0x61, 0x74, 0x20, 0x77, 0x65, 0x72, 0x65, 0x20, 0x61, 0x62, 0x6e,
0x6f, 0x72, 0x6d, 0x61, 0x6c, 0x6c, 0x79, 0x20, 0x74, 0x65, 0x72, 0x6d,
0x69, 0x6e, 0x61, 0x74, 0x65, 0x64, 0x2c, 0x20, 0x65, 0x2e, 0x67, 0x2e,
0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x64, 0x75, 0x65, 0x20, 0x74, 0x6f, 0x20, 0x69, 0x64, 0x6c, 0x65,
0x20, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x20, 0x6f, 0x72, 0x20,
0x74, 0x72, 0x61, 0x6e, 0x73, 0x70, 0x6f, 0x72, 0x74, 0x20, 0x63, 0x6c,
0x6f, 0x73, 0x65, 0x2e, 0x20, 0x20, 0x54, 0x68, 0x69, 0x73, 0x20, 0x63,
0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x20, 0x69, 0x73, 0x20, 0x6e, 0x6f,
0x74, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x69, 0x6e, 0x63, 0x72, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x65, 0x64,
0x20, 0x77, 0x68, 0x65, 0x6e, 0x20, 0x61, 0x20, 0x73, 0x65, 0x73, 0x73,
0x69, 0x6f, 0x6e, 0x20, 0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x70, 0x65,
0x72, 0x6c, 0x79, 0x20, 0x63, 0x6c, 0x6f, 0x73, 0x65, 0x64, 0x20, 0x62,
0x79, 0x20, 0x61, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x3c, 0x63, 0x6c, 0x6f, 0x73, 0x65, 0x2d, 0x73, 0x65,
0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x20, 0x6f, 0x70, 0x65, 0x72, 0x61,
0x74, 0x69, 0x6f, 0x6e, 0x2c, 0x20, 0x6f, 0x72, 0x20, 0x6b, 0x69, 0x6c,
0x6c, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x61, 0x20, 0x3c, 0x6b, 0x69,
0x6c, 0x6c, 0x2d, 0x73, 0x65, 0x73, 0x73, 0x69, 0x6f, 0x6e, 0x3e, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6f,
0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x22, 0x3b, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x75, 0x73, 0x65, 0x73, 0x20, 0x63, 0x6f, 0x6d, 0x6d, 0x6f,
0x6e, 0x2d, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x73, 0x20, 0x7b,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73,
0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x47, 0x6c, 0x6f, 0x62,
0x61, 0x6c, 0x20, 0x63, 0x6f, 0x75, 0x6e, 0x74, 0x65, 0x72, 0x73, 0x2c,
0x20, 0x61, 0x63, 0x63, 0x75, 0x6d, 0x75, 0x6c, 0x61, 0x74, 0x65, 0x64,
0x20, 0x66, 0x72, 0x6f, 0x6d, 0x20, 0x61, 0x6c, 0x6c, 0x20, 0x73, 0x65,
0x73, 0x73, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x5a, 0x65, 0x72, 0x6f, 0x20,
0x62, 0x61, 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x66,
0x6f, 0x6c, 0x6c, 0x6f, 0x77, 0x69, 0x6e, 0x67, 0x20, 0x72, 0x65, 0x73,
0x65, 0x74, 0x20, 0x62, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x75, 0x72,
0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x2d, 0x20, 0x72, 0x65, 0x2d, 0x69, 0x6e, 0x69, 0x74,
0x69, 0x61, 0x6c, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6f,
0x66, 0x20, 0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20, 0x73, 0x65,
0x72, 0x76, 0x65, 0x72, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x2d, 0x20, 0x77, 0x68, 0x65, 0x6e,
0x20, 0x6d, 0x61, 0x78, 0x20, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x20, 0x69,
0x73, 0x20, 0x72, 0x65, 0x61, 0x63, 0x68, 0x65, 0x64, 0x22, 0x3b, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x7d, 0x0a, 0x20, 0x20, 0x7d, 0x0a, 0x0a, 0x20, 0x20, 0x72, 0x70, 0x63,
0x20, 0x67, 0x65, 0x74, 0x2d, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x20,
0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69,
0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x22, 0x54, 0x68, 0x69, 0x73, 0x20, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74,
0x69, 0x6f, 0x6e, 0x20, 0x69, 0x73, 0x20, 0x75, 0x73, 0x65, 0x64, 0x20,
0x74, 0x6f, 0x20, 0x72, 0x65, 0x74, 0x72, 0x69, 0x65, 0x76, 0x65, 0x20,
0x61, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x20, 0x66, 0x72, 0x6f,
0x6d, 0x20, 0x74, 0x68, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x4e, 0x45, 0x54, 0x43, 0x4f, 0x4e, 0x46, 0x20, 0x73, 0x65, 0x72,
0x76, 0x65, 0x72, 0x2e, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x50, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x76, 0x65, 0x20, 0x52, 0x65,
0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x54, 0x68, 0x65, 0x20, 0x4e, 0x45, 0x54,
0x43, 0x4f, 0x4e, 0x46, 0x20, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x20,
0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20,
0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x65, 0x64, 0x20, 0x73, 0x63,
0x68, 0x65, 0x6d, 0x61, 0x2e, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x4e, 0x65, 0x67, 0x61, 0x74, 0x69, 0x76, 0x65, 0x20, 0x52,
0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x3a, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x49, 0x66, 0x20, 0x72, 0x65, 0x71,
0x75, 0x65, 0x73, 0x74, 0x65, 0x64, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d,
0x61, 0x20, 0x64, 0x6f, 0x65, 0x73, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x65,
0x78, 0x69, 0x73, 0x74, 0x2c, 0x20, 0x74, 0x68, 0x65, 0x20, 0x3c, 0x65,
0x72, 0x72, 0x6f, 0x72, 0x2d, 0x74, 0x61, 0x67, 0x3e, 0x20, 0x69, 0x73,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x27, 0x69,
0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x2d, 0x76, 0x61, 0x6c, 0x75, 0x65,
0x27, 0x2e, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x49, 0x66, 0x20, 0x6d, 0x6f, 0x72, 0x65, 0x20, 0x74, 0x68, 0x61,
0x6e, 0x20, 0x6f, 0x6e, 0x65, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61,
0x20, 0x6d, 0x61, 0x74, 0x63, 0x68, 0x65, 0x73, 0x20, 0x74, 0x68, 0x65,
0x20, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x65, 0x64, 0x20, 0x70,
0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65, 0x72, 0x73, 0x2c, 0x20, 0x74,
0x68, 0x65, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x3c, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x2d, 0x74, 0x61, 0x67, 0x3e, 0x20,
0x69, 0x73, 0x20, 0x27, 0x6f, 0x70, 0x65, 0x72, 0x61, 0x74, 0x69, 0x6f,
0x6e, 0x2d, 0x66, 0x61, 0x69, 0x6c, 0x65, 0x64, 0x27, 0x2c, 0x20, 0x61,
0x6e, 0x64, 0x20, 0x3c, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x2d, 0x61, 0x70,
0x70, 0x2d, 0x74, 0x61, 0x67, 0x3e, 0x20, 0x69, 0x73, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x27, 0x64, 0x61, 0x74, 0x61,
0x2d, 0x6e, 0x6f, 0x74, 0x2d, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65, 0x27,
0x2e, 0x22, 0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x6e, 0x70,
0x75, 0x74, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c,
0x65, 0x61, 0x66, 0x20, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69,
0x65, 0x72, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67,
0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6d, 0x61,
0x6e, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x79, 0x20, 0x74, 0x72, 0x75, 0x65,
0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65,
0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x49, 0x64, 0x65,
0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x20, 0x66, 0x6f, 0x72, 0x20,
0x74, 0x68, 0x65, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x20, 0x6c,
0x69, 0x73, 0x74, 0x20, 0x65, 0x6e, 0x74, 0x72, 0x79, 0x2e, 0x22, 0x3b,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x6c, 0x65, 0x61, 0x66, 0x20, 0x76, 0x65, 0x72, 0x73,
0x69, 0x6f, 0x6e, 0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e,
0x67, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64,
0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x56, 0x65,
0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65,
0x20, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x20, 0x72, 0x65, 0x71, 0x75,
0x65, 0x73, 0x74, 0x65, 0x64, 0x2e, 0x20, 0x20, 0x49, 0x66, 0x20, 0x74,
0x68, 0x69, 0x73, 0x20, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65,
0x72, 0x20, 0x69, 0x73, 0x20, 0x6e, 0x6f, 0x74, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x70, 0x72, 0x65, 0x73,
0x65, 0x6e, 0x74, 0x2c, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x6d, 0x6f, 0x72,
0x65, 0x20, 0x74, 0x68, 0x61, 0x6e, 0x20, 0x6f, 0x6e, 0x65, 0x20, 0x76,
0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68,
0x65, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x20, 0x65, 0x78, 0x69,
0x73, 0x74, 0x73, 0x20, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x65,
0x72, 0x76, 0x65, 0x72, 0x2c, 0x20, 0x61, 0x20, 0x27, 0x64, 0x61, 0x74,
0x61, 0x2d, 0x6e, 0x6f, 0x74, 0x2d, 0x75, 0x6e, 0x69, 0x71, 0x75, 0x65,
0x27, 0x20, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x20, 0x69, 0x73, 0x20, 0x72,
0x65, 0x74, 0x75, 0x72, 0x6e, 0x65, 0x64, 0x2c, 0x20, 0x61, 0x73, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64,
0x65, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x64, 0x20, 0x61, 0x62, 0x6f,
0x76, 0x65, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x65, 0x61, 0x66,
0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x7b, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74, 0x79, 0x70, 0x65, 0x20, 0x69,
0x64, 0x65, 0x6e, 0x74, 0x69, 0x74, 0x79, 0x72, 0x65, 0x66, 0x20, 0x7b,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x62,
0x61, 0x73, 0x65, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x2d, 0x66,
0x6f, 0x72, 0x6d, 0x61, 0x74, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x22, 0x54, 0x68, 0x65, 0x20, 0x64, 0x61, 0x74, 0x61, 0x20, 0x6d, 0x6f,
0x64, 0x65, 0x6c, 0x69, 0x6e, 0x67, 0x20, 0x6c, 0x61, 0x6e, 0x67, 0x75,
0x61, 0x67, 0x65, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73,
0x63, 0x68, 0x65, 0x6d, 0x61, 0x2e, 0x20, 0x20, 0x49, 0x66, 0x20, 0x74,
0x68, 0x69, 0x73, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x65, 0x74, 0x65,
0x72, 0x20, 0x69, 0x73, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x70, 0x72, 0x65,
0x73, 0x65, 0x6e, 0x74, 0x2c, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x6d, 0x6f,
0x72, 0x65, 0x20, 0x74, 0x68, 0x61, 0x6e, 0x20, 0x6f, 0x6e, 0x65, 0x20,
0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x73, 0x20, 0x6f, 0x66, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x74,
0x68, 0x65, 0x20, 0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x20, 0x65, 0x78,
0x69, 0x73, 0x74, 0x73, 0x20, 0x6f, 0x6e, 0x20, 0x74, 0x68, 0x65, 0x20,
0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2c, 0x20, 0x61, 0x20, 0x27, 0x64,
0x61, 0x74, 0x61, 0x2d, 0x6e, 0x6f, 0x74, 0x2d, 0x75, 0x6e, 0x69, 0x71,
0x75, 0x65, 0x27, 0x20, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x73,
0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x65, 0x64, 0x2c, 0x20, 0x61,
0x73, 0x20, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x62, 0x65, 0x64, 0x20,
0x61, 0x62, 0x6f, 0x76, 0x65, 0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x20, 0x7b, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x61, 0x6e, 0x79, 0x78,
0x6d, 0x6c, 0x20, 0x64, 0x61, 0x74, 0x61, 0x20, 0x7b, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x73, 0x63,
0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x43, 0x6f, 0x6e,
0x74, 0x61, 0x69, 0x6e, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x73, 0x63,
0x68, 0x65, 0x6d, 0x61, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74,
0x2e, 0x22, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x7d, 0x0a, 0x20, 0x20, 0x7d, 0x0a, 0x7d, 0x0a,
0x00
};
|
wungad/libnetconf2 | tests/test_thread_messages.c | /**
* \file test_thread_messages
* \author <NAME> <<EMAIL>>
* \brief libnetconf2 tests - thread-safety for receiving messages
*
* Copyright 2021 Deutsche Telekom AG.
* Copyright 2021 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <libyang/libyang.h>
#include <log.h>
#include <messages_p.h>
#include <messages_server.h>
#include <session_client.h>
#include <session_server.h>
#include "tests/config.h"
/* millisec */
#define NC_ACCEPT_TIMEOUT 5000
/* millisec */
#define NC_PS_POLL_TIMEOUT 5000
/* sec */
#define CLIENT_SSH_AUTH_TIMEOUT 10
#define nc_assert(cond) if (!(cond)) { fprintf(stderr, "assert failed (%s:%d)\n", __FILE__, __LINE__); exit(1); }
#if _POSIX_BARRIERS >= 200112L
pthread_barrier_t barrier;
pthread_barrier_t barrier_msg;
#endif
typedef struct arg {
int in;
int out;
struct ly_ctx *ctx;
} arg_t;
struct nc_server_reply *
rpc_clb(struct lyd_node *rpc, struct nc_session *session)
{
(void)rpc; (void)session;
return nc_server_reply_ok();
}
static void *
server_thread(void *arg)
{
struct nc_session *sess;
struct nc_server_notif *notif;
struct lyd_node *ntf;
struct ly_in *in;
struct nc_pollsession *ps;
arg_t args = *(arg_t *)arg;
char *eventtime;
struct timespec ts;
const char *data;
int poll;
nc_assert(!nc_server_init(args.ctx));
nc_assert(nc_accept_inout(args.in, args.out, "test", &sess) == NC_MSG_HELLO);
nc_session_inc_notif_status(sess);
data =
"<n1 xmlns=\"n1\">\n"
" <first>Test</first>\n"
"</n1>\n";
nc_assert(ly_in_new_memory(data, &in) == LY_SUCCESS);
nc_assert(lyd_parse_op(args.ctx, NULL, in, LYD_XML, LYD_TYPE_NOTIF_YANG, &ntf, NULL) == LY_SUCCESS);
ly_in_free(in, 0);
nc_assert(clock_gettime(CLOCK_REALTIME, &ts) != -1);
nc_assert(ly_time_ts2str(&ts, &eventtime) == LY_SUCCESS);
notif = nc_server_notif_new(ntf, eventtime, NC_PARAMTYPE_FREE);
ps = nc_ps_new();
nc_assert(ps);
nc_ps_add_session(ps, sess);
poll = nc_ps_poll(ps, 1000, &sess);
nc_server_notif_send(sess, notif, 1000);
nc_assert(poll == NC_PSPOLL_RPC);
nc_ps_clear(ps, 1, NULL);
nc_ps_free(ps);
/* Waiting for end of test */
pthread_barrier_wait(&barrier);
nc_server_notif_free(notif);
return arg;
}
static void *
notif_thread(void *arg)
{
struct nc_session *sess = (struct nc_session *)arg;
struct lyd_node *envp;
struct lyd_node *op;
NC_MSG_TYPE msgtype;
/* Sync threads for receiving message to increase chance of datarace */
pthread_barrier_wait(&barrier_msg);
do {
msgtype = nc_recv_notif(sess, 1000, &envp, &op);
} while (msgtype == NC_MSG_REPLY);
nc_assert(msgtype == NC_MSG_NOTIF);
lyd_free_tree(envp);
lyd_free_tree(op);
return arg;
}
int
main(void)
{
int pipes[4];
struct nc_session *sess;
struct lyd_node *op, *envp;
struct ly_ctx *ctx;
struct nc_rpc *rpc;
uint64_t msgid;
NC_MSG_TYPE msgtype;
const char *features[] = {"startup", NULL};
arg_t thread_arg;
pthread_t t[2];
pthread_barrier_init(&barrier, NULL, 2);
pthread_barrier_init(&barrier_msg, NULL, 2);
/* Create a two pipes */
nc_assert(pipe(pipes) != -1);
nc_assert(pipe(pipes + 2) != -1);
thread_arg.in = pipes[0];
thread_arg.out = pipes[3];
/* Create context */
nc_assert(ly_ctx_new(TESTS_DIR "/data/modules", 0, &ctx) == LY_SUCCESS);
nc_assert(ly_ctx_load_module(ctx, "ietf-netconf", NULL, features));
nc_assert(ly_ctx_load_module(ctx, "notif1", NULL, NULL));
thread_arg.ctx = ctx;
nc_set_global_rpc_clb(rpc_clb);
/* Start server thread */
pthread_create(&t[0], NULL, server_thread, &thread_arg);
nc_client_init();
/* Listen for notifications */
sess = nc_connect_inout(pipes[2], pipes[1], ctx);
nc_assert(sess);
pthread_create(&t[1], NULL, notif_thread, sess);
/* Send rpc */
rpc = nc_rpc_delete(NC_DATASTORE_STARTUP, NULL, NC_PARAMTYPE_CONST);
nc_assert(nc_send_rpc(sess, rpc, 1000, &msgid) == NC_MSG_RPC);
/* Sync threads for receiving message to increase chance of datarace */
pthread_barrier_wait(&barrier_msg);
do {
msgtype = nc_recv_reply(sess, rpc, msgid, 1000, &envp, &op);
} while (msgtype == NC_MSG_NOTIF);
nc_assert(msgtype == NC_MSG_REPLY);
nc_rpc_free(rpc);
lyd_free_tree(envp);
/* Waiting of end of test */
pthread_barrier_wait(&barrier);
pthread_join(t[0], NULL);
pthread_join(t[1], NULL);
/* Cleanup */
nc_session_free(sess, NULL);
ly_ctx_destroy(ctx);
for (uint8_t i = 0; i < 4; i++) {
close(pipes[i]);
}
return 0;
}
|
wungad/libnetconf2 | tests/test_server_thread.c | /**
* \file test_server_thread.c
* \author <NAME> <<EMAIL>>
* \brief libnetconf2 tests - thread-safety of all server functions
*
* Copyright (c) 2017 CESNET, z.s.p.o.
*
* This source code is licensed under BSD 3-Clause License (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <libyang/libyang.h>
#include <log.h>
#include <session_client.h>
#include <session_server.h>
#include "tests/config.h"
/* millisec */
#define NC_ACCEPT_TIMEOUT 5000
/* millisec */
#define NC_PS_POLL_TIMEOUT 5000
/* sec */
#define CLIENT_SSH_AUTH_TIMEOUT 10
#define nc_assert(cond) if (!(cond)) { fprintf(stderr, "assert failed (%s:%d)\n", __FILE__, __LINE__); exit(1); }
#if _POSIX_BARRIERS >= 200112L
pthread_barrier_t barrier;
#if defined (NC_ENABLED_SSH) || defined (NC_ENABLED_TLS)
static void *
server_thread(void *arg)
{
(void)arg;
NC_MSG_TYPE msgtype;
int ret;
struct nc_pollsession *ps;
struct nc_session *session;
ps = nc_ps_new();
nc_assert(ps);
pthread_barrier_wait(&barrier);
#if defined (NC_ENABLED_SSH) && defined (NC_ENABLED_TLS)
msgtype = nc_accept(NC_ACCEPT_TIMEOUT, &session);
nc_assert(msgtype == NC_MSG_HELLO);
nc_ps_add_session(ps, session);
ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT, NULL);
nc_assert(ret & NC_PSPOLL_RPC);
nc_ps_clear(ps, 0, NULL);
#endif
msgtype = nc_accept(NC_ACCEPT_TIMEOUT, &session);
nc_assert(msgtype == NC_MSG_HELLO);
nc_ps_add_session(ps, session);
ret = nc_ps_poll(ps, NC_PS_POLL_TIMEOUT, NULL);
nc_assert(ret & NC_PSPOLL_RPC);
nc_ps_clear(ps, 0, NULL);
nc_ps_free(ps);
nc_thread_destroy();
return NULL;
}
#endif /* NC_ENABLED_SSH || NC_ENABLED_TLS */
#ifdef NC_ENABLED_SSH
static int
clb_hostkeys(const char *name, void *UNUSED(user_data), char **privkey_path, char **UNUSED(privkey_data),
NC_SSH_KEY_TYPE *UNUSED(privkey_type))
{
if (!strcmp(name, "key_rsa")) {
*privkey_path = strdup(TESTS_DIR "/data/key_rsa");
return 0;
} else if (!strcmp(name, "key_dsa")) {
*privkey_path = strdup(TESTS_DIR "/data/key_dsa");
return 0;
}
return 1;
}
static void *
add_endpt_thread(void *arg)
{
(void)arg;
int ret;
pthread_barrier_wait(&barrier);
ret = nc_server_add_endpt("tertiary", NC_TI_LIBSSH);
nc_assert(!ret);
return NULL;
}
static void *
del_endpt_thread(void *arg)
{
(void)arg;
int ret;
pthread_barrier_wait(&barrier);
ret = nc_server_del_endpt("secondary", 0);
nc_assert(!ret);
return NULL;
}
static void *
ssh_endpt_set_hostkey_thread(void *arg)
{
(void)arg;
int ret;
pthread_barrier_wait(&barrier);
ret = nc_server_ssh_endpt_add_hostkey("main_ssh", "key_dsa", -1);
nc_assert(!ret);
return NULL;
}
static void *
ssh_endpt_set_auth_methods_thread(void *arg)
{
(void)arg;
int ret;
pthread_barrier_wait(&barrier);
ret = nc_server_ssh_endpt_set_auth_methods("main_ssh", NC_SSH_AUTH_PUBLICKEY | NC_SSH_AUTH_PASSWORD | NC_SSH_AUTH_INTERACTIVE);
nc_assert(!ret);
return NULL;
}
static void *
ssh_endpt_set_auth_attempts_thread(void *arg)
{
(void)arg;
int ret;
pthread_barrier_wait(&barrier);
ret = nc_server_ssh_endpt_set_auth_attempts("main_ssh", 2);
nc_assert(!ret);
return NULL;
}
static void *
ssh_endpt_set_auth_timeout_thread(void *arg)
{
(void)arg;
int ret;
pthread_barrier_wait(&barrier);
ret = nc_server_ssh_endpt_set_auth_timeout("main_ssh", 5);
nc_assert(!ret);
return NULL;
}
static void *
ssh_endpt_add_authkey_thread(void *arg)
{
(void)arg;
int ret;
pthread_barrier_wait(&barrier);
ret = nc_server_ssh_add_authkey_path(TESTS_DIR "/data/key_rsa.pub", "test3");
nc_assert(!ret);
return NULL;
}
static void *
ssh_endpt_del_authkey_thread(void *arg)
{
(void)arg;
int ret;
pthread_barrier_wait(&barrier);
ret = nc_server_ssh_del_authkey(TESTS_DIR "/data/key_dsa.pub", NULL, 0, "test2");
nc_assert(!ret);
return NULL;
}
static int
ssh_hostkey_check_clb(const char *hostname, ssh_session session, void *priv)
{
(void)hostname;
(void)session;
(void)priv;
return 0;
}
static void *
ssh_client_thread(void *arg)
{
int ret, read_pipe = *(int *)arg;
char buf[9];
struct nc_session *session;
fprintf(stdout, "SSH client start.\n");
ret = read(read_pipe, buf, 9);
nc_assert(ret == 9);
nc_assert(!strncmp(buf, "ssh_ready", 9));
/* skip the knownhost check */
nc_client_ssh_set_auth_hostkey_check_clb(ssh_hostkey_check_clb, NULL);
ret = nc_client_ssh_set_username("test");
nc_assert(!ret);
ret = nc_client_ssh_add_keypair(TESTS_DIR "/data/key_ecdsa.pub", TESTS_DIR "/data/key_ecdsa");
nc_assert(!ret);
nc_client_ssh_set_auth_pref(NC_SSH_AUTH_PUBLICKEY, 1);
nc_client_ssh_set_auth_pref(NC_SSH_AUTH_PASSWORD, -1);
nc_client_ssh_set_auth_pref(NC_SSH_AUTH_INTERACTIVE, -1);
session = nc_connect_ssh("127.0.0.1", 6001, NULL);
nc_assert(session);
nc_session_free(session, NULL);
fprintf(stdout, "SSH client finished.\n");
nc_thread_destroy();
return NULL;
}
#endif /* NC_ENABLED_SSH */
#ifdef NC_ENABLED_TLS
static int
clb_server_cert(const char *name, void *UNUSED(user_data), char **cert_path, char **cert_data, char **privkey_path,
char **privkey_data, NC_SSH_KEY_TYPE *privkey_type)
{
if (!strcmp(name, "server_cert1")) {
*cert_data = strdup("MIIEQDCCAygCCQCV65JgDvfWkTANBgkqhkiG9w0BAQsFADBjMQswCQYDVQQGEwJD\n"
"WjETMBEGA1UECAwKU29tZS1TdGF0ZTENMAsGA1UEBwwEQnJubzEPMA0GA1UECgwG\n"
"Q0VTTkVUMQwwCgYDVQQLDANUTUMxETAPBgNVBAMMCHNlcnZlcmNhMB4XDTE4MTEw\n"
"NTA3MzExMFoXDTI4MTEwMjA3MzExMFowYTELMAkGA1UEBhMCQ1oxEzARBgNVBAgM\n"
"<KEY>"
"<KEY>"
"<KEY>n"
"sBCbAaHTmLqWbxORWXWegyUjEskNxayVp5WforK+xfQeGxC1fCo+rCRrlQK/pqXB\n"
"/+K8C9w2lxfWPS3+4gYIjh1KIqfNALJ/QVOKvNCSOsNlR3eZ4OE1BOu4JqUZXiB8\n"
"1Yird7Wga7ACfW0uW72hOsTgfMymBs0RTrA2axKqnAbFSFguhJoztvR0uao/5lzN\n"
"JLRRpzQ8U2R6EZDYJghPzR/nzSjhca2gsJRQaSnpgJMvhnYJ4ERokAFaMMgMf50p\n"
"ghQGpSnPhOHXaBcA/6H7eojr716ml4et+vMBEOx8uPBQ3FAmx7VBICuMDK1/QUq0\n"
"Yes5FztbROIIW9HTNqhQ0tMqTt6dOJFD2t9Zk4C7jh9S88JpcMTrNdd5pWCgoKjh\n"
"UeWGjfp6tRyOUQEz6OTbwjKRtka0FvqKAq9hrW09KB5ib/MmgVWNByevXi5yL9+3\n"
"<KEY>"
"<KEY>"
"<KEY>//<KEY>"
"<KEY>"
"VgkN66BdpsE4UlWdlp0XL3aauMPxzLn9rq1yRtoHWT4/ucL9iEa6B295JBNjkgW+\n"
"ct9/y8060P9BUhY1DTv5DLzitsA4bjRaraIevjATDPfsbHFx9DTNrS5pXHIFbRcz\n"
"y3WniYXTKhpfM6m+1X8ogImE968DG8RqAW5YZZtrZW<KEY>"
"<KEY>"
"sGvC6hP9GKU3R2Jhxih/<KEY>");
*privkey_data = strdup("<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"t1+Na+hOIEoEEiKxcAPk2b2vBKNlRIW7WLJ3u7ZiuQEJTNm6+3cE4+lfwaBCBqBT\n"
"oE+dpzvoUXoMyFFReUFd1O5axu4fXgt00jMaOQxmE0v9OmR/pL/PWIflVF4Zz5yV\n"
"ONYaDVc7l+veY0oEZruEPJ0hlEgxuCzLrcMhjufl2qE2Q7fQIaav/1NqBVkCAwEA\n"
"AQKCAgAeRZw75Oszoqj0jfMmMILdD3Cfad+dY3FvLESYESeyt0XAX8XoOed6ymQj\n"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"2mb4EbReaaBzwCYqJdRWtlpJ54kzy8U00co+Yn//ZS7sbbIDkqHPnXkpdIr+0rED\n"
"<KEY>"
"R+NaVMjbqmrVeH70eKjoNVgcNYY1C9rGVF1d+LQEm7UsqS0DPp4wN9QKLAqIfuar\n"
"<KEY>"
"xZ0cxmkLtxrj/DVyExV11Cl0SbZLLa9mScYvxdl/qZutXt3PQyab0NiYxGzCD2Rn\n"
"<KEY>"
<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"ovVxR7LGKKTKIa9pxawHwB6Ithygs7YoJkjF2dm8pZTMZKsQN92K70XGj07SmYRL\n"
"<KEY>0Rcw6W0twfcy0/iB4U5ZS52EcCjW8vHlL+MpUo7\n"
"<KEY>1ZaM28zW/ZGk3wE0zy1YT5s30SQkm0NiWN3t/<KEY>"
"<KEY>"
"<KEY>"
"W4cgxzG0SZGgNwow4AhB+ygiiS8yvOa7UcHfUObVrzWeeq9mYSQ1PkvUTjkWR2/Y\n"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"<KEY>"
"nwrHSLk7HdKhnwGsLPduuRRH8q0n/osnoOutSQroE0n41UyIv2ZNccRwNmSzQcai\n"
"rBu2dSz02hlsh2otNl5IuGpOqXyPjXBpW4qGD6n2tH7THALnLC0BHtTSQVQsJsRM\n"
"3gX39LoiWvLDp2qJvplm6rTpi8Rgap6rZSqHe1yNKIxxD2vlr/WY9SMgLXYASO4S\n"
"SBz9wfGOmQIPk6KXNJkdV4kC7nNjIi75iwLLCgjHgUiHTrDq5sWekpeNnUoWsinb\n"
"Tsdsjnv3zHG9GyiClyLGxMbs4M5eyYECggEBAKuC8ZMpdIrjk6tERYB6g0LnQ7mW\n"
"8XYbDFAmLYMLs9yfG2jcjVbsW9Kugsr+3poUUv/q+hNO3jfY4HazhZDa0MalgNPo\n"
"Swr/VNRnkck40x2ovFb989J7yl++zTrnIrax9XRH1V0cNu+Kj7OMwZ2RRfbNv5JB\n"
"dOZPvkfqyIKFmbQgYbtD66rHuzNOfJpzqr/WVLO57/zzW8245NKG2B6B0oXkei/K\n"
"qDY0DAbHR3i3EOj1NPtVI1FC/xX8R9BREaid458bqoHJKuInrGcBjaUI9Cvymv8T\n"
"bstUgD6NPbJR4Sm6vrLeUqzjWZP3t1+Z6DjXmnpR2vvhMU/FWb//21p/88o=");
*privkey_type = NC_SSH_KEY_RSA;
return 0;
} else if (!strcmp(name, "main_cert")) {
*cert_path = strdup(TESTS_DIR "/data/server.crt");
*privkey_path = strdup(TESTS_DIR "/data/server.key");
return 0;
}
return 1;
}
static int
clb_trusted_cert_lists(const char *name, void *UNUSED(user_data), char ***cert_paths, int *cert_path_count,
char ***cert_data, int *cert_data_count)
{
if (!strcmp(name, "trusted_cert_list1")) {
*cert_data = malloc(sizeof **cert_data);
(*cert_data)[0] = strdup("<KEY>"
"<KEY>"
"<KEY>"
"<KEY>n"
"<KEY>sGA1UEBwwEQnJubzEPMA0GA1UECgwGQ0VTTkVU\n"
"MQwwCgYDVQQLDANUTUMxETAPBgNVBAMMCHNlcnZlcmNhMIIBIjANBgkqhkiG9w0B\n"
"AQEFAAOCAQ8AMIIBCgKCAQEAyMrKraqraFGklO2itRIEWxfuzWo1IwxZ22aJmeXD\n"
"Leomt6893NXelMLaC3swQ+hu49JjiIY81DXvbVgmIgLm7cAz5tHTHuJbfdI4Q6gy\n"
"ic4aOpy2s3s1/vYz+1TvEUFCiPXEsJrH72he/z9nBxL8vY6Eg8U8EG8NvKp9zyCK\n"
"A7vmNSgQOtuyF18fesYHAnvQjNXO5q6diPXdHOr2bjTRUvARGbWlv4Rvf81RwUkR\n"
"sWoF/0pglV/TxnW2MoHnn3apxb/kmH92CQ+GWKxq5SkhvbkYePlA87kgKnDtXl4w\n"
"EXIhYwM51kafRhhlAKN+qYeV9teBqGpjsZRYesrh3mXHlQIDAQABo1MwUTAdBgNV\n"
"HQ4EFgQU60nJ4q3ItcfaOOBjJSqadAPiMg8wHwYDVR0jBBgwFoAU<KEY>n"
"<KEY>"
"xIqIQ5SCXnKslZfrXiAEbB5dglxVOSa8me5a/70uHK/27JZ6veeIgRqZ4VgPHnBC\n"
"a3m6EHr+mnTjjqSUcGIUiKV3g2Dumw8paqZC+Qv+Ib/NKquS1lO2Ry1wHBtXzn5K\n"
"KHHyM1bWMDaDszirw2+pp22VdRrPZNA9NWXheEDYOLyQekyL2CfidhxhaXvUZyWg\n"
"alLyF2XRZ5/jAT+NjfWw39EmWPUGk13Jm83OaFc1VdrXNCiD0sGCQ+BTCllDinQv\n"
"R08yzd4fzA3YXthvX1dBu1SvqQAGOS7gssRCyv9uWI6MXta25X91eY1ZMz1euJ04\n"
"mB8EdyYiZc0kzrb9dv5d0g==");
*cert_data_count = 1;
return 0;
} else if (!strcmp(name, "client_cert_list")) {
*cert_paths = malloc(sizeof **cert_paths);
(*cert_paths)[0] = strdup(TESTS_DIR "/data/client.crt");
*cert_path_count = 1;
return 0;
}
return 1;
}
static void *
endpt_set_address_thread(void *arg)
{
(void)arg;
int ret;
pthread_barrier_wait(&barrier);
ret = nc_server_endpt_set_address("quaternary", "0.0.0.0");
nc_assert(!ret);
return NULL;
}
static void *
endpt_set_port_thread(void *arg)
{
(void)arg;
int ret;
pthread_barrier_wait(&barrier);
ret = nc_server_endpt_set_port("quaternary", 6003);
nc_assert(!ret);
return NULL;
}
static void *
tls_endpt_set_server_cert_thread(void *arg)
{
(void)arg;
int ret;
pthread_barrier_wait(&barrier);
ret = nc_server_tls_endpt_set_server_cert("quaternary", "server_cert1");
nc_assert(!ret);
nc_thread_destroy();
return NULL;
}
static void *
tls_endpt_add_trusted_cert_list_thread(void *arg)
{
(void)arg;
int ret;
pthread_barrier_wait(&barrier);
ret = nc_server_tls_endpt_add_trusted_cert_list("quaternary", "trusted_cert_list1");
nc_assert(!ret);
nc_thread_destroy();
return NULL;
}
static void *
tls_endpt_set_trusted_ca_paths_thread(void *arg)
{
(void)arg;
int ret;
pthread_barrier_wait(&barrier);
ret = nc_server_tls_endpt_set_trusted_ca_paths("quaternary", TESTS_DIR "/data/serverca.pem", "data");
nc_assert(!ret);
nc_thread_destroy();
return NULL;
}
static void *
tls_endpt_del_trusted_cert_list_thread(void *arg)
{
(void)arg;
pthread_barrier_wait(&barrier);
nc_server_tls_endpt_del_trusted_cert_list("quaternary", "trusted_cert_list1");
return NULL;
}
static void *
tls_endpt_set_crl_paths_thread(void *arg)
{
(void)arg;
int ret;
pthread_barrier_wait(&barrier);
ret = nc_server_tls_endpt_set_crl_paths("quaternary", NULL, "data");
nc_assert(!ret);
nc_thread_destroy();
return NULL;
}
static void *
tls_endpt_clear_crls_thread(void *arg)
{
(void)arg;
pthread_barrier_wait(&barrier);
nc_server_tls_endpt_clear_crls("quaternary");
return NULL;
}
static void *
tls_endpt_add_ctn_thread(void *arg)
{
(void)arg;
int ret;
pthread_barrier_wait(&barrier);
ret = nc_server_tls_endpt_add_ctn("main_tls", 2, "02:F0:F1:F2:F3:F4:F5:F6:F7:F8:F9:10:11:12:EE:FF:A0:A1:A2:A3",
NC_TLS_CTN_SAN_IP_ADDRESS, NULL);
nc_assert(!ret);
return NULL;
}
static void *
tls_endpt_del_ctn_thread(void *arg)
{
(void)arg;
int ret;
pthread_barrier_wait(&barrier);
ret = nc_server_tls_endpt_del_ctn("main_tls", -1, NULL, NC_TLS_CTN_SAN_ANY, NULL);
nc_assert(!ret);
return NULL;
}
static void *
tls_client_thread(void *arg)
{
int ret, read_pipe = *(int *)arg;
char buf[9];
struct nc_session *session;
fprintf(stdout, "TLS client start.\n");
ret = read(read_pipe, buf, 9);
nc_assert(ret == 9);
nc_assert(!strncmp(buf, "tls_ready", 9));
ret = nc_client_tls_set_cert_key_paths(TESTS_DIR "/data/client.crt", TESTS_DIR "/data/client.key");
nc_assert(!ret);
ret = nc_client_tls_set_trusted_ca_paths(NULL, TESTS_DIR "/data");
nc_assert(!ret);
session = nc_connect_tls("127.0.0.1", 6501, NULL);
nc_assert(session);
/* verify some capabilities */
nc_assert(nc_session_cpblt(session, "urn:jmu:params:xml:ns:yang:module-a?module=module-a&deviations=module-a-dv,module-a-dv2"));
nc_session_free(session, NULL);
fprintf(stdout, "TLS client finished.\n");
nc_thread_destroy();
return NULL;
}
#endif /* NC_ENABLED_TLS */
static void *(*thread_funcs[])(void *) = {
#if defined (NC_ENABLED_SSH) || defined (NC_ENABLED_TLS)
server_thread,
#endif
#ifdef NC_ENABLED_SSH
add_endpt_thread,
del_endpt_thread,
ssh_endpt_set_hostkey_thread,
ssh_endpt_set_auth_methods_thread,
ssh_endpt_set_auth_attempts_thread,
ssh_endpt_set_auth_timeout_thread,
ssh_endpt_add_authkey_thread,
ssh_endpt_del_authkey_thread,
#endif
#ifdef NC_ENABLED_TLS
endpt_set_address_thread,
endpt_set_port_thread,
tls_endpt_set_server_cert_thread,
tls_endpt_add_trusted_cert_list_thread,
tls_endpt_set_trusted_ca_paths_thread,
tls_endpt_del_trusted_cert_list_thread,
tls_endpt_set_crl_paths_thread,
tls_endpt_clear_crls_thread,
tls_endpt_add_ctn_thread,
tls_endpt_del_ctn_thread,
#endif
};
const int thread_count = sizeof thread_funcs / sizeof *thread_funcs;
#if defined (NC_ENABLED_SSH) && defined (NC_ENABLED_TLS)
const int client_count = 2;
pid_t pids[2];
int pipes[4];
#else
const int client_count = 1;
pid_t pids[1];
int pipes[2];
#endif
static void
client_fork(void)
{
int ret, clients = 0;
#ifdef NC_ENABLED_SSH
nc_assert(pipe(pipes + clients * 2) == 0);
if (!(pids[clients] = fork())) {
nc_client_init();
ret = nc_client_set_schema_searchpath(TESTS_DIR "/data/modules");
nc_assert(!ret);
/* close write */
close(pipes[clients * 2 + 1]);
ssh_client_thread(&pipes[clients * 2]);
close(pipes[clients * 2]);
nc_client_destroy();
exit(0);
}
/* close read */
close(pipes[clients * 2]);
++clients;
#endif
#ifdef NC_ENABLED_TLS
nc_assert(pipe(pipes + clients * 2) == 0);
if (!(pids[clients] = fork())) {
nc_client_init();
ret = nc_client_set_schema_searchpath(TESTS_DIR "/data/modules");
nc_assert(!ret);
/* close write */
close(pipes[clients * 2 + 1]);
tls_client_thread(&pipes[clients * 2]);
close(pipes[clients * 2]);
nc_client_destroy();
exit(0);
}
/* close read */
close(pipes[clients * 2]);
++clients;
#endif
}
#endif
int
main(void)
{
#if _POSIX_BARRIERS >= 200112L
struct ly_ctx *ctx;
int ret, i, clients = 0;
pthread_t tids[thread_count];
nc_verbosity(NC_VERB_VERBOSE);
client_fork();
ly_ctx_new(TESTS_DIR "/data/modules", 0, &ctx);
nc_assert(ctx);
ly_ctx_load_module(ctx, "ietf-netconf", NULL, NULL);
/* load some application models with deviations */
nc_assert(ly_ctx_load_module(ctx, "module-a", NULL, NULL));
nc_assert(ly_ctx_load_module(ctx, "module-a-dv", NULL, NULL));
nc_assert(ly_ctx_load_module(ctx, "module-a-dv2", NULL, NULL));
nc_server_init(ctx);
pthread_barrier_init(&barrier, NULL, thread_count);
#ifdef NC_ENABLED_SSH
/* set callback */
nc_server_ssh_set_hostkey_clb(clb_hostkeys, NULL, NULL);
/* do first, so that client can connect on SSH */
ret = nc_server_add_endpt("main_ssh", NC_TI_LIBSSH);
nc_assert(!ret);
ret = nc_server_endpt_set_address("main_ssh", "0.0.0.0");
nc_assert(!ret);
ret = nc_server_endpt_set_port("main_ssh", 6001);
nc_assert(!ret);
ret = nc_server_ssh_add_authkey_path(TESTS_DIR "/data/key_ecdsa.pub", "test");
nc_assert(!ret);
ret = nc_server_ssh_endpt_add_hostkey("main_ssh", "key_rsa", -1);
nc_assert(!ret);
/* client ready */
ret = write(pipes[clients * 2 + 1], "ssh_ready", 9);
nc_assert(ret == 9);
++clients;
/* for ssh_endpt_del_authkey */
ret = nc_server_ssh_add_authkey_path(TESTS_DIR "/data/key_dsa.pub", "test2");
nc_assert(!ret);
ret = nc_server_add_endpt("secondary", NC_TI_LIBSSH);
nc_assert(!ret);
#endif
#ifdef NC_ENABLED_TLS
/* set callbacks */
nc_server_tls_set_server_cert_clb(clb_server_cert, NULL, NULL);
nc_server_tls_set_trusted_cert_list_clb(clb_trusted_cert_lists, NULL, NULL);
/* do first, so that client can connect on TLS */
ret = nc_server_add_endpt("main_tls", NC_TI_OPENSSL);
nc_assert(!ret);
ret = nc_server_endpt_set_address("main_tls", "0.0.0.0");
nc_assert(!ret);
ret = nc_server_endpt_set_port("main_tls", 6501);
nc_assert(!ret);
ret = nc_server_tls_endpt_set_server_cert("main_tls", "main_cert");
nc_assert(!ret);
ret = nc_server_tls_endpt_add_trusted_cert_list("main_tls", "client_cert_list");
nc_assert(!ret);
ret = nc_server_tls_endpt_add_ctn("main_tls", 0, "02:B3:9F:26:65:76:6B:CC:FC:86:8E:D4:1A:81:64:0F:92:EB:18:AE:FF", NC_TLS_CTN_SPECIFIED, "test");
nc_assert(!ret);
/* client ready */
ret = write(pipes[clients * 2 + 1], "tls_ready", 9);
nc_assert(ret == 9);
++clients;
/* for tls_endpt_del_ctn */
ret = nc_server_tls_endpt_add_ctn("main_tls", 1, "fc00:db20:35b:7399::5:77:88:99:AA:BB:CC:DD:EE:FF:A0:A1:A2:A3", NC_TLS_CTN_SAN_ANY, NULL);
nc_assert(!ret);
ret = nc_server_add_endpt("quaternary", NC_TI_OPENSSL);
nc_assert(!ret);
#endif
/* threads'n'stuff */
ret = 0;
for (i = 0; i < thread_count; ++i) {
ret += pthread_create(&tids[i], NULL, thread_funcs[i], NULL);
}
nc_assert(!ret);
/* cleanup */
for (i = 0; i < thread_count; ++i) {
pthread_join(tids[i], NULL);
}
for (i = 0; i < client_count; ++i) {
waitpid(pids[i], NULL, 0);
close(pipes[i * 2 + 1]);
}
pthread_barrier_destroy(&barrier);
nc_server_destroy();
ly_ctx_destroy(ctx);
#endif
return 0;
}
|
wungad/libnetconf2 | tests/client/test_client_tls.c | <reponame>wungad/libnetconf2<filename>tests/client/test_client_tls.c
#include <errno.h>
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <cmocka.h>
#include <config.h>
#include <libyang/libyang.h>
#include <log.h>
#include <session_client.h>
#include "tests/config.h"
static int
setup_f(void **state)
{
(void)state;
nc_verbosity(NC_VERB_VERBOSE);
return 0;
}
static int
teardown_f(void **state)
{
(void)state;
return 0;
}
MOCK int
__wrap_connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen)
{
(void)sockfd;
(void)addr;
(void)addrlen;
return (int)mock();
}
MOCK int
__wrap_SSL_connect(SSL *ssl)
{
(void)ssl;
return (int)mock();
}
MOCK int
__wrap_nc_handshake_io(struct nc_session *session)
{
(void)session;
return (int)mock();
}
MOCK int
__wrap_nc_ctx_check_and_fill(struct nc_session *session)
{
(void)session;
return (int)mock();
}
static void
test_nc_client_tls_setting_cert_key_paths(void **state)
{
(void)state;
const char *cert, *key;
int ret;
nc_client_init();
/* no certificats are set, nc_client_tls_get_cert_key_paths should output NULL */
nc_client_tls_get_cert_key_paths(&cert, &key);
assert_null(cert);
assert_null(key);
/* set certificate path */
ret = nc_client_tls_set_cert_key_paths("cert_path", "key_path");
assert_int_equal(ret, 0);
nc_client_tls_get_cert_key_paths(&cert, &key);
assert_string_equal(cert, "cert_path");
assert_string_equal(key, "key_path");
/* override certificate path */
ret = nc_client_tls_set_cert_key_paths("cert_path1", "key_path1");
assert_int_equal(ret, 0);
nc_client_tls_get_cert_key_paths(&cert, &key);
assert_string_equal(cert, "cert_path1");
assert_string_equal(key, "key_path1");
}
static void
test_nc_client_tls_setting_trusted_ca_paths(void **state)
{
(void)state;
const char *file, *dir;
int ret;
ret = nc_client_tls_set_trusted_ca_paths("ca_file", "ca_dir");
assert_int_equal(ret, 0);
nc_client_tls_get_trusted_ca_paths(&file, &dir);
assert_string_equal("ca_file", file);
assert_string_equal("ca_dir", dir);
ret = nc_client_tls_set_trusted_ca_paths("ca_file1", "ca_dir1");
assert_int_equal(ret, 0);
nc_client_tls_get_trusted_ca_paths(&file, &dir);
assert_string_equal("ca_file1", file);
assert_string_equal("ca_dir1", dir);
}
static void
test_nc_connect_tls_succesfull(void **state)
{
(void)state;
int ret;
struct nc_session *session;
ret = nc_client_tls_set_cert_key_paths(TESTS_DIR "/data/client.crt", TESTS_DIR "/data/client.key");
assert_int_equal(ret, 0);
ret = nc_client_tls_set_trusted_ca_paths(NULL, TESTS_DIR "/data");
assert_int_equal(ret, 0);
will_return(__wrap_connect, 0);
will_return(__wrap_SSL_connect, 1);
/* fake succesfull handshake */
will_return(__wrap_nc_handshake_io, 3);
will_return(__wrap_nc_ctx_check_and_fill, 0);
session = nc_connect_tls("0.0.0.0", 6001, NULL);
assert_non_null(session);
nc_session_free(session, NULL);
}
static void
test_nc_client_tls_setting_crl_paths(void **state)
{
(void)state;
const char *file, *dir;
int ret;
nc_client_tls_get_crl_paths(&file, &dir);
assert_null(file);
assert_null(dir);
ret = nc_client_tls_set_crl_paths("file", "dir");
assert_int_equal(ret, 0);
nc_client_tls_get_crl_paths(&file, &dir);
assert_string_equal(file, "file");
assert_string_equal(dir, "dir");
ret = nc_client_tls_set_crl_paths("file1", "dir1");
assert_int_equal(ret, 0);
nc_client_tls_get_crl_paths(&file, &dir);
assert_string_equal(file, "file1");
assert_string_equal(dir, "dir1");
/* destroy client */
nc_client_destroy();
}
static void
test_nc_connect_tls_handshake_failed(void **state)
{
(void)state;
int ret;
struct nc_session *session;
ret = nc_client_tls_set_cert_key_paths(TESTS_DIR "/data/client.crt", TESTS_DIR "/data/client.key");
assert_int_equal(ret, 0);
ret = nc_client_tls_set_trusted_ca_paths(NULL, TESTS_DIR "/data");
assert_int_equal(ret, 0);
will_return(__wrap_connect, 0);
will_return(__wrap_SSL_connect, 1);
/* fake failed handshake */
will_return(__wrap_nc_handshake_io, 0);
session = nc_connect_tls("0.0.0.0", 6001, NULL);
assert_null(session);
}
int
main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test_setup_teardown(test_nc_client_tls_setting_cert_key_paths, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_connect_tls_handshake_failed, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_connect_tls_succesfull, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_client_tls_setting_trusted_ca_paths, setup_f, teardown_f),
cmocka_unit_test_setup_teardown(test_nc_client_tls_setting_crl_paths, setup_f, teardown_f),
};
return cmocka_run_group_tests(tests, NULL, NULL);
}
|
SoundMetrics/aris-file-sdk | type-definitions/C/FileHeader.h | // FileHeader.h
// THIS IS GENERATED WITH GenerateHeader, DO NOT MODIFY
#ifndef ARIS_ARISFILEHEADER_H
#define ARIS_ARISFILEHEADER_H
#include <stdint.h>
#define ARIS_FILE_SIGNATURE 0x05464444
#define ARIS_FRAME_SIGNATURE 0x05464444
#pragma pack(push, 1)
// Defines the metadata at the start of an ARIS recording.
struct ArisFileHeader {
// File format version DDF_05 = 0x05464444
uint32_t Version;
// Total frames in file
// Note: Writers should populate; readers should calculate the number of frames from file size & beams*samples.
uint32_t FrameCount;
// Initial recorded frame rate
// OBSOLETE: See frame header instead.
uint32_t FrameRate;
// Non-zero if HF, zero if LF
// OBSOLETE: See frame header instead.
uint32_t HighResolution;
// ARIS 3000 = 128/64, ARIS 1800 = 96/48, ARIS 1200 = 48
// Note: Writers should populate; readers should see frame header instead.
uint32_t NumRawBeams;
// 1/Sample Period
// OBSOLETE: See frame header instead.
float SampleRate;
// Number of range samples in each beam
// Note: Writers should populate; readers should see frame header instead.
uint32_t SamplesPerChannel;
// Relative gain in dB: 0 - 40
// OBSOLETE: See frame header instead.
uint32_t ReceiverGain;
// Image window start range in meters (code [0..31] in DIDSON)
// OBSOLETE: See frame header instead.
float WindowStart;
// Image window length in meters (code [0..3] in DIDSON)
// OBSOLETE: See frame header instead.
float WindowLength;
// Non-zero = lens down (DIDSON) or lens up (ARIS), zero = opposite
// OBSOLETE: See frame header instead.
uint32_t Reverse;
// Sonar serial number
uint32_t SN;
// Date that file was recorded
char strDate[32];
// User input to identify file in 256 characters
char strHeaderID[256];
// User-defined integer quantity
int32_t UserID1;
// User-defined integer quantity
int32_t UserID2;
// User-defined integer quantity
int32_t UserID3;
// User-defined integer quantity
int32_t UserID4;
// First frame number from source file (for DIDSON snippet files)
uint32_t StartFrame;
// Last frame number from source file (for DIDSON snippet files)
uint32_t EndFrame;
// Non-zero indicates time lapse recording
uint32_t TimeLapse;
// Number of frames/seconds between recorded frames
uint32_t RecordInterval;
// Frames or seconds interval
uint32_t RadioSeconds;
// Record every Nth frame
uint32_t FrameInterval;
// See DDF_04 file format document
// OBSOLETE: Obsolete.
uint32_t Flags;
// See DDF_04 file format document
uint32_t AuxFlags;
// Sound velocity in water
// OBSOLETE: See frame header instead.
uint32_t Sspd;
// See DDF_04 file format document
uint32_t Flags3D;
// DIDSON software version that recorded the file
uint32_t SoftwareVersion;
// Water temperature code: 0 = 5-15C, 1 = 15-25C, 2 = 25-35C
uint32_t WaterTemp;
// Salinity code: 0 = fresh, 1 = brackish, 2 = salt
uint32_t Salinity;
// Added for ARIS but not used
uint32_t PulseLength;
// Added for ARIS but not used
uint32_t TxMode;
// Reserved for future use
uint32_t VersionFGPA;
// Reserved for future use
uint32_t VersionPSuC;
// Frame index of frame used for thumbnail image of file
uint32_t ThumbnailFI;
// Total file size in bytes
// OBSOLETE: Do not use; query your filesystem instead.
uint64_t FileSize;
// Reserved for future use
// OBSOLETE: Obsolete; not used.
uint64_t OptionalHeaderSize;
// Reserved for future use
// OBSOLETE: Obsolete; not used.
uint64_t OptionalTailSize;
// DIDSON_ADJUSTED_VERSION_MINOR
// OBSOLETE: Obsolete.
uint32_t VersionMinor;
// Non-zero if telephoto lens (large lens, hi-res lens, big lens) is present
// OBSOLETE: See frame header instead.
uint32_t LargeLens;
// Padding to fill out to 1024 bytes
char padding[568];
};
#pragma pack(pop)
// In general the struct above should be used rather than the offsets.
// The 'ArisFileHeader' prefix prevents name conflicts between the file and frame headers
enum ArisFileHeaderOffsets {
ArisFileHeaderOffset_Version = 0,
ArisFileHeaderOffset_FrameCount = 4,
// OBSOLETE: See frame header instead.
ArisFileHeaderOffset_FrameRate = 8,
// OBSOLETE: See frame header instead.
ArisFileHeaderOffset_HighResolution = 12,
ArisFileHeaderOffset_NumRawBeams = 16,
// OBSOLETE: See frame header instead.
ArisFileHeaderOffset_SampleRate = 20,
ArisFileHeaderOffset_SamplesPerChannel = 24,
// OBSOLETE: See frame header instead.
ArisFileHeaderOffset_ReceiverGain = 28,
// OBSOLETE: See frame header instead.
ArisFileHeaderOffset_WindowStart = 32,
// OBSOLETE: See frame header instead.
ArisFileHeaderOffset_WindowLength = 36,
// OBSOLETE: See frame header instead.
ArisFileHeaderOffset_Reverse = 40,
ArisFileHeaderOffset_SN = 44,
ArisFileHeaderOffset_strDate = 48,
ArisFileHeaderOffset_strHeaderID = 80,
ArisFileHeaderOffset_UserID1 = 336,
ArisFileHeaderOffset_UserID2 = 340,
ArisFileHeaderOffset_UserID3 = 344,
ArisFileHeaderOffset_UserID4 = 348,
ArisFileHeaderOffset_StartFrame = 352,
ArisFileHeaderOffset_EndFrame = 356,
ArisFileHeaderOffset_TimeLapse = 360,
ArisFileHeaderOffset_RecordInterval = 364,
ArisFileHeaderOffset_RadioSeconds = 368,
ArisFileHeaderOffset_FrameInterval = 372,
// OBSOLETE: Obsolete.
ArisFileHeaderOffset_Flags = 376,
ArisFileHeaderOffset_AuxFlags = 380,
// OBSOLETE: See frame header instead.
ArisFileHeaderOffset_Sspd = 384,
ArisFileHeaderOffset_Flags3D = 388,
ArisFileHeaderOffset_SoftwareVersion = 392,
ArisFileHeaderOffset_WaterTemp = 396,
ArisFileHeaderOffset_Salinity = 400,
ArisFileHeaderOffset_PulseLength = 404,
ArisFileHeaderOffset_TxMode = 408,
ArisFileHeaderOffset_VersionFGPA = 412,
ArisFileHeaderOffset_VersionPSuC = 416,
ArisFileHeaderOffset_ThumbnailFI = 420,
// OBSOLETE: Do not use; query your filesystem instead.
ArisFileHeaderOffset_FileSize = 424,
// OBSOLETE: Obsolete; not used.
ArisFileHeaderOffset_OptionalHeaderSize = 432,
// OBSOLETE: Obsolete; not used.
ArisFileHeaderOffset_OptionalTailSize = 440,
// OBSOLETE: Obsolete.
ArisFileHeaderOffset_VersionMinor = 448,
// OBSOLETE: See frame header instead.
ArisFileHeaderOffset_LargeLens = 452,
};
#endif // !ARIS_ARISFILEHEADER_H
|
SoundMetrics/aris-file-sdk | beam-width-metrics/BeamWidths_ARIS3000_128.h | <reponame>SoundMetrics/aris-file-sdk<filename>beam-width-metrics/BeamWidths_ARIS3000_128.h
// Copyright 2010-2018 Sound Metrics corporation
//
// Approximate Beam Angles for ARIS3000 (128 channels)
//
// beam, center, left, right
DEFINE_BEAMWIDTH3(0, -15.0068, -15.1218, -14.8918)
DEFINE_BEAMWIDTH3(1, -14.7768, -14.8918, -14.6615)
DEFINE_BEAMWIDTH3(2, -14.5462, -14.6615, -14.4306)
DEFINE_BEAMWIDTH3(3, -14.3150, -14.4306, -14.1992)
DEFINE_BEAMWIDTH3(4, -14.0833, -14.1992, -13.9672)
DEFINE_BEAMWIDTH3(5, -13.8511, -13.9672, -13.7349)
DEFINE_BEAMWIDTH3(6, -13.6186, -13.7349, -13.5022)
DEFINE_BEAMWIDTH3(7, -13.3858, -13.5022, -13.2693)
DEFINE_BEAMWIDTH3(8, -13.1528, -13.2693, -13.0362)
DEFINE_BEAMWIDTH3(9, -12.9196, -13.0362, -12.8029)
DEFINE_BEAMWIDTH3(10, -12.6861, -12.8029, -12.5692)
DEFINE_BEAMWIDTH3(11, -12.4523, -12.5692, -12.3353)
DEFINE_BEAMWIDTH3(12, -12.2182, -12.3353, -12.101)
DEFINE_BEAMWIDTH3(13, -11.9838, -12.101, -11.8665)
DEFINE_BEAMWIDTH3(14, -11.7491, -11.8665, -11.6316)
DEFINE_BEAMWIDTH3(15, -11.5141, -11.6316, -11.3965)
DEFINE_BEAMWIDTH3(16, -11.2789, -11.3965, -11.1612)
DEFINE_BEAMWIDTH3(17, -11.0435, -11.1612, -10.9257)
DEFINE_BEAMWIDTH3(18, -10.8079, -10.9257, -10.6900)
DEFINE_BEAMWIDTH3(19, -10.5721, -10.6900, -10.4541)
DEFINE_BEAMWIDTH3(20, -10.3361, -10.4541, -10.218)
DEFINE_BEAMWIDTH3(21, -10.0999, -10.218, -9.9817)
DEFINE_BEAMWIDTH3(22, -9.8635, -9.9817, -9.7452)
DEFINE_BEAMWIDTH3(23, -9.6269, -9.7452, -9.5086)
DEFINE_BEAMWIDTH3(24, -9.3902, -9.5086, -9.2718)
DEFINE_BEAMWIDTH3(25, -9.1534, -9.2718, -9.0350)
DEFINE_BEAMWIDTH3(26, -8.9165, -9.0350, -8.7980)
DEFINE_BEAMWIDTH3(27, -8.6795, -8.7980, -8.5610)
DEFINE_BEAMWIDTH3(28, -8.4424, -8.5610, -8.3239)
DEFINE_BEAMWIDTH3(29, -8.2053, -8.3239, -8.0868)
DEFINE_BEAMWIDTH3(30, -7.9682, -8.0868, -7.8496)
DEFINE_BEAMWIDTH3(31, -7.7310, -7.8496, -7.6124)
DEFINE_BEAMWIDTH3(32, -7.4938, -7.6124, -7.3752)
DEFINE_BEAMWIDTH3(33, -7.2566, -7.3752, -7.1380)
DEFINE_BEAMWIDTH3(34, -7.0193, -7.1380, -6.9007)
DEFINE_BEAMWIDTH3(35, -6.7820, -6.9007, -6.6633)
DEFINE_BEAMWIDTH3(36, -6.5446, -6.6633, -6.4259)
DEFINE_BEAMWIDTH3(37, -6.3072, -6.4259, -6.1885)
DEFINE_BEAMWIDTH3(38, -6.0698, -6.1885, -5.9511)
DEFINE_BEAMWIDTH3(39, -5.8324, -5.9511, -5.7137)
DEFINE_BEAMWIDTH3(40, -5.5949, -5.7137, -5.4762)
DEFINE_BEAMWIDTH3(41, -5.3574, -5.4762, -5.2387)
DEFINE_BEAMWIDTH3(42, -5.1199, -5.2387, -5.0011)
DEFINE_BEAMWIDTH3(43, -4.8823, -5.0011, -4.7635)
DEFINE_BEAMWIDTH3(44, -4.6447, -4.7635, -4.5259)
DEFINE_BEAMWIDTH3(45, -4.4071, -4.5259, -4.2883)
DEFINE_BEAMWIDTH3(46, -4.1695, -4.2883, -4.0507)
DEFINE_BEAMWIDTH3(47, -3.9318, -4.0507, -3.8130)
DEFINE_BEAMWIDTH3(48, -3.6941, -3.8130, -3.5753)
DEFINE_BEAMWIDTH3(49, -3.4564, -3.5753, -3.3376)
DEFINE_BEAMWIDTH3(50, -3.2187, -3.3376, -3.0998)
DEFINE_BEAMWIDTH3(51, -2.9809, -3.0998, -2.8620)
DEFINE_BEAMWIDTH3(52, -2.7430, -2.8620, -2.6240)
DEFINE_BEAMWIDTH3(53, -2.5050, -2.6240, -2.3860)
DEFINE_BEAMWIDTH3(54, -2.2669, -2.3860, -2.1478)
DEFINE_BEAMWIDTH3(55, -2.0287, -2.1478, -1.9096)
DEFINE_BEAMWIDTH3(56, -1.7904, -1.9096, -1.6712)
DEFINE_BEAMWIDTH3(57, -1.5520, -1.6712, -1.4328)
DEFINE_BEAMWIDTH3(58, -1.3135, -1.4328, -1.1942)
DEFINE_BEAMWIDTH3(59, -1.0749, -1.1942, -0.9556)
DEFINE_BEAMWIDTH3(60, -0.8362, -0.9556, -0.7168)
DEFINE_BEAMWIDTH3(61, -0.5974, -0.7168, -0.4780)
DEFINE_BEAMWIDTH3(62, -0.3585, -0.4780, -0.2391)
DEFINE_BEAMWIDTH3(63, -0.1196, -0.2391, -0.0001)
DEFINE_BEAMWIDTH3(64, 0.1194, -0.0001, 0.2389)
DEFINE_BEAMWIDTH3(65, 0.3584, 0.2389, 0.4779)
DEFINE_BEAMWIDTH3(66, 0.5973, 0.4779, 0.7168)
DEFINE_BEAMWIDTH3(67, 0.8362, 0.7168, 0.9556)
DEFINE_BEAMWIDTH3(68, 1.0750, 0.9556, 1.1944)
DEFINE_BEAMWIDTH3(69, 1.3137, 1.1944, 1.4330)
DEFINE_BEAMWIDTH3(70, 1.5523, 1.4330, 1.6716)
DEFINE_BEAMWIDTH3(71, 1.7908, 1.6716, 1.9100)
DEFINE_BEAMWIDTH3(72, 2.0292, 1.9100, 2.1484)
DEFINE_BEAMWIDTH3(73, 2.2675, 2.1484, 2.3866)
DEFINE_BEAMWIDTH3(74, 2.5057, 2.3866, 2.6248)
DEFINE_BEAMWIDTH3(75, 2.7438, 2.6248, 2.8628)
DEFINE_BEAMWIDTH3(76, 2.9818, 2.8628, 3.1008)
DEFINE_BEAMWIDTH3(77, 3.2197, 3.1008, 3.3386)
DEFINE_BEAMWIDTH3(78, 3.4575, 3.3386, 3.5764)
DEFINE_BEAMWIDTH3(79, 3.6952, 3.5764, 3.8141)
DEFINE_BEAMWIDTH3(80, 3.9329, 3.8141, 4.0518)
DEFINE_BEAMWIDTH3(81, 4.1706, 4.0518, 4.2895)
DEFINE_BEAMWIDTH3(82, 4.4083, 4.2895, 4.5271)
DEFINE_BEAMWIDTH3(83, 4.6459, 4.5271, 4.7647)
DEFINE_BEAMWIDTH3(84, 4.8835, 4.7647, 5.0023)
DEFINE_BEAMWIDTH3(85, 5.1211, 5.0023, 5.2399)
DEFINE_BEAMWIDTH3(86, 5.3587, 5.2399, 5.4775)
DEFINE_BEAMWIDTH3(87, 5.5962, 5.4775, 5.7150)
DEFINE_BEAMWIDTH3(88, 5.8337, 5.7150, 5.9525)
DEFINE_BEAMWIDTH3(89, 6.0712, 5.9525, 6.1899)
DEFINE_BEAMWIDTH3(90, 6.3086, 6.1899, 6.4273)
DEFINE_BEAMWIDTH3(91, 6.5460, 6.4273, 6.6647)
DEFINE_BEAMWIDTH3(92, 6.7834, 6.6647, 6.9021)
DEFINE_BEAMWIDTH3(93, 7.0208, 6.9021, 7.1395)
DEFINE_BEAMWIDTH3(94, 7.2581, 7.1395, 7.3768)
DEFINE_BEAMWIDTH3(95, 7.4954, 7.3768, 7.6140)
DEFINE_BEAMWIDTH3(96, 7.7326, 7.6140, 7.8512)
DEFINE_BEAMWIDTH3(97, 7.9698, 7.8512, 8.0884)
DEFINE_BEAMWIDTH3(98, 8.2070, 8.0884, 8.3256)
DEFINE_BEAMWIDTH3(99, 8.4441, 8.3256, 8.5627)
DEFINE_BEAMWIDTH3(100, 8.6812, 8.5627, 8.7998)
DEFINE_BEAMWIDTH3(101, 8.9183, 8.7998, 9.0368)
DEFINE_BEAMWIDTH3(102, 9.1553, 9.0368, 9.2738)
DEFINE_BEAMWIDTH3(103, 9.3922, 9.2738, 9.5106)
DEFINE_BEAMWIDTH3(104, 9.6290, 9.5106, 9.7474)
DEFINE_BEAMWIDTH3(105, 9.8657, 9.7474, 9.9840)
DEFINE_BEAMWIDTH3(106, 10.1023, 9.9840, 10.2205)
DEFINE_BEAMWIDTH3(107, 10.3387, 10.2205, 10.4568)
DEFINE_BEAMWIDTH3(108, 10.5749, 10.4568, 10.6929)
DEFINE_BEAMWIDTH3(109, 10.8109, 10.6929, 10.9288)
DEFINE_BEAMWIDTH3(110, 11.0467, 10.9288, 11.1645)
DEFINE_BEAMWIDTH3(111, 11.2823, 11.1645, 11.4000)
DEFINE_BEAMWIDTH3(112, 11.5177, 11.4000, 11.6353)
DEFINE_BEAMWIDTH3(113, 11.7529, 11.6353, 11.8704)
DEFINE_BEAMWIDTH3(114, 11.9879, 11.8704, 12.1053)
DEFINE_BEAMWIDTH3(115, 12.2226, 12.1053, 12.3398)
DEFINE_BEAMWIDTH3(116, 12.4570, 12.3398, 12.5741)
DEFINE_BEAMWIDTH3(117, 12.6911, 12.5741, 12.8080)
DEFINE_BEAMWIDTH3(118, 12.9249, 12.8080, 13.0417)
DEFINE_BEAMWIDTH3(119, 13.1584, 13.0417, 13.2750)
DEFINE_BEAMWIDTH3(120, 13.3916, 13.2750, 13.5081)
DEFINE_BEAMWIDTH3(121, 13.6246, 13.5081, 13.7410)
DEFINE_BEAMWIDTH3(122, 13.8574, 13.7410, 13.9737)
DEFINE_BEAMWIDTH3(123, 14.0899, 13.9737, 14.2060)
DEFINE_BEAMWIDTH3(124, 14.3221, 14.2060, 14.4380)
DEFINE_BEAMWIDTH3(125, 14.5538, 14.4380, 14.6694)
DEFINE_BEAMWIDTH3(126, 14.7850, 14.6694, 14.9003)
DEFINE_BEAMWIDTH3(127, 15.0156, 14.9003, 15.1306)
|
SoundMetrics/aris-file-sdk | beam-width-metrics/BeamWidths_ARIS_Telephoto_96.h | <reponame>SoundMetrics/aris-file-sdk
// Copyright 2010-2018 Sound Metrics corporation
//
// Updated Beam Angles for ARIS 1800 Telephoto (96 channels)
//
// beam, center, left, right
DEFINE_BEAMWIDTH3(0, -7.419, -7.493, -7.345)
DEFINE_BEAMWIDTH3(1, -7.271, -7.345, -7.197)
DEFINE_BEAMWIDTH3(2, -7.123, -7.197, -7.048)
DEFINE_BEAMWIDTH3(3, -6.974, -7.048, -6.899)
DEFINE_BEAMWIDTH3(4, -6.824, -6.899, -6.749)
DEFINE_BEAMWIDTH3(5, -6.674, -6.749, -6.598)
DEFINE_BEAMWIDTH3(6, -6.523, -6.598, -6.447)
DEFINE_BEAMWIDTH3(7, -6.372, -6.447, -6.296)
DEFINE_BEAMWIDTH3(8, -6.220, -6.296, -6.144)
DEFINE_BEAMWIDTH3(9, -6.068, -6.144, -5.992)
DEFINE_BEAMWIDTH3(10, -5.915, -5.992, -5.839)
DEFINE_BEAMWIDTH3(11, -5.763, -5.839, -5.686)
DEFINE_BEAMWIDTH3(12, -5.609, -5.686, -5.533)
DEFINE_BEAMWIDTH3(13, -5.456, -5.533, -5.379)
DEFINE_BEAMWIDTH3(14, -5.302, -5.379, -5.225)
DEFINE_BEAMWIDTH3(15, -5.148, -5.225, -5.070)
DEFINE_BEAMWIDTH3(16, -4.993, -5.070, -4.915)
DEFINE_BEAMWIDTH3(17, -4.838, -4.915, -4.760)
DEFINE_BEAMWIDTH3(18, -4.682, -4.76, -4.604)
DEFINE_BEAMWIDTH3(19, -4.526, -4.604, -4.448)
DEFINE_BEAMWIDTH3(20, -4.370, -4.448, -4.291)
DEFINE_BEAMWIDTH3(21, -4.213, -4.291, -4.134)
DEFINE_BEAMWIDTH3(22, -4.055, -4.134, -3.976)
DEFINE_BEAMWIDTH3(23, -3.897, -3.976, -3.818)
DEFINE_BEAMWIDTH3(24, -3.739, -3.818, -3.660)
DEFINE_BEAMWIDTH3(25, -3.581, -3.660, -3.501)
DEFINE_BEAMWIDTH3(26, -3.422, -3.501, -3.343)
DEFINE_BEAMWIDTH3(27, -3.264, -3.343, -3.185)
DEFINE_BEAMWIDTH3(28, -3.105, -3.185, -3.026)
DEFINE_BEAMWIDTH3(29, -2.947, -3.026, -2.868)
DEFINE_BEAMWIDTH3(30, -2.788, -2.868, -2.709)
DEFINE_BEAMWIDTH3(31, -2.630, -2.709, -2.550)
DEFINE_BEAMWIDTH3(32, -2.471, -2.550, -2.392)
DEFINE_BEAMWIDTH3(33, -2.313, -2.392, -2.233)
DEFINE_BEAMWIDTH3(34, -2.154, -2.233, -2.075)
DEFINE_BEAMWIDTH3(35, -1.995, -2.075, -1.916)
DEFINE_BEAMWIDTH3(36, -1.836, -1.916, -1.757)
DEFINE_BEAMWIDTH3(37, -1.677, -1.757, -1.598)
DEFINE_BEAMWIDTH3(38, -1.518, -1.598, -1.438)
DEFINE_BEAMWIDTH3(39, -1.359, -1.438, -1.279)
DEFINE_BEAMWIDTH3(40, -1.199, -1.279, -1.119)
DEFINE_BEAMWIDTH3(41, -1.039, -1.119, -0.960)
DEFINE_BEAMWIDTH3(42, -0.880, -0.960, -0.800)
DEFINE_BEAMWIDTH3(43, -0.720, -0.800, -0.640)
DEFINE_BEAMWIDTH3(44, -0.560, -0.640, -0.480)
DEFINE_BEAMWIDTH3(45, -0.400, -0.480, -0.320)
DEFINE_BEAMWIDTH3(46, -0.240, -0.320, -0.160)
DEFINE_BEAMWIDTH3(47, -0.080, -0.160, 0.000)
DEFINE_BEAMWIDTH3(48, 0.080, 0.000, 0.160)
DEFINE_BEAMWIDTH3(49, 0.240, 0.160, 0.320)
DEFINE_BEAMWIDTH3(50, 0.400, 0.320, 0.480)
DEFINE_BEAMWIDTH3(51, 0.560, 0.480, 0.640)
DEFINE_BEAMWIDTH3(52, 0.720, 0.640, 0.800)
DEFINE_BEAMWIDTH3(53, 0.880, 0.800, 0.960)
DEFINE_BEAMWIDTH3(54, 1.039, 0.960, 1.119)
DEFINE_BEAMWIDTH3(55, 1.199, 1.119, 1.279)
DEFINE_BEAMWIDTH3(56, 1.359, 1.279, 1.438)
DEFINE_BEAMWIDTH3(57, 1.518, 1.438, 1.598)
DEFINE_BEAMWIDTH3(58, 1.677, 1.598, 1.757)
DEFINE_BEAMWIDTH3(59, 1.836, 1.757, 1.916)
DEFINE_BEAMWIDTH3(60, 1.995, 1.916, 2.075)
DEFINE_BEAMWIDTH3(61, 2.154, 2.075, 2.233)
DEFINE_BEAMWIDTH3(62, 2.313, 2.233, 2.392)
DEFINE_BEAMWIDTH3(63, 2.471, 2.392, 2.550)
DEFINE_BEAMWIDTH3(64, 2.630, 2.550, 2.709)
DEFINE_BEAMWIDTH3(65, 2.788, 2.709, 2.868)
DEFINE_BEAMWIDTH3(66, 2.947, 2.868, 3.026)
DEFINE_BEAMWIDTH3(67, 3.105, 3.026, 3.185)
DEFINE_BEAMWIDTH3(68, 3.264, 3.185, 3.343)
DEFINE_BEAMWIDTH3(69, 3.422, 3.343, 3.501)
DEFINE_BEAMWIDTH3(70, 3.581, 3.501, 3.660)
DEFINE_BEAMWIDTH3(71, 3.739, 3.660, 3.818)
DEFINE_BEAMWIDTH3(72, 3.897, 3.818, 3.976)
DEFINE_BEAMWIDTH3(73, 4.055, 3.976, 4.134)
DEFINE_BEAMWIDTH3(74, 4.213, 4.134, 4.291)
DEFINE_BEAMWIDTH3(75, 4.370, 4.291, 4.448)
DEFINE_BEAMWIDTH3(76, 4.526, 4.448, 4.605)
DEFINE_BEAMWIDTH3(77, 4.682, 4.605, 4.760)
DEFINE_BEAMWIDTH3(78, 4.838, 4.760, 4.916)
DEFINE_BEAMWIDTH3(79, 4.993, 4.916, 5.070)
DEFINE_BEAMWIDTH3(80, 5.148, 5.070, 5.225)
DEFINE_BEAMWIDTH3(81, 5.302, 5.225, 5.379)
DEFINE_BEAMWIDTH3(82, 5.456, 5.379, 5.533)
DEFINE_BEAMWIDTH3(83, 5.609, 5.533, 5.686)
DEFINE_BEAMWIDTH3(84, 5.763, 5.686, 5.839)
DEFINE_BEAMWIDTH3(85, 5.915, 5.839, 5.992)
DEFINE_BEAMWIDTH3(86, 6.068, 5.992, 6.144)
DEFINE_BEAMWIDTH3(87, 6.220, 6.144, 6.296)
DEFINE_BEAMWIDTH3(88, 6.372, 6.296, 6.448)
DEFINE_BEAMWIDTH3(89, 6.523, 6.448, 6.599)
DEFINE_BEAMWIDTH3(90, 6.674, 6.599, 6.749)
DEFINE_BEAMWIDTH3(91, 6.824, 6.749, 6.899)
DEFINE_BEAMWIDTH3(92, 6.974, 6.899, 7.049)
DEFINE_BEAMWIDTH3(93, 7.123, 7.049, 7.199)
DEFINE_BEAMWIDTH3(94, 7.271, 7.199, 7.345)
DEFINE_BEAMWIDTH3(95, 7.419, 7.345, 7.493)
|
SoundMetrics/aris-file-sdk | sample-code/extract-readings/extract.c | <reponame>SoundMetrics/aris-file-sdk<gh_stars>1-10
// extract
#include "stdio.h"
#include "FileHeader.h"
#include "FrameHeader.h"
#include "FrameFuncs.h"
#include <math.h>
#include <string.h>
#define INVALID_INPUTS -1
#define CANT_OPEN_INPUT -2
#define CANT_OPEN_OUTPUT -3
#define NOT_ARIS_FILE -4
#define CORRUPT_ARIS_FILE -5
#define IO_ERROR -6
int validate_inputs(int argc,
char** argv,
const char** inputPath,
const char** outputPath);
void show_usage(void);
int extract(FILE* fpIn, FILE* fpOut);
int main(int argc, char** argv ) {
const char* inputPath = NULL;
const char* outputPath = NULL;
FILE* fpIn = NULL;
FILE* fpOut = NULL;
if (validate_inputs(argc, argv, &inputPath, &outputPath)) {
show_usage();
return INVALID_INPUTS;
}
fpIn = fopen(inputPath, "rb");
if (!fpIn) {
fprintf(stderr, "Couldn't open the input file.\n");
return CANT_OPEN_INPUT;
}
fpOut = fopen(outputPath, "w");
if (!fpOut) {
fprintf(stderr, "Couldn't open output file.\n");
fclose(fpIn);
return CANT_OPEN_OUTPUT;
}
int result = extract(fpIn, fpOut);
fclose(fpIn);
fclose(fpOut);
if (result) {
fprintf(stderr, "An error occurred while extracting data.\n");
}
return result;
}
void show_usage(void) {
fprintf(stderr, "USAGE:\n");
fprintf(stderr, " extract <input-path> <output-path>\n");
fprintf(stderr, "\n");
}
int validate_inputs(int argc,
char** argv,
const char** inputPath,
const char** outputPath) {
if (argc != 3) {
fprintf(stderr, "Bad number of arguments.\n");
return 1;
}
*inputPath = argv[1];
*outputPath = argv[2];
if (strlen(*inputPath) == 0) {
fprintf(stderr, "No input path.\n");
return 2;
}
if (strlen(*outputPath) == 0) {
fprintf(stderr, "No output path.\n");
return 3;
}
return 0;
}
int extract(FILE* fpIn, FILE* fpOut) {
struct ArisFileHeader fileHeader;
struct ArisFrameHeader frameHeader;
long fileSize = 0, dataSize = 0, frameSize = 0, frameCount = 0;
if (fseek(fpIn, 0, SEEK_END)) {
fprintf(stderr, "Couldn't determine file size.\n");
return IO_ERROR;
}
fileSize = ftell(fpIn);
fseek(fpIn, 0, SEEK_SET);
dataSize = fileSize - sizeof(struct ArisFileHeader);
if (fread(&fileHeader, sizeof(fileHeader), 1, fpIn) != 1) {
fprintf(stderr, "Couldn't read complete file header.\n");
return NOT_ARIS_FILE;
}
if (fileHeader.Version != ARIS_FILE_SIGNATURE) {
fprintf(stderr, "Invalid file header.\n");
return NOT_ARIS_FILE;
}
if (fread(&frameHeader, sizeof(frameHeader), 1, fpIn) != 1) {
fprintf(stderr, "Couldn't read first frame buffer.\n");
return CORRUPT_ARIS_FILE;
}
// ARIS recordings have a consistent frame size all the way through the file.
frameSize = (long)(frameHeader.SamplesPerBeam * get_beams_from_pingmode(frameHeader.PingMode));
frameCount = dataSize / frameSize;
(void)frameCount; // not actually using this variable
fprintf(fpOut, "FrameIndex,FrameTime,WaterTemp\n");
// Print frame data for each frame.
do {
// Note: frames indices start at zero, but always present to the
// user as starting at 1.
fprintf(fpOut, "%u", frameHeader.FrameIndex + 1);
fprintf(fpOut, ",%llu", frameHeader.FrameTime);
if (isnan(frameHeader.WaterTemp)) {
fprintf(fpOut, ",");
}
else {
fprintf(fpOut, ",%f", (double)frameHeader.WaterTemp);
}
fprintf(fpOut, "\n");
// Skip over the frame data
fseek(fpIn, frameSize, SEEK_CUR);
} while (fread(&frameHeader, sizeof(frameHeader), 1, fpIn) == 1);
return 0;
}
|
SoundMetrics/aris-file-sdk | type-definitions/C/FrameHeaderFieldsOnly.h | // Frame number in file
uint32_t FrameIndex;
// PC time stamp when recorded; microseconds since epoch (Jan 1st 1970)
uint64_t FrameTime;
// ARIS file format version = 0x05464444
uint32_t Version;
uint32_t Status;
// On-sonar microseconds since epoch (Jan 1st 1970)
uint64_t sonarTimeStamp;
uint32_t TS_Day;
uint32_t TS_Hour;
uint32_t TS_Minute;
uint32_t TS_Second;
uint32_t TS_Hsecond;
uint32_t TransmitMode;
// Window start in meters
float WindowStart;
// Window length in meters
float WindowLength;
uint32_t Threshold;
int32_t Intensity;
// Note: 0-24 dB
uint32_t ReceiverGain;
// CPU temperature
// Note: Celsius
uint32_t DegC1;
// Power supply temperature
// Note: Celsius
uint32_t DegC2;
// % relative humidity
uint32_t Humidity;
// Focus units 0-1000
uint32_t Focus;
// OBSOLETE: Unused.
uint32_t Battery;
float UserValue1;
float UserValue2;
float UserValue3;
float UserValue4;
float UserValue5;
float UserValue6;
float UserValue7;
float UserValue8;
// Platform velocity from AUV integration
float Velocity;
// Platform depth from AUV integration
float Depth;
// Platform altitude from AUV integration
float Altitude;
// Platform pitch from AUV integration
float Pitch;
// Platform pitch rate from AUV integration
float PitchRate;
// Platform roll from AUV integration
float Roll;
// Platform roll rate from AUV integration
float RollRate;
// Platform heading from AUV integration
float Heading;
// Platform heading rate from AUV integration
float HeadingRate;
// Sonar compass heading output
float CompassHeading;
// Sonar compass pitch output
float CompassPitch;
// Sonar compass roll output
float CompassRoll;
// from auxiliary GPS sensor
double Latitude;
// from auxiliary GPS sensor
double Longitude;
// Note: special for PNNL
float SonarPosition;
uint32_t ConfigFlags;
float BeamTilt;
float TargetRange;
float TargetBearing;
uint32_t TargetPresent;
// OBSOLETE: Unused.
uint32_t FirmwareRevision;
uint32_t Flags;
// Source file frame number for CSOT output files
uint32_t SourceFrame;
// Water temperature from housing temperature sensor
float WaterTemp;
uint32_t TimerPeriod;
// Sonar X location for 3D processing
// Note: Bluefin, external sensor data
float SonarX;
// Sonar Y location for 3D processing
float SonarY;
// Sonar Z location for 3D processing
float SonarZ;
// X2 pan output
float SonarPan;
// X2 tilt output
float SonarTilt;
// X2 roll output
float SonarRoll;
float PanPNNL;
float TiltPNNL;
float RollPNNL;
// Note: special for Bluefin HAUV or other AUV integration
double VehicleTime;
// GPS output from NMEA GGK message
float TimeGGK;
// GPS output from NMEA GGK message
uint32_t DateGGK;
// GPS output from NMEA GGK message
uint32_t QualityGGK;
// GPS output from NMEA GGK message
uint32_t NumSatsGGK;
// GPS output from NMEA GGK message
float DOPGGK;
// GPS output from NMEA GGK message
float EHTGGK;
// external sensor
float HeaveTSS;
// GPS year output
uint32_t YearGPS;
// GPS month output
uint32_t MonthGPS;
// GPS day output
uint32_t DayGPS;
// GPS hour output
uint32_t HourGPS;
// GPS minute output
uint32_t MinuteGPS;
// GPS second output
uint32_t SecondGPS;
// GPS 1/100th second output
uint32_t HSecondGPS;
// Sonar mount location pan offset for 3D processing; meters
float SonarPanOffset;
// Sonar mount location tilt offset for 3D processing
float SonarTiltOffset;
// Sonar mount location roll offset for 3D processing
float SonarRollOffset;
// Sonar mount location X offset for 3D processing
float SonarXOffset;
// Sonar mount location Y offset for 3D processing
float SonarYOffset;
// Sonar mount location Z offset for 3D processing
float SonarZOffset;
// 3D processing transformation matrix
float Tmatrix[16];
// Calculated as 1e6/SamplePeriod
float SampleRate;
// X-axis sonar acceleration
float AccellX;
// Y-axis sonar acceleration
float AccellY;
// Z-axis sonar acceleration
float AccellZ;
// ARIS ping mode
// Note: 1..12
uint32_t PingMode;
// Frequency
// Note: 1 = HF, 0 = LF
uint32_t FrequencyHiLow;
// Width of transmit pulse
// Note: 4..100 microseconds
uint32_t PulseWidth;
// Ping cycle time
// Note: 1802..65535 microseconds
uint32_t CyclePeriod;
// Downrange sample rate
// Note: 4..100 microseconds
uint32_t SamplePeriod;
// 1 = Transmit ON, 0 = Transmit OFF
uint32_t TransmitEnable;
// Instantaneous frame rate between frame N and frame N-1
// Note: microseconds
float FrameRate;
// Sound velocity in water calculated from water temperature depth and salinity setting
// Note: m/s
float SoundSpeed;
// Number of downrange samples in each beam
uint32_t SamplesPerBeam;
// 1 = 150V ON (Max Power), 0 = 150V OFF (Min Power, 12V)
uint32_t Enable150V;
// Delay from transmit until start of sampling (window start) in usec, [930..65535]
uint32_t SampleStartDelay;
// 1 = telephoto lens (large lens, big lens, hi-res lens) present
uint32_t LargeLens;
// 1 = ARIS 3000, 0 = ARIS 1800, 2 = ARIS 1200
uint32_t TheSystemType;
// Sonar serial number as labeled on housing
uint32_t SonarSerialNumber;
// Reserved.
// OBSOLETE: Obsolete
uint64_t ReservedEK;
// Error flag code bits
uint32_t ArisErrorFlagsUint;
// Missed packet count for Ethernet statistics reporting
uint32_t MissedPackets;
// Version number of ArisApp sending frame data
uint32_t ArisAppVersion;
// Reserved for future use
uint32_t Available2;
// 1 = frame data already ordered into [beam,sample] array, 0 = needs reordering
uint32_t ReorderedSamples;
// Water salinity code: 0 = fresh, 15 = brackish, 35 = salt
uint32_t Salinity;
// Depth sensor output
// Note: psi
float Pressure;
// Battery input voltage before power steering
// Note: mV
float BatteryVoltage;
// Main cable input voltage before power steering
// Note: mV
float MainVoltage;
// Input voltage after power steering; filtered voltage
// Note: mV
float SwitchVoltage;
// Note: Added 14-Aug-2012 for AutomaticRecording
uint32_t FocusMotorMoving;
// Note: Added 16-Aug (first two bits = 12V, second two bits = 150V, 00 = not changing, 01 = turning on, 10 = turning off)
uint32_t VoltageChanging;
uint32_t FocusTimeoutFault;
uint32_t FocusOverCurrentFault;
uint32_t FocusNotFoundFault;
uint32_t FocusStalledFault;
uint32_t FPGATimeoutFault;
uint32_t FPGABusyFault;
uint32_t FPGAStuckFault;
uint32_t CPUTempFault;
uint32_t PSUTempFault;
uint32_t WaterTempFault;
uint32_t HumidityFault;
uint32_t PressureFault;
uint32_t VoltageReadFault;
uint32_t VoltageWriteFault;
// Focus shaft current position
// Note: 0..1000 motor units
uint32_t FocusCurrentPosition;
// Commanded pan position
float TargetPan;
// Commanded tilt position
float TargetTilt;
// Commanded roll position
float TargetRoll;
uint32_t PanMotorErrorCode;
uint32_t TiltMotorErrorCode;
uint32_t RollMotorErrorCode;
// Low-resolution magnetic encoder absolute pan position (NaN indicates no arm detected for axis since 2.6.0.8403)
float PanAbsPosition;
// Low-resolution magnetic encoder absolute tilt position (NaN indicates no arm detected for axis since 2.6.0.8403)
float TiltAbsPosition;
// Low-resolution magnetic encoder absolute roll position (NaN indicates no arm detected for axis since 2.6.0.8403)
float RollAbsPosition;
// Accelerometer outputs from AR2 CPU board sensor
// Note: G
float PanAccelX;
// Note: G
float PanAccelY;
// Note: G
float PanAccelZ;
// Note: G
float TiltAccelX;
// Note: G
float TiltAccelY;
// Note: G
float TiltAccelZ;
// Note: G
float RollAccelX;
// Note: G
float RollAccelY;
// Note: G
float RollAccelZ;
// Cookie indices for command acknowlege in frame header
uint32_t AppliedSettings;
// Cookie indices for command acknowlege in frame header
uint32_t ConstrainedSettings;
// Cookie indices for command acknowlege in frame header
uint32_t InvalidSettings;
// If true delay is added between sending out image data packets
uint32_t EnableInterpacketDelay;
// packet delay factor in us (does not include function overhead time)
uint32_t InterpacketDelayPeriod;
// Total time the sonar has been running over its lifetime.
// Note: seconds
uint32_t Uptime;
// Major version number
uint16_t ArisAppVersionMajor;
// Minor version number
uint16_t ArisAppVersionMinor;
// Sonar time when frame cycle is initiated in hardware
uint64_t GoTime;
// AR2 pan velocity
// Note: degrees/second
float PanVelocity;
// AR2 tilt velocity
// Note: degrees/second
float TiltVelocity;
// AR2 roll velocity
// Note: degrees/second
float RollVelocity;
// Age of the last GPS fix acquired; capped at 0xFFFFFFFF; zero if none
// Note: microseconds
uint32_t GpsTimeAge;
// bit 0 = Defender
uint32_t SystemVariant;
// Padding to fill out to 1024 bytes
char padding[288];
|
SoundMetrics/aris-file-sdk | common-code/FrameFuncs.c | <gh_stars>1-10
// FrameFuncs.c
#include "FrameFuncs.h"
size_t get_beams_from_pingmode(uint32_t pingmode) {
switch (pingmode) {
case 1:
case 2:
return 48;
case 3:
case 4:
case 5:
return 96;
case 6:
case 7:
case 8:
return 64;
case 9:
case 10:
case 11:
case 12:
return 128;
}
return 0;
}
|
SoundMetrics/aris-file-sdk | beam-width-metrics/BeamWidths_ARIS3000_64.h | // Copyright 2010-2018 Sound Metrics corporation
//
// Updated Beam Angles for ARIS3000 (64 channels)
//
// beam, center, left, right
DEFINE_BEAMWIDTH3(0, -14.8872, -15.1175, -14.6569)
DEFINE_BEAMWIDTH3(1, -14.4266, -14.6569, -14.1952)
DEFINE_BEAMWIDTH3(2, -13.9637, -14.1952, -13.7314)
DEFINE_BEAMWIDTH3(3, -13.4990, -13.7314, -13.2661)
DEFINE_BEAMWIDTH3(4, -13.0332, -13.2661, -12.7999)
DEFINE_BEAMWIDTH3(5, -12.5665, -12.7999, -12.3326)
DEFINE_BEAMWIDTH3(6, -12.0986, -12.3326, -11.8641)
DEFINE_BEAMWIDTH3(7, -11.6295, -11.8641, -11.3944)
DEFINE_BEAMWIDTH3(8, -11.1593, -11.3944, -10.9238)
DEFINE_BEAMWIDTH3(9, -10.6883, -10.9238, -10.4524)
DEFINE_BEAMWIDTH3(10, -10.2165, -10.4524, -9.9802)
DEFINE_BEAMWIDTH3(11, -9.7439, -9.9802, -9.5073)
DEFINE_BEAMWIDTH3(12, -9.2706, -9.5073, -9.0338)
DEFINE_BEAMWIDTH3(13, -8.7969, -9.0338, -8.5599)
DEFINE_BEAMWIDTH3(14, -8.3228, -8.5599, -8.0857)
DEFINE_BEAMWIDTH3(15, -7.8486, -8.0857, -7.6114)
DEFINE_BEAMWIDTH3(16, -7.3742, -7.6114, -7.1370)
DEFINE_BEAMWIDTH3(17, -6.8997, -7.1370, -6.6624)
DEFINE_BEAMWIDTH3(18, -6.4250, -6.6624, -6.1876)
DEFINE_BEAMWIDTH3(19, -5.9502, -6.1876, -5.7128)
DEFINE_BEAMWIDTH3(20, -5.4753, -5.7128, -5.2378)
DEFINE_BEAMWIDTH3(21, -5.0003, -5.2378, -4.7627)
DEFINE_BEAMWIDTH3(22, -4.5251, -4.7627, -4.2875)
DEFINE_BEAMWIDTH3(23, -4.0499, -4.2875, -3.8122)
DEFINE_BEAMWIDTH3(24, -3.5745, -3.8122, -3.3368)
DEFINE_BEAMWIDTH3(25, -3.0991, -3.3368, -2.8613)
DEFINE_BEAMWIDTH3(26, -2.6234, -2.8613, -2.3854)
DEFINE_BEAMWIDTH3(27, -2.1473, -2.3854, -1.9091)
DEFINE_BEAMWIDTH3(28, -1.6708, -1.9091, -1.4324)
DEFINE_BEAMWIDTH3(29, -1.1939, -1.4324, -0.9553)
DEFINE_BEAMWIDTH3(30, -0.7166, -0.9553, -0.4778)
DEFINE_BEAMWIDTH3(31, -0.2389, -0.4778, 0.0000)
DEFINE_BEAMWIDTH3(32, 0.2389, 0.0000, 0.4778)
DEFINE_BEAMWIDTH3(33, 0.7166, 0.4778, 0.9553)
DEFINE_BEAMWIDTH3(34, 1.1939, 0.9553, 1.4324)
DEFINE_BEAMWIDTH3(35, 1.6708, 1.4324, 1.9091)
DEFINE_BEAMWIDTH3(36, 2.1473, 1.9091, 2.3854)
DEFINE_BEAMWIDTH3(37, 2.6234, 2.3854, 2.8613)
DEFINE_BEAMWIDTH3(38, 3.0991, 2.8613, 3.3368)
DEFINE_BEAMWIDTH3(39, 3.5745, 3.3368, 3.8122)
DEFINE_BEAMWIDTH3(40, 4.0499, 3.8122, 4.2875)
DEFINE_BEAMWIDTH3(41, 4.5251, 4.2875, 4.7627)
DEFINE_BEAMWIDTH3(42, 5.0003, 4.7627, 5.2378)
DEFINE_BEAMWIDTH3(43, 5.4753, 5.2378, 5.7128)
DEFINE_BEAMWIDTH3(44, 5.9502, 5.7128, 6.1876)
DEFINE_BEAMWIDTH3(45, 6.4250, 6.1876, 6.6624)
DEFINE_BEAMWIDTH3(46, 6.8997, 6.6624, 7.1370)
DEFINE_BEAMWIDTH3(47, 7.3742, 7.1370, 7.6114)
DEFINE_BEAMWIDTH3(48, 7.8486, 7.6114, 8.0857)
DEFINE_BEAMWIDTH3(49, 8.3228, 8.0857, 8.5599)
DEFINE_BEAMWIDTH3(50, 8.7969, 8.5599, 9.0338)
DEFINE_BEAMWIDTH3(51, 9.2706, 9.0338, 9.5073)
DEFINE_BEAMWIDTH3(52, 9.7439, 9.5073, 9.9802)
DEFINE_BEAMWIDTH3(53, 10.2165, 9.9802, 10.4524)
DEFINE_BEAMWIDTH3(54, 10.6883, 10.4524, 10.9238)
DEFINE_BEAMWIDTH3(55, 11.1593, 10.9238, 11.3944)
DEFINE_BEAMWIDTH3(56, 11.6295, 11.3944, 11.8641)
DEFINE_BEAMWIDTH3(57, 12.0986, 11.8641, 12.3326)
DEFINE_BEAMWIDTH3(58, 12.5665, 12.3326, 12.7999)
DEFINE_BEAMWIDTH3(59, 13.0332, 12.7999, 13.2661)
DEFINE_BEAMWIDTH3(60, 13.4990, 13.2661, 13.7314)
DEFINE_BEAMWIDTH3(61, 13.9637, 13.7314, 14.1952)
DEFINE_BEAMWIDTH3(62, 14.4266, 14.1952, 14.6569)
DEFINE_BEAMWIDTH3(63, 14.8872, 14.6569, 15.1175)
|
SoundMetrics/aris-file-sdk | type-definitions/C/FrameHeader.h | // FrameHeader.h
// THIS IS GENERATED WITH GenerateHeader, DO NOT MODIFY
#ifndef ARIS_ARISFRAMEHEADER_H
#define ARIS_ARISFRAMEHEADER_H
#include <stdint.h>
#define ARIS_FILE_SIGNATURE 0x05464444
#define ARIS_FRAME_SIGNATURE 0x05464444
#pragma pack(push, 1)
// Defines the metadata at the start of an ARIS frame.
struct ArisFrameHeader {
// Frame number in file
uint32_t FrameIndex;
// PC time stamp when recorded; microseconds since epoch (Jan 1st 1970)
uint64_t FrameTime;
// ARIS file format version = 0x05464444
uint32_t Version;
uint32_t Status;
// On-sonar microseconds since epoch (Jan 1st 1970)
uint64_t sonarTimeStamp;
uint32_t TS_Day;
uint32_t TS_Hour;
uint32_t TS_Minute;
uint32_t TS_Second;
uint32_t TS_Hsecond;
uint32_t TransmitMode;
// Window start in meters
float WindowStart;
// Window length in meters
float WindowLength;
uint32_t Threshold;
int32_t Intensity;
// Note: 0-24 dB
uint32_t ReceiverGain;
// CPU temperature
// Note: Celsius
uint32_t DegC1;
// Power supply temperature
// Note: Celsius
uint32_t DegC2;
// % relative humidity
uint32_t Humidity;
// Focus units 0-1000
uint32_t Focus;
// OBSOLETE: Unused.
uint32_t Battery;
float UserValue1;
float UserValue2;
float UserValue3;
float UserValue4;
float UserValue5;
float UserValue6;
float UserValue7;
float UserValue8;
// Platform velocity from AUV integration
float Velocity;
// Platform depth from AUV integration
float Depth;
// Platform altitude from AUV integration
float Altitude;
// Platform pitch from AUV integration
float Pitch;
// Platform pitch rate from AUV integration
float PitchRate;
// Platform roll from AUV integration
float Roll;
// Platform roll rate from AUV integration
float RollRate;
// Platform heading from AUV integration
float Heading;
// Platform heading rate from AUV integration
float HeadingRate;
// Sonar compass heading output
float CompassHeading;
// Sonar compass pitch output
float CompassPitch;
// Sonar compass roll output
float CompassRoll;
// from auxiliary GPS sensor
double Latitude;
// from auxiliary GPS sensor
double Longitude;
// Note: special for PNNL
float SonarPosition;
uint32_t ConfigFlags;
float BeamTilt;
float TargetRange;
float TargetBearing;
uint32_t TargetPresent;
// OBSOLETE: Unused.
uint32_t FirmwareRevision;
uint32_t Flags;
// Source file frame number for CSOT output files
uint32_t SourceFrame;
// Water temperature from housing temperature sensor
float WaterTemp;
uint32_t TimerPeriod;
// Sonar X location for 3D processing
// Note: Bluefin, external sensor data
float SonarX;
// Sonar Y location for 3D processing
float SonarY;
// Sonar Z location for 3D processing
float SonarZ;
// X2 pan output
float SonarPan;
// X2 tilt output
float SonarTilt;
// X2 roll output
float SonarRoll;
float PanPNNL;
float TiltPNNL;
float RollPNNL;
// Note: special for Bluefin HAUV or other AUV integration
double VehicleTime;
// GPS output from NMEA GGK message
float TimeGGK;
// GPS output from NMEA GGK message
uint32_t DateGGK;
// GPS output from NMEA GGK message
uint32_t QualityGGK;
// GPS output from NMEA GGK message
uint32_t NumSatsGGK;
// GPS output from NMEA GGK message
float DOPGGK;
// GPS output from NMEA GGK message
float EHTGGK;
// external sensor
float HeaveTSS;
// GPS year output
uint32_t YearGPS;
// GPS month output
uint32_t MonthGPS;
// GPS day output
uint32_t DayGPS;
// GPS hour output
uint32_t HourGPS;
// GPS minute output
uint32_t MinuteGPS;
// GPS second output
uint32_t SecondGPS;
// GPS 1/100th second output
uint32_t HSecondGPS;
// Sonar mount location pan offset for 3D processing; meters
float SonarPanOffset;
// Sonar mount location tilt offset for 3D processing
float SonarTiltOffset;
// Sonar mount location roll offset for 3D processing
float SonarRollOffset;
// Sonar mount location X offset for 3D processing
float SonarXOffset;
// Sonar mount location Y offset for 3D processing
float SonarYOffset;
// Sonar mount location Z offset for 3D processing
float SonarZOffset;
// 3D processing transformation matrix
float Tmatrix[16];
// Calculated as 1e6/SamplePeriod
float SampleRate;
// X-axis sonar acceleration
float AccellX;
// Y-axis sonar acceleration
float AccellY;
// Z-axis sonar acceleration
float AccellZ;
// ARIS ping mode
// Note: 1..12
uint32_t PingMode;
// Frequency
// Note: 1 = HF, 0 = LF
uint32_t FrequencyHiLow;
// Width of transmit pulse
// Note: 4..100 microseconds
uint32_t PulseWidth;
// Ping cycle time
// Note: 1802..65535 microseconds
uint32_t CyclePeriod;
// Downrange sample rate
// Note: 4..100 microseconds
uint32_t SamplePeriod;
// 1 = Transmit ON, 0 = Transmit OFF
uint32_t TransmitEnable;
// Instantaneous frame rate between frame N and frame N-1
// Note: microseconds
float FrameRate;
// Sound velocity in water calculated from water temperature depth and salinity setting
// Note: m/s
float SoundSpeed;
// Number of downrange samples in each beam
uint32_t SamplesPerBeam;
// 1 = 150V ON (Max Power), 0 = 150V OFF (Min Power, 12V)
uint32_t Enable150V;
// Delay from transmit until start of sampling (window start) in usec, [930..65535]
uint32_t SampleStartDelay;
// 1 = telephoto lens (large lens, big lens, hi-res lens) present
uint32_t LargeLens;
// 1 = ARIS 3000, 0 = ARIS 1800, 2 = ARIS 1200
uint32_t TheSystemType;
// Sonar serial number as labeled on housing
uint32_t SonarSerialNumber;
// Reserved.
// OBSOLETE: Obsolete
uint64_t ReservedEK;
// Error flag code bits
uint32_t ArisErrorFlagsUint;
// Missed packet count for Ethernet statistics reporting
uint32_t MissedPackets;
// Version number of ArisApp sending frame data
uint32_t ArisAppVersion;
// Reserved for future use
uint32_t Available2;
// 1 = frame data already ordered into [beam,sample] array, 0 = needs reordering
uint32_t ReorderedSamples;
// Water salinity code: 0 = fresh, 15 = brackish, 35 = salt
uint32_t Salinity;
// Depth sensor output
// Note: psi
float Pressure;
// Battery input voltage before power steering
// Note: mV
float BatteryVoltage;
// Main cable input voltage before power steering
// Note: mV
float MainVoltage;
// Input voltage after power steering; filtered voltage
// Note: mV
float SwitchVoltage;
// Note: Added 14-Aug-2012 for AutomaticRecording
uint32_t FocusMotorMoving;
// Note: Added 16-Aug (first two bits = 12V, second two bits = 150V, 00 = not changing, 01 = turning on, 10 = turning off)
uint32_t VoltageChanging;
uint32_t FocusTimeoutFault;
uint32_t FocusOverCurrentFault;
uint32_t FocusNotFoundFault;
uint32_t FocusStalledFault;
uint32_t FPGATimeoutFault;
uint32_t FPGABusyFault;
uint32_t FPGAStuckFault;
uint32_t CPUTempFault;
uint32_t PSUTempFault;
uint32_t WaterTempFault;
uint32_t HumidityFault;
uint32_t PressureFault;
uint32_t VoltageReadFault;
uint32_t VoltageWriteFault;
// Focus shaft current position
// Note: 0..1000 motor units
uint32_t FocusCurrentPosition;
// Commanded pan position
float TargetPan;
// Commanded tilt position
float TargetTilt;
// Commanded roll position
float TargetRoll;
uint32_t PanMotorErrorCode;
uint32_t TiltMotorErrorCode;
uint32_t RollMotorErrorCode;
// Low-resolution magnetic encoder absolute pan position (NaN indicates no arm detected for axis since 2.6.0.8403)
float PanAbsPosition;
// Low-resolution magnetic encoder absolute tilt position (NaN indicates no arm detected for axis since 2.6.0.8403)
float TiltAbsPosition;
// Low-resolution magnetic encoder absolute roll position (NaN indicates no arm detected for axis since 2.6.0.8403)
float RollAbsPosition;
// Accelerometer outputs from AR2 CPU board sensor
// Note: G
float PanAccelX;
// Note: G
float PanAccelY;
// Note: G
float PanAccelZ;
// Note: G
float TiltAccelX;
// Note: G
float TiltAccelY;
// Note: G
float TiltAccelZ;
// Note: G
float RollAccelX;
// Note: G
float RollAccelY;
// Note: G
float RollAccelZ;
// Cookie indices for command acknowlege in frame header
uint32_t AppliedSettings;
// Cookie indices for command acknowlege in frame header
uint32_t ConstrainedSettings;
// Cookie indices for command acknowlege in frame header
uint32_t InvalidSettings;
// If true delay is added between sending out image data packets
uint32_t EnableInterpacketDelay;
// packet delay factor in us (does not include function overhead time)
uint32_t InterpacketDelayPeriod;
// Total time the sonar has been running over its lifetime.
// Note: seconds
uint32_t Uptime;
// Major version number
uint16_t ArisAppVersionMajor;
// Minor version number
uint16_t ArisAppVersionMinor;
// Sonar time when frame cycle is initiated in hardware
uint64_t GoTime;
// AR2 pan velocity
// Note: degrees/second
float PanVelocity;
// AR2 tilt velocity
// Note: degrees/second
float TiltVelocity;
// AR2 roll velocity
// Note: degrees/second
float RollVelocity;
// Age of the last GPS fix acquired; capped at 0xFFFFFFFF; zero if none
// Note: microseconds
uint32_t GpsTimeAge;
// bit 0 = Defender
uint32_t SystemVariant;
// Padding to fill out to 1024 bytes
char padding[288];
};
#pragma pack(pop)
// In general the struct above should be used rather than the offsets.
// The 'ArisFrameHeader' prefix prevents name conflicts between the file and frame headers
enum ArisFrameHeaderOffsets {
ArisFrameHeaderOffset_FrameIndex = 0,
ArisFrameHeaderOffset_FrameTime = 4,
ArisFrameHeaderOffset_Version = 12,
ArisFrameHeaderOffset_Status = 16,
ArisFrameHeaderOffset_sonarTimeStamp = 20,
ArisFrameHeaderOffset_TS_Day = 28,
ArisFrameHeaderOffset_TS_Hour = 32,
ArisFrameHeaderOffset_TS_Minute = 36,
ArisFrameHeaderOffset_TS_Second = 40,
ArisFrameHeaderOffset_TS_Hsecond = 44,
ArisFrameHeaderOffset_TransmitMode = 48,
ArisFrameHeaderOffset_WindowStart = 52,
ArisFrameHeaderOffset_WindowLength = 56,
ArisFrameHeaderOffset_Threshold = 60,
ArisFrameHeaderOffset_Intensity = 64,
ArisFrameHeaderOffset_ReceiverGain = 68,
ArisFrameHeaderOffset_DegC1 = 72,
ArisFrameHeaderOffset_DegC2 = 76,
ArisFrameHeaderOffset_Humidity = 80,
ArisFrameHeaderOffset_Focus = 84,
// OBSOLETE: Unused.
ArisFrameHeaderOffset_Battery = 88,
ArisFrameHeaderOffset_UserValue1 = 92,
ArisFrameHeaderOffset_UserValue2 = 96,
ArisFrameHeaderOffset_UserValue3 = 100,
ArisFrameHeaderOffset_UserValue4 = 104,
ArisFrameHeaderOffset_UserValue5 = 108,
ArisFrameHeaderOffset_UserValue6 = 112,
ArisFrameHeaderOffset_UserValue7 = 116,
ArisFrameHeaderOffset_UserValue8 = 120,
ArisFrameHeaderOffset_Velocity = 124,
ArisFrameHeaderOffset_Depth = 128,
ArisFrameHeaderOffset_Altitude = 132,
ArisFrameHeaderOffset_Pitch = 136,
ArisFrameHeaderOffset_PitchRate = 140,
ArisFrameHeaderOffset_Roll = 144,
ArisFrameHeaderOffset_RollRate = 148,
ArisFrameHeaderOffset_Heading = 152,
ArisFrameHeaderOffset_HeadingRate = 156,
ArisFrameHeaderOffset_CompassHeading = 160,
ArisFrameHeaderOffset_CompassPitch = 164,
ArisFrameHeaderOffset_CompassRoll = 168,
ArisFrameHeaderOffset_Latitude = 172,
ArisFrameHeaderOffset_Longitude = 180,
ArisFrameHeaderOffset_SonarPosition = 188,
ArisFrameHeaderOffset_ConfigFlags = 192,
ArisFrameHeaderOffset_BeamTilt = 196,
ArisFrameHeaderOffset_TargetRange = 200,
ArisFrameHeaderOffset_TargetBearing = 204,
ArisFrameHeaderOffset_TargetPresent = 208,
// OBSOLETE: Unused.
ArisFrameHeaderOffset_FirmwareRevision = 212,
ArisFrameHeaderOffset_Flags = 216,
ArisFrameHeaderOffset_SourceFrame = 220,
ArisFrameHeaderOffset_WaterTemp = 224,
ArisFrameHeaderOffset_TimerPeriod = 228,
ArisFrameHeaderOffset_SonarX = 232,
ArisFrameHeaderOffset_SonarY = 236,
ArisFrameHeaderOffset_SonarZ = 240,
ArisFrameHeaderOffset_SonarPan = 244,
ArisFrameHeaderOffset_SonarTilt = 248,
ArisFrameHeaderOffset_SonarRoll = 252,
ArisFrameHeaderOffset_PanPNNL = 256,
ArisFrameHeaderOffset_TiltPNNL = 260,
ArisFrameHeaderOffset_RollPNNL = 264,
ArisFrameHeaderOffset_VehicleTime = 268,
ArisFrameHeaderOffset_TimeGGK = 276,
ArisFrameHeaderOffset_DateGGK = 280,
ArisFrameHeaderOffset_QualityGGK = 284,
ArisFrameHeaderOffset_NumSatsGGK = 288,
ArisFrameHeaderOffset_DOPGGK = 292,
ArisFrameHeaderOffset_EHTGGK = 296,
ArisFrameHeaderOffset_HeaveTSS = 300,
ArisFrameHeaderOffset_YearGPS = 304,
ArisFrameHeaderOffset_MonthGPS = 308,
ArisFrameHeaderOffset_DayGPS = 312,
ArisFrameHeaderOffset_HourGPS = 316,
ArisFrameHeaderOffset_MinuteGPS = 320,
ArisFrameHeaderOffset_SecondGPS = 324,
ArisFrameHeaderOffset_HSecondGPS = 328,
ArisFrameHeaderOffset_SonarPanOffset = 332,
ArisFrameHeaderOffset_SonarTiltOffset = 336,
ArisFrameHeaderOffset_SonarRollOffset = 340,
ArisFrameHeaderOffset_SonarXOffset = 344,
ArisFrameHeaderOffset_SonarYOffset = 348,
ArisFrameHeaderOffset_SonarZOffset = 352,
ArisFrameHeaderOffset_Tmatrix = 356,
ArisFrameHeaderOffset_SampleRate = 420,
ArisFrameHeaderOffset_AccellX = 424,
ArisFrameHeaderOffset_AccellY = 428,
ArisFrameHeaderOffset_AccellZ = 432,
ArisFrameHeaderOffset_PingMode = 436,
ArisFrameHeaderOffset_FrequencyHiLow = 440,
ArisFrameHeaderOffset_PulseWidth = 444,
ArisFrameHeaderOffset_CyclePeriod = 448,
ArisFrameHeaderOffset_SamplePeriod = 452,
ArisFrameHeaderOffset_TransmitEnable = 456,
ArisFrameHeaderOffset_FrameRate = 460,
ArisFrameHeaderOffset_SoundSpeed = 464,
ArisFrameHeaderOffset_SamplesPerBeam = 468,
ArisFrameHeaderOffset_Enable150V = 472,
ArisFrameHeaderOffset_SampleStartDelay = 476,
ArisFrameHeaderOffset_LargeLens = 480,
ArisFrameHeaderOffset_TheSystemType = 484,
ArisFrameHeaderOffset_SonarSerialNumber = 488,
// OBSOLETE: Obsolete
ArisFrameHeaderOffset_ReservedEK = 492,
ArisFrameHeaderOffset_ArisErrorFlagsUint = 500,
ArisFrameHeaderOffset_MissedPackets = 504,
ArisFrameHeaderOffset_ArisAppVersion = 508,
ArisFrameHeaderOffset_Available2 = 512,
ArisFrameHeaderOffset_ReorderedSamples = 516,
ArisFrameHeaderOffset_Salinity = 520,
ArisFrameHeaderOffset_Pressure = 524,
ArisFrameHeaderOffset_BatteryVoltage = 528,
ArisFrameHeaderOffset_MainVoltage = 532,
ArisFrameHeaderOffset_SwitchVoltage = 536,
ArisFrameHeaderOffset_FocusMotorMoving = 540,
ArisFrameHeaderOffset_VoltageChanging = 544,
ArisFrameHeaderOffset_FocusTimeoutFault = 548,
ArisFrameHeaderOffset_FocusOverCurrentFault = 552,
ArisFrameHeaderOffset_FocusNotFoundFault = 556,
ArisFrameHeaderOffset_FocusStalledFault = 560,
ArisFrameHeaderOffset_FPGATimeoutFault = 564,
ArisFrameHeaderOffset_FPGABusyFault = 568,
ArisFrameHeaderOffset_FPGAStuckFault = 572,
ArisFrameHeaderOffset_CPUTempFault = 576,
ArisFrameHeaderOffset_PSUTempFault = 580,
ArisFrameHeaderOffset_WaterTempFault = 584,
ArisFrameHeaderOffset_HumidityFault = 588,
ArisFrameHeaderOffset_PressureFault = 592,
ArisFrameHeaderOffset_VoltageReadFault = 596,
ArisFrameHeaderOffset_VoltageWriteFault = 600,
ArisFrameHeaderOffset_FocusCurrentPosition = 604,
ArisFrameHeaderOffset_TargetPan = 608,
ArisFrameHeaderOffset_TargetTilt = 612,
ArisFrameHeaderOffset_TargetRoll = 616,
ArisFrameHeaderOffset_PanMotorErrorCode = 620,
ArisFrameHeaderOffset_TiltMotorErrorCode = 624,
ArisFrameHeaderOffset_RollMotorErrorCode = 628,
ArisFrameHeaderOffset_PanAbsPosition = 632,
ArisFrameHeaderOffset_TiltAbsPosition = 636,
ArisFrameHeaderOffset_RollAbsPosition = 640,
ArisFrameHeaderOffset_PanAccelX = 644,
ArisFrameHeaderOffset_PanAccelY = 648,
ArisFrameHeaderOffset_PanAccelZ = 652,
ArisFrameHeaderOffset_TiltAccelX = 656,
ArisFrameHeaderOffset_TiltAccelY = 660,
ArisFrameHeaderOffset_TiltAccelZ = 664,
ArisFrameHeaderOffset_RollAccelX = 668,
ArisFrameHeaderOffset_RollAccelY = 672,
ArisFrameHeaderOffset_RollAccelZ = 676,
ArisFrameHeaderOffset_AppliedSettings = 680,
ArisFrameHeaderOffset_ConstrainedSettings = 684,
ArisFrameHeaderOffset_InvalidSettings = 688,
ArisFrameHeaderOffset_EnableInterpacketDelay = 692,
ArisFrameHeaderOffset_InterpacketDelayPeriod = 696,
ArisFrameHeaderOffset_Uptime = 700,
ArisFrameHeaderOffset_ArisAppVersionMajor = 704,
ArisFrameHeaderOffset_ArisAppVersionMinor = 706,
ArisFrameHeaderOffset_GoTime = 708,
ArisFrameHeaderOffset_PanVelocity = 716,
ArisFrameHeaderOffset_TiltVelocity = 720,
ArisFrameHeaderOffset_RollVelocity = 724,
ArisFrameHeaderOffset_GpsTimeAge = 728,
ArisFrameHeaderOffset_SystemVariant = 732,
};
#endif // !ARIS_ARISFRAMEHEADER_H
|
SoundMetrics/aris-file-sdk | beam-width-metrics/BeamWidths_ARIS1800_1200_48.h | <gh_stars>1-10
// Copyright 2010-2018 Sound Metrics corporation
//
// Updated Beam Angles for ARIS1800/1200 (48 channels)
//
// beam, center, left, right
DEFINE_BEAMWIDTH3(0, -13.5735, -13.7893, -13.3577)
DEFINE_BEAMWIDTH3(1, -13.1419, -13.3577, -12.9211)
DEFINE_BEAMWIDTH3(2, -12.7003, -12.9211, -12.4723)
DEFINE_BEAMWIDTH3(3, -12.2442, -12.4723, -12.0082)
DEFINE_BEAMWIDTH3(4, -11.7721, -12.0082, -11.5301)
DEFINE_BEAMWIDTH3(5, -11.2881, -11.5301, -11.0401)
DEFINE_BEAMWIDTH3(6, -10.7921, -11.0401, -10.5373)
DEFINE_BEAMWIDTH3(7, -10.2824, -10.5373, -10.0211)
DEFINE_BEAMWIDTH3(8, -9.7597, -10.0211, -9.4902)
DEFINE_BEAMWIDTH3(9, -9.2206, -9.4902, -8.9418)
DEFINE_BEAMWIDTH3(10, -8.6630, -8.9418, -8.3765)
DEFINE_BEAMWIDTH3(11, -8.0899, -8.3765, -7.7963)
DEFINE_BEAMWIDTH3(12, -7.5026, -7.7963, -7.2023)
DEFINE_BEAMWIDTH3(13, -6.9019, -7.2023, -6.5958)
DEFINE_BEAMWIDTH3(14, -6.2897, -6.5958, -5.9779)
DEFINE_BEAMWIDTH3(15, -5.6661, -5.9779, -5.3476)
DEFINE_BEAMWIDTH3(16, -5.0291, -5.3476, -4.7057)
DEFINE_BEAMWIDTH3(17, -4.3823, -4.7057, -4.0544)
DEFINE_BEAMWIDTH3(18, -3.7264, -4.0544, -3.3948)
DEFINE_BEAMWIDTH3(19, -3.0632, -3.3948, -2.7282)
DEFINE_BEAMWIDTH3(20, -2.3931, -2.7282, -2.0551)
DEFINE_BEAMWIDTH3(21, -1.7170, -2.0551, -1.3757)
DEFINE_BEAMWIDTH3(22, -1.0343, -1.3757, -0.6902)
DEFINE_BEAMWIDTH3(23, -0.3461, -0.6902, 0.0000)
DEFINE_BEAMWIDTH3(24, 0.3461, 0.0000, 0.6902)
DEFINE_BEAMWIDTH3(25, 1.0343, 0.6902, 1.3757)
DEFINE_BEAMWIDTH3(26, 1.7170, 1.3757, 2.0551)
DEFINE_BEAMWIDTH3(27, 2.3931, 2.0551, 2.7282)
DEFINE_BEAMWIDTH3(28, 3.0632, 2.7282, 3.3948)
DEFINE_BEAMWIDTH3(29, 3.7264, 3.3948, 4.0544)
DEFINE_BEAMWIDTH3(30, 4.3823, 4.0544, 4.7057)
DEFINE_BEAMWIDTH3(31, 5.0291, 4.7057, 5.3476)
DEFINE_BEAMWIDTH3(32, 5.6661, 5.3476, 5.9779)
DEFINE_BEAMWIDTH3(33, 6.2897, 5.9779, 6.5958)
DEFINE_BEAMWIDTH3(34, 6.9019, 6.5958, 7.2023)
DEFINE_BEAMWIDTH3(35, 7.5026, 7.2023, 7.7963)
DEFINE_BEAMWIDTH3(36, 8.0899, 7.7963, 8.3765)
DEFINE_BEAMWIDTH3(37, 8.6630, 8.3765, 8.9418)
DEFINE_BEAMWIDTH3(38, 9.2206, 8.9418, 9.4902)
DEFINE_BEAMWIDTH3(39, 9.7597, 9.4902, 10.0211)
DEFINE_BEAMWIDTH3(40, 10.2824, 10.0211, 10.5373)
DEFINE_BEAMWIDTH3(41, 10.7921, 10.5373, 11.0401)
DEFINE_BEAMWIDTH3(42, 11.2881, 11.0401, 11.5301)
DEFINE_BEAMWIDTH3(43, 11.7721, 11.5301, 12.0082)
DEFINE_BEAMWIDTH3(44, 12.2442, 12.0082, 12.4723)
DEFINE_BEAMWIDTH3(45, 12.7003, 12.4723, 12.9211)
DEFINE_BEAMWIDTH3(46, 13.1419, 12.9211, 13.3577)
DEFINE_BEAMWIDTH3(47, 13.5735, 13.3577, 13.7893)
|
SoundMetrics/aris-file-sdk | type-definitions/C/FileHeaderFieldsOnly.h | <filename>type-definitions/C/FileHeaderFieldsOnly.h<gh_stars>1-10
// File format version DDF_05 = 0x05464444
uint32_t Version;
// Total frames in file
// Note: Writers should populate; readers should calculate the number of frames from file size & beams*samples.
uint32_t FrameCount;
// Initial recorded frame rate
// OBSOLETE: See frame header instead.
uint32_t FrameRate;
// Non-zero if HF, zero if LF
// OBSOLETE: See frame header instead.
uint32_t HighResolution;
// ARIS 3000 = 128/64, ARIS 1800 = 96/48, ARIS 1200 = 48
// Note: Writers should populate; readers should see frame header instead.
uint32_t NumRawBeams;
// 1/Sample Period
// OBSOLETE: See frame header instead.
float SampleRate;
// Number of range samples in each beam
// Note: Writers should populate; readers should see frame header instead.
uint32_t SamplesPerChannel;
// Relative gain in dB: 0 - 40
// OBSOLETE: See frame header instead.
uint32_t ReceiverGain;
// Image window start range in meters (code [0..31] in DIDSON)
// OBSOLETE: See frame header instead.
float WindowStart;
// Image window length in meters (code [0..3] in DIDSON)
// OBSOLETE: See frame header instead.
float WindowLength;
// Non-zero = lens down (DIDSON) or lens up (ARIS), zero = opposite
// OBSOLETE: See frame header instead.
uint32_t Reverse;
// Sonar serial number
uint32_t SN;
// Date that file was recorded
char strDate[32];
// User input to identify file in 256 characters
char strHeaderID[256];
// User-defined integer quantity
int32_t UserID1;
// User-defined integer quantity
int32_t UserID2;
// User-defined integer quantity
int32_t UserID3;
// User-defined integer quantity
int32_t UserID4;
// First frame number from source file (for DIDSON snippet files)
uint32_t StartFrame;
// Last frame number from source file (for DIDSON snippet files)
uint32_t EndFrame;
// Non-zero indicates time lapse recording
uint32_t TimeLapse;
// Number of frames/seconds between recorded frames
uint32_t RecordInterval;
// Frames or seconds interval
uint32_t RadioSeconds;
// Record every Nth frame
uint32_t FrameInterval;
// See DDF_04 file format document
// OBSOLETE: Obsolete.
uint32_t Flags;
// See DDF_04 file format document
uint32_t AuxFlags;
// Sound velocity in water
// OBSOLETE: See frame header instead.
uint32_t Sspd;
// See DDF_04 file format document
uint32_t Flags3D;
// DIDSON software version that recorded the file
uint32_t SoftwareVersion;
// Water temperature code: 0 = 5-15C, 1 = 15-25C, 2 = 25-35C
uint32_t WaterTemp;
// Salinity code: 0 = fresh, 1 = brackish, 2 = salt
uint32_t Salinity;
// Added for ARIS but not used
uint32_t PulseLength;
// Added for ARIS but not used
uint32_t TxMode;
// Reserved for future use
uint32_t VersionFGPA;
// Reserved for future use
uint32_t VersionPSuC;
// Frame index of frame used for thumbnail image of file
uint32_t ThumbnailFI;
// Total file size in bytes
// OBSOLETE: Do not use; query your filesystem instead.
uint64_t FileSize;
// Reserved for future use
// OBSOLETE: Obsolete; not used.
uint64_t OptionalHeaderSize;
// Reserved for future use
// OBSOLETE: Obsolete; not used.
uint64_t OptionalTailSize;
// DIDSON_ADJUSTED_VERSION_MINOR
// OBSOLETE: Obsolete.
uint32_t VersionMinor;
// Non-zero if telephoto lens (large lens, hi-res lens, big lens) is present
// OBSOLETE: See frame header instead.
uint32_t LargeLens;
// Padding to fill out to 1024 bytes
char padding[568];
|
SoundMetrics/aris-file-sdk | beam-width-metrics/BeamWidths_ARIS1800_96.h | // Copyright 2010-2018 Sound Metrics corporation
//
// Approximate Beam Angles for ARIS3000 (128 channels)
//
// beam, center, left, right
DEFINE_BEAMWIDTH3(0, -13.749, -13.8562, -13.6419)
DEFINE_BEAMWIDTH3(1, -13.5347, -13.6419, -13.4261)
DEFINE_BEAMWIDTH3(2, -13.3174, -13.4261, -13.2075)
DEFINE_BEAMWIDTH3(3, -13.0975, -13.2075, -12.9867)
DEFINE_BEAMWIDTH3(4, -12.8758, -12.9867, -12.7628)
DEFINE_BEAMWIDTH3(5, -12.6498, -12.7628, -12.5348)
DEFINE_BEAMWIDTH3(6, -12.4197, -12.5348, -12.3026)
DEFINE_BEAMWIDTH3(7, -12.1855, -12.3026, -12.0666)
DEFINE_BEAMWIDTH3(8, -11.9476, -12.0666, -11.8273)
DEFINE_BEAMWIDTH3(9, -11.7069, -11.8273, -11.5853)
DEFINE_BEAMWIDTH3(10, -11.4636, -11.5853, -11.3405)
DEFINE_BEAMWIDTH3(11, -11.2173, -11.3405, -11.0925)
DEFINE_BEAMWIDTH3(12, -10.9676, -11.0925, -10.841)
DEFINE_BEAMWIDTH3(13, -10.7144, -10.841, -10.5862)
DEFINE_BEAMWIDTH3(14, -10.4579, -10.5862, -10.3282)
DEFINE_BEAMWIDTH3(15, -10.1985, -10.3282, -10.0669)
DEFINE_BEAMWIDTH3(16, -9.9352, -10.0669, -9.8016)
DEFINE_BEAMWIDTH3(17, -9.668, -9.8016, -9.5321)
DEFINE_BEAMWIDTH3(18, -9.3961, -9.5321, -9.2578)
DEFINE_BEAMWIDTH3(19, -9.1195, -9.2578, -8.979)
DEFINE_BEAMWIDTH3(20, -8.8385, -8.979, -8.696)
DEFINE_BEAMWIDTH3(21, -8.5535, -8.696, -8.4095)
DEFINE_BEAMWIDTH3(22, -8.2654, -8.4095, -8.1196)
DEFINE_BEAMWIDTH3(23, -7.9738, -8.1196, -7.826)
DEFINE_BEAMWIDTH3(24, -7.6781, -7.826, -7.5287)
DEFINE_BEAMWIDTH3(25, -7.3793, -7.5287, -7.2284)
DEFINE_BEAMWIDTH3(26, -7.0774, -7.2284, -6.9251)
DEFINE_BEAMWIDTH3(27, -6.7727, -6.9251, -6.619)
DEFINE_BEAMWIDTH3(28, -6.4652, -6.619, -6.3101)
DEFINE_BEAMWIDTH3(29, -6.1549, -6.3101, -5.9983)
DEFINE_BEAMWIDTH3(30, -5.8416, -5.9983, -5.6831)
DEFINE_BEAMWIDTH3(31, -5.5246, -5.6831, -5.3646)
DEFINE_BEAMWIDTH3(32, -5.2046, -5.3646, -5.0435)
DEFINE_BEAMWIDTH3(33, -4.8824, -5.0435, -4.7201)
DEFINE_BEAMWIDTH3(34, -4.5578, -4.7201, -4.3944)
DEFINE_BEAMWIDTH3(35, -4.231, -4.3944, -4.0665)
DEFINE_BEAMWIDTH3(36, -3.9019, -4.0665, -3.7365)
DEFINE_BEAMWIDTH3(37, -3.5711, -3.7365, -3.4049)
DEFINE_BEAMWIDTH3(38, -3.2387, -3.4049, -3.0716)
DEFINE_BEAMWIDTH3(39, -2.9044, -3.0716, -2.7365)
DEFINE_BEAMWIDTH3(40, -2.5686, -2.7365, -2.4)
DEFINE_BEAMWIDTH3(41, -2.2314, -2.4, -2.062)
DEFINE_BEAMWIDTH3(42, -1.8925, -2.062, -1.7222)
DEFINE_BEAMWIDTH3(43, -1.5519, -1.7222, -1.3809)
DEFINE_BEAMWIDTH3(44, -1.2098, -1.3809, -1.0381)
DEFINE_BEAMWIDTH3(45, -0.8664, -1.0381, -0.694)
DEFINE_BEAMWIDTH3(46, -0.5216, -0.694, -0.3487)
DEFINE_BEAMWIDTH3(47, -0.1757, -0.3487, -0.0026)
DEFINE_BEAMWIDTH3(48, 0.1706, -0.0026, 0.3438)
DEFINE_BEAMWIDTH3(49, 0.5169, 0.3438, 0.6899)
DEFINE_BEAMWIDTH3(50, 0.8628, 0.6899, 1.0352)
DEFINE_BEAMWIDTH3(51, 1.2076, 1.0352, 1.3793)
DEFINE_BEAMWIDTH3(52, 1.551, 1.3793, 1.7221)
DEFINE_BEAMWIDTH3(53, 1.8931, 1.7221, 2.0634)
DEFINE_BEAMWIDTH3(54, 2.2337, 2.0634, 2.4032)
DEFINE_BEAMWIDTH3(55, 2.5726, 2.4032, 2.7412)
DEFINE_BEAMWIDTH3(56, 2.9098, 2.7412, 3.0777)
DEFINE_BEAMWIDTH3(57, 3.2456, 3.0777, 3.4128)
DEFINE_BEAMWIDTH3(58, 3.5799, 3.4128, 3.7461)
DEFINE_BEAMWIDTH3(59, 3.9123, 3.7461, 4.0777)
DEFINE_BEAMWIDTH3(60, 4.2431, 4.0777, 4.4077)
DEFINE_BEAMWIDTH3(61, 4.5722, 4.4077, 4.7356)
DEFINE_BEAMWIDTH3(62, 4.899, 4.7356, 5.0613)
DEFINE_BEAMWIDTH3(63, 5.2236, 5.0613, 5.3847)
DEFINE_BEAMWIDTH3(64, 5.5458, 5.3847, 5.7058)
DEFINE_BEAMWIDTH3(65, 5.8658, 5.7058, 6.0243)
DEFINE_BEAMWIDTH3(66, 6.1828, 6.0243, 6.3395)
DEFINE_BEAMWIDTH3(67, 6.4961, 6.3395, 6.6513)
DEFINE_BEAMWIDTH3(68, 6.8064, 6.6513, 6.9602)
DEFINE_BEAMWIDTH3(69, 7.1139, 6.9602, 7.2663)
DEFINE_BEAMWIDTH3(70, 7.4186, 7.2663, 7.5696)
DEFINE_BEAMWIDTH3(71, 7.7205, 7.5696, 7.8699)
DEFINE_BEAMWIDTH3(72, 8.0193, 7.8699, 8.1672)
DEFINE_BEAMWIDTH3(73, 8.315, 8.1672, 8.4608)
DEFINE_BEAMWIDTH3(74, 8.6066, 8.4608, 8.7507)
DEFINE_BEAMWIDTH3(75, 8.8947, 8.7507, 9.0372)
DEFINE_BEAMWIDTH3(76, 9.1797, 9.0372, 9.3202)
DEFINE_BEAMWIDTH3(77, 9.4607, 9.3202, 9.599)
DEFINE_BEAMWIDTH3(78, 9.7373, 9.599, 9.8733)
DEFINE_BEAMWIDTH3(79, 10.0092, 9.8733, 10.1428)
DEFINE_BEAMWIDTH3(80, 10.2764, 10.1428, 10.4081)
DEFINE_BEAMWIDTH3(81, 10.5397, 10.4081, 10.6694)
DEFINE_BEAMWIDTH3(82, 10.7991, 10.6694, 10.9274)
DEFINE_BEAMWIDTH3(83, 11.0556, 10.9274, 11.1822)
DEFINE_BEAMWIDTH3(84, 11.3088, 11.1822, 11.4337)
DEFINE_BEAMWIDTH3(85, 11.5585, 11.4337, 11.6817)
DEFINE_BEAMWIDTH3(86, 11.8048, 11.6817, 11.9265)
DEFINE_BEAMWIDTH3(87, 12.0481, 11.9265, 12.1685)
DEFINE_BEAMWIDTH3(88, 12.2888, 12.1685, 12.4078)
DEFINE_BEAMWIDTH3(89, 12.5267, 12.4078, 12.6438)
DEFINE_BEAMWIDTH3(90, 12.7609, 12.6438, 12.876)
DEFINE_BEAMWIDTH3(91, 12.991, 12.876, 13.104)
DEFINE_BEAMWIDTH3(92, 13.217, 13.104, 13.3279)
DEFINE_BEAMWIDTH3(93, 13.4387, 13.3279, 13.5487)
DEFINE_BEAMWIDTH3(94, 13.6586, 13.5487, 13.7673)
DEFINE_BEAMWIDTH3(95, 13.8759, 13.7673, 13.9831)
|
SoundMetrics/aris-file-sdk | common-code/FrameFuncs.h | // FrameFuncs.h
#include <stdint.h>
#ifndef FRAMEFUNCS_H
#define FRAMEFUNCS_H
// Returns the number of beams used for the specified pingmode.
size_t get_beams_from_pingmode(uint32_t pingmode);
#endif // !FRAMEFUNCS_H
|
SoundMetrics/aris-file-sdk | beam-width-metrics/BeamWidths_ARIS_Telephoto_48.h | <reponame>SoundMetrics/aris-file-sdk<filename>beam-width-metrics/BeamWidths_ARIS_Telephoto_48.h
// Copyright 2010-2018 Sound Metrics corporation
//
// Updated Beam Angles for ARIS 1800/1200 Telephoto (48 channels)
//
// beam, center, left, right
DEFINE_BEAMWIDTH3(0, -7.339, -7.487, -7.345)
DEFINE_BEAMWIDTH3(1, -7.043, -7.193, -7.048)
DEFINE_BEAMWIDTH3(2, -6.744, -6.895, -6.749)
DEFINE_BEAMWIDTH3(3, -6.443, -6.595, -6.447)
DEFINE_BEAMWIDTH3(4, -6.140, -6.293, -6.144)
DEFINE_BEAMWIDTH3(5, -5.835, -5.988, -5.839)
DEFINE_BEAMWIDTH3(6, -5.529, -5.683, -5.533)
DEFINE_BEAMWIDTH3(7, -5.222, -5.377, -5.225)
DEFINE_BEAMWIDTH3(8, -4.913, -5.069, -4.915)
DEFINE_BEAMWIDTH3(9, -4.602, -4.758, -4.604)
DEFINE_BEAMWIDTH3(10, -4.29, -4.448, -4.291)
DEFINE_BEAMWIDTH3(11, -3.975, -4.133, -3.976)
DEFINE_BEAMWIDTH3(12, -3.659, -3.818, -3.660)
DEFINE_BEAMWIDTH3(13, -3.342, -3.501, -3.343)
DEFINE_BEAMWIDTH3(14, -3.025, -3.184, -3.026)
DEFINE_BEAMWIDTH3(15, -2.708, -2.867, -2.709)
DEFINE_BEAMWIDTH3(16, -2.391, -2.550, -2.392)
DEFINE_BEAMWIDTH3(17, -2.074, -2.233, -2.075)
DEFINE_BEAMWIDTH3(18, -1.756, -1.915, -1.757)
DEFINE_BEAMWIDTH3(19, -1.438, -1.598, -1.438)
DEFINE_BEAMWIDTH3(20, -1.119, -1.279, -1.119)
DEFINE_BEAMWIDTH3(21, -0.800, -0.960, -0.800)
DEFINE_BEAMWIDTH3(22, -0.480, -0.640, -0.480)
DEFINE_BEAMWIDTH3(23, -0.160, -0.320, -0.160)
DEFINE_BEAMWIDTH3(24, 0.160, 0.160, 0.320)
DEFINE_BEAMWIDTH3(25, 0.480, 0.480, 0.640)
DEFINE_BEAMWIDTH3(26, 0.800, 0.800, 0.960)
DEFINE_BEAMWIDTH3(27, 1.119, 1.119, 1.279)
DEFINE_BEAMWIDTH3(28, 1.438, 1.438, 1.598)
DEFINE_BEAMWIDTH3(29, 1.756, 1.757, 1.915)
DEFINE_BEAMWIDTH3(30, 2.074, 2.075, 2.233)
DEFINE_BEAMWIDTH3(31, 2.391, 2.392, 2.550)
DEFINE_BEAMWIDTH3(32, 2.708, 2.709, 2.867)
DEFINE_BEAMWIDTH3(33, 3.025, 3.026, 3.184)
DEFINE_BEAMWIDTH3(34, 3.342, 3.343, 3.501)
DEFINE_BEAMWIDTH3(35, 3.659, 3.660, 3.818)
DEFINE_BEAMWIDTH3(36, 3.975, 3.976, 4.133)
DEFINE_BEAMWIDTH3(37, 4.290, 4.291, 4.448)
DEFINE_BEAMWIDTH3(38, 4.602, 4.604, 4.758)
DEFINE_BEAMWIDTH3(39, 4.913, 4.915, 5.069)
DEFINE_BEAMWIDTH3(40, 5.222, 5.225, 5.377)
DEFINE_BEAMWIDTH3(41, 5.529, 5.533, 5.683)
DEFINE_BEAMWIDTH3(42, 5.835, 5.839, 5.988)
DEFINE_BEAMWIDTH3(43, 6.140, 6.144, 6.293)
DEFINE_BEAMWIDTH3(44, 6.443, 6.447, 6.595)
DEFINE_BEAMWIDTH3(45, 6.744, 6.749, 6.895)
DEFINE_BEAMWIDTH3(46, 7.043, 7.048, 7.193)
DEFINE_BEAMWIDTH3(47, 7.339, 7.345, 7.487)
|
tailhook/paperjam | src/pjutil.c | <filename>src/pjutil.c
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#include <stdio.h>
#include <config.h>
#include <time.h>
#include <assert.h>
#include "pjutil.h"
#ifdef HAVE_XS
#include <xs.h>
#include "xs_cli.h"
#endif
#ifdef HAVE_ZMQ
#include <zmq.h>
#include "zmq_cli.h"
#endif
struct cli_options_s cli_options;
struct {
char pattern[2];
void (*function)();
} table[] = {
# if HAVE_XS
{"Xp", run_xs_pull},
{"XP", run_xs_push},
{"Xs", run_xs_sub},
{"XS", run_xs_pub},
{"XR", run_xs_req},
{"Xr", run_xs_rep},
# ifdef HAVE_SURVEY
{"XU", run_xs_surveyor},
{"Xu", run_xs_respondent},
# endif
# endif
# if HAVE_ZMQ
{"Zp", run_zmq_pull},
{"ZP", run_zmq_push},
{"Zs", run_zmq_sub},
{"ZS", run_zmq_pub},
{"ZR", run_zmq_req},
{"Zr", run_zmq_rep},
# endif
{"\0\0", NULL}
};
char *short_options = "hZXpPsSrRb:c:t:";
struct option long_options[] = {
# ifdef HAVE_ZMQ
{"zmq", 0, NULL, 'Z'},
# endif
# ifdef HAVE_XS
{"xs", 0, NULL, 'X'},
# endif
{"pull", 0, NULL, 'p'},
{"push", 0, NULL, 'P'},
{"sub", 0, NULL, 's'},
{"pub", 0, NULL, 'S'},
{"req", 0, NULL, 'R'},
{"rep", 0, NULL, 'r'},
# ifdef HAVE_SURVEY
{"surveyor", 0, NULL, 'U'},
{"respondent", 0, NULL, 'u'},
# endif
{"bind", 1, NULL, 'b'},
{"connect", 1, NULL, 'c'},
{"timeout", 1, NULL, 't'},
{"help", 0, NULL, 'h'},
{NULL, 0, NULL, 0}
};
void print_usage(FILE *stream, char *arg0) {
fprintf(stream, "Usage:\n");
char *stype = "{--push|--pull"
"|--pub|--sub"
"|--req|--rep"
# if HAVE_SURVEY
"|--surveyor|--respondent"
# endif
"}";
if(cli_options.arg0_lib && cli_options.arg0_sock) {
fprintf(stream, " %s {--bind|--connect} ADDR [msg1 [msg2 ...]]\n",
arg0);
} else if(cli_options.arg0_lib) {
if(cli_options.arg0_lib == 'X') {
// zmq has no surveyor
stype = "{--push|--pull|--pub|--sub|--req|--rep}";
}
fprintf(stream, " %s %s\\\n"
" {--bind|--connect} ADDR [msg1 [msg2 ...]]\n", arg0, stype);
} else if(cli_options.arg0_sock) {
fprintf(stream, " %s [--zmq|--xs] "
"{--bind|--connect} ADDR [msg1 [msg2 ...]]\n", arg0);
} else {
# if defined(HAVE_ZMQ) && defined(HAVE_XS)
fprintf(stream,
" %s [--zmq|--xs] %s \\\n"
" {--bind|--connect} ADDR [options] [msg1 [msg2 ...]]\n",
arg0, stype);
# else
fprintf(stream,
" %s %s\\\n"
" {--bind|--connect} ADDR [options] [msg1 [msg2 ...]]\n",
arg0, stype);
# endif
}
fprintf(stream, "\n"
"Options:\n");
# ifdef HAVE_ZMQ
if(cli_options.defaultlib == 'Z') {
fprintf(stream, " -Z,--zmq Open zeromq socket (default)\n");
} else {
fprintf(stream, " -Z,--zmq Open zeromq socket\n");
}
# endif
# ifdef HAVE_XS
if(cli_options.defaultlib == 'X') {
fprintf(stream,
" -X,--xs Open crossroads IO (libxs) socket (default)\n");
} else {
fprintf(stream, " -X,--xs Open crossroads IO (libxs) socket\n");
}
# endif
fprintf(stream,
" -p,--pull Open PULL socket and print all incoming data\n"
" -P,--push Open PUSH socket and push messages\n"
" -S,--pub Open PUB socket and publish messages\n"
" -s,--sub Open SUB socket and print all incoming data\n"
" -R,--req Open REQ socket and send a request\n"
" -r,--rep Open REP socket and answer requests with same data\n"
" -U,--surveyor Open SURVEYOR socket and send a request"
" (if supported)\n"
" -u,--respondent Open RESPONDENT socket and answer requests"
" (if supported)\n"
" -b,--bind ADDR Bind socket to address. ADDR is zeromq/libxs address\n"
" -c,--connect ADDR\n"
" Connect socket to address. ADDR is zeromq/libxs address\n"
" -t,--timeout SEC\n"
" Maximum time process runs, in seconds\n"
"\n"
);
}
double get_time() {
struct timespec ts;
int rc = clock_gettime(CLOCK_MONOTONIC, &ts);
assert(rc != -1);
return (double)ts.tv_sec + ts.tv_nsec*0.000000001;
}
void clear_options(int argc, char **argv) {
# if HAVE_XS
cli_options.defaultlib = 'X';
# else
cli_options.defaultlib = 'Z';
# endif
cli_options.arg0_lib = 0;
cli_options.arg0_sock = 0;
cli_options.lib = 0;
cli_options.sock = 0;
cli_options.messages = NULL;
cli_options.argc = argc;
cli_options.argv = argv;
cli_options.timeout = 0.0;
cli_options.finishtime = 1e20;
}
void parse_arg0(char *arg0) {
if(strstr(arg0, "xs")) {
cli_options.arg0_lib = 'X';
} else if(strstr(arg0, "zmq")) {
cli_options.arg0_lib = 'Z';
}
if(strstr(arg0, "push")) {
cli_options.arg0_sock = 'P';
} else if(strstr(arg0, "pull")) {
cli_options.arg0_sock = 'p';
} else if(strstr(arg0, "pub")) {
cli_options.arg0_sock = 'S';
} else if(strstr(arg0, "sub")) {
cli_options.arg0_sock = 's';
} else if(strstr(arg0, "req")) {
cli_options.arg0_sock = 'R';
} else if(strstr(arg0, "rep")) {
cli_options.arg0_sock = 'r';
} else if(strstr(arg0, "surveyor")) {
cli_options.arg0_sock = 'U';
} else if(strstr(arg0, "respondent")) {
cli_options.arg0_sock = 'u';
}
}
void parse_options(int argc, char **argv) {
int opt;
while((opt = getopt_long(argc, argv,
short_options, long_options, NULL)) != -1) {
switch(opt) {
case 'Z':
cli_options.lib = 'Z';
break;
case 'X':
cli_options.lib = 'X';
break;
case 't':
cli_options.timeout = strtod(optarg, NULL);
cli_options.finishtime = get_time() + cli_options.timeout;
break;
case 'p': case 'P':
case 's': case 'S':
case 'r': case 'R':
case 'u': case 'U':
cli_options.sock = opt;
break;
case 'h':
print_usage(stdout, argv[0]);
exit(0);
case '?':
print_usage(stderr, argv[0]);
exit(1);
}
}
cli_options.messages = argv + optind;
}
int main(int argc, char **argv) {
clear_options(argc, argv);
char *arg0 = strrchr(argv[0], '/');
if(arg0) arg0 += 1;
else arg0 = argv[0];
parse_arg0(argv[0]);
parse_options(argc, argv);
int sock = cli_options.sock;
if(!sock) sock = cli_options.arg0_sock;
if(!cli_options.sock && !cli_options.arg0_sock) {
fprintf(stderr, "Socket type is not specified\n");
print_usage(stderr, argv[0]);
exit(1);
}
int lib = cli_options.lib;
if(!lib) lib = cli_options.arg0_lib;
if(!lib) lib = cli_options.defaultlib;
if(!lib) {
fprintf(stderr, "Library used (libxs or libzmq) is not specified\n");
exit(0);
}
for(int i = 0; i < sizeof(table)/sizeof(table[0]); ++i) {
if(table[i].pattern[0] == lib && table[i].pattern[1] == sock) {
table[i].function();
exit(0);
}
}
fprintf(stderr, "Wrong combination of library and socket type\n");
exit(1);
}
|
tailhook/paperjam | src/pjutil.h | <reponame>tailhook/paperjam<gh_stars>1-10
#ifndef _H_PJUTIL
#define _H_PJUTIL
#include <getopt.h>
#include "print.h"
struct cli_options_s {
int defaultlib;
int arg0_lib;
int arg0_sock;
int lib;
int sock;
double timeout;
double finishtime;
int argc;
char **argv;
char **messages;
};
extern struct cli_options_s cli_options;
extern char *short_options;
extern struct option long_options[];
double get_time();
#endif //_H_PJUTIL
|
tailhook/paperjam | src/main.c | #include <malloc.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <sys/time.h>
#include <time.h>
#include <poll.h>
#include "config.h"
#include "handle_zmq.h"
#include "handle_xs.h"
#include "paperjam.h"
#define ASSERTERR(val) if((val) == -1) { \
fprintf(stderr, "Assertion error at %s:%d: %s\n", \
__FILE__, __LINE__, \
strerror(errno)); \
abort(); \
}
static void device_check(config_socket_t *front, config_socket_t *back) {
if(IS_READONLY(front) && IS_WRITEONLY(back)) return;
if(IS_WRITEONLY(front) && IS_READONLY(back)) return;
if(IS_REQ(front) && IS_REP(back)) return;
if(IS_REP(front) && IS_REQ(back)) return;
fprintf(stderr, "Wrong combination of sockets for %s", front->_name);
abort();
}
static void monitor_check(config_socket_t *sock) {
if(IS_WRITEONLY(sock)) return;
// Can reply socket be able to monitor? probably not
fprintf(stderr, "Wrong socket for monitoring %s, use push or pub sockets",
sock->_name);
abort();
}
static int close_message(message *msg) {
// TODO(tailhook)
if(msg->zmq) {
#ifdef HAVE_ZMQ
ZMQ_ASSERTERR(zmq_msg_close(&msg->zmq_msg));
#else
assert(0);
#endif
}
if(msg->xs) {
#ifdef HAVE_XS
XS_ASSERTERR(xs_msg_close(&msg->xs_msg));
#else
assert(0);
#endif
}
msg->xs = 0;
msg->zmq = 0;
msg->more = 0;
return 0;
}
static int forward(context *ctx, config_socket_t *src, config_socket_t *tgt,
config_device_t *dev, int mode)
{
message msg;
msg.xs = 0;
msg.zmq = 0;
msg.more = 0;
int rc = src->_impl->read_message(src, &msg);
if(rc == -1) {
if(errno == EAGAIN) {
src->_state.readable = 0;
return 0;
}
ASSERTERR(rc);
}
if(mode) {
dev->_stat.input_msg += 1;
} else {
dev->_stat.output_msg += 1;
}
int monactive = 0;
if(dev->monitor.kind) {
rc = dev->monitor._impl->write_string(&dev->monitor,
mode ? "in" : "out", 1);
if(rc >= 0) {
monactive = 1;
}
}
if(monactive) {
ASSERTERR(dev->monitor._impl->write_message(&dev->monitor, &msg));
}
rc = tgt->_impl->write_message(tgt, &msg);
if(rc == -1) {
if(errno == EAGAIN) {
dev->_stat.discard_msg += 1;
while(msg.more) {
close_message(&msg);
ASSERTERR(src->_impl->read_message(src, &msg));
}
close_message(&msg);
return 0;
}
ASSERTERR(rc);
}
while(msg.more) {
close_message(&msg);
ASSERTERR(src->_impl->read_message(src, &msg));
if(monactive) {
ASSERTERR(dev->monitor._impl->write_message(&dev->monitor, &msg));
}
ASSERTERR(tgt->_impl->write_message(tgt, &msg));
}
close_message(&msg);
return 1;
}
static int iterate(context *ctx) {
int res = 0;
int any;
int rc;
CONFIG_STRING_DEVICE_LOOP(item, ctx->config->Devices) {
any = 0;
if(item->value.frontend._state.readable
&& item->value.backend._state.writeable) {
any = 1;
rc = forward(ctx,
&item->value.frontend,
&item->value.backend,
&item->value, 1);
assert(rc >= 0);
}
if(item->value.backend._state.readable
&& item->value.frontend._state.writeable) {
any = 1;
rc = forward(ctx,
&item->value.backend,
&item->value.frontend,
&item->value, 0);
assert(rc >= 0);
}
if(any) {
item->value.frontend._impl->check_state(&item->value.frontend);
item->value.backend._impl->check_state(&item->value.backend);
res = 1;
}
}
return res;
}
static int check_statistics(context *ctx, int timeout) {
if(!ctx->stat_interval)
return timeout;
struct timeval curtime;
gettimeofday(&curtime, NULL);
int64_t time = (int64_t)curtime.tv_sec * 1000 + curtime.tv_usec / 1000;
int64_t diff = ctx->nextstat - time;
if(diff < 0) {
char tstamp[32];
struct tm tm;
gmtime_r(&curtime.tv_sec, &tm);
strftime(tstamp, 32, "%Y-%m-%dT%H:%M:%SZ", &tm);
config_socket_t *statsock = &ctx->config->Estp.socket;
char buf[512];
sprintf(buf,
"ESTP:%.64s:paperjam::devices: %s %ld %lu",
ctx->config->Estp.hostname,
tstamp,
ctx->config->Estp.interval,
ctx->config->Devices_len);
statsock->_impl->write_string(statsock, buf, 0);
CONFIG_STRING_DEVICE_LOOP(item, ctx->config->Devices) {
if(IS_READABLE(&item->value.frontend)) {
sprintf(buf,
"ESTP:%.64s:paperjam:%.64s:input.messages: %s %ld %lu:c",
ctx->config->Estp.hostname,
item->value.frontend._name,
tstamp,
ctx->config->Estp.interval,
item->value._stat.input_msg);
statsock->_impl->write_string(statsock, buf, 0);
}
if(IS_WRITEABLE(&item->value.frontend)) {
sprintf(buf,
"ESTP:%.64s:paperjam:%.64s:output.messages: %s %ld %lu:c",
ctx->config->Estp.hostname,
item->value.frontend._name,
tstamp,
ctx->config->Estp.interval,
item->value._stat.output_msg);
statsock->_impl->write_string(statsock, buf, 0);
}
sprintf(buf,
"ESTP:%.64s:paperjam:%.64s:discard.messages: %s %ld %lu:c",
ctx->config->Estp.hostname,
item->value.frontend._name,
tstamp,
ctx->config->Estp.interval,
item->value._stat.discard_msg);
statsock->_impl->write_string(statsock, buf, 0);
}
ctx->nextstat = time - time % ctx->stat_interval + ctx->stat_interval;
diff = ctx->nextstat - time;
}
if(timeout == 0)
return 0;
return diff;
}
void loop(context *ctx) {
int maxpoll = ctx->config->Devices_len*2;
int nsocks = 0;
struct pollfd pollitems[maxpoll];
config_socket_t *sockets[maxpoll];
CONFIG_STRING_DEVICE_LOOP(item, ctx->config->Devices) {
config_socket_t *sock = &item->value.frontend;
pollitems[nsocks].fd = sock->_impl->get_fd(sock);
pollitems[nsocks].events = POLLIN;
sockets[nsocks] = sock;
nsocks += 1;
sock->_impl->check_state(sock);
sock = &item->value.backend;
pollitems[nsocks].fd = sock->_impl->get_fd(sock);
pollitems[nsocks].events = POLLIN;
sockets[nsocks] = sock;
nsocks += 1;
sock->_impl->check_state(sock);
}
int timeout = 0;
for(;;) {
timeout = check_statistics(ctx, timeout);
int rc = poll(pollitems, nsocks, timeout);
assert(rc >= 0); // remove
if(rc > 0) {
for(int i = 0; i < nsocks; ++i) {
if(pollitems[i].revents) {
sockets[i]->_impl->check_state(sockets[i]);
}
// TODO(tailhook) optimize if rc < nsocks
}
}
if(iterate(ctx)) {
// there is something to process, but we want to check other
// sockets too
timeout = 0;
} else {
// nothing to do, can wait indefinitely
timeout = -1;
}
}
}
int main(int argc, char **argv) {
config_main_t *config = config_load(NULL, argc, argv);
assert(config);
int zmq_socks = 0;
int xs_socks = 0;
context ctx;
memset(&ctx, 0, sizeof(ctx));
ctx.config = config;
if(config->Estp.socket.kind && config->Estp.interval) {
if(!IS_WRITEONLY(&config->Estp.socket)) {
fprintf(stderr, "Wrong socket for ESTP");
abort();
}
ctx.stat_interval = config->Estp.interval * 1000; // milliseconds
}
if(config->Estp.socket.kind) {
if(IS_XS(&config->Estp.socket)) {
xs_socks += 1;
XS_SOCKETERR(&config->Estp.socket,
open_xs_socket(&ctx, &config->Estp.socket));
} else {
zmq_socks += 1;
ZMQ_SOCKETERR(&config->Estp.socket,
open_zmq_socket(&ctx, &config->Estp.socket));
}
}
CONFIG_STRING_DEVICE_LOOP(item, config->Devices) {
item->value.frontend._name = item->key;
item->value.frontend._type = "frontend";
if(IS_XS(&item->value.frontend)) {
xs_socks += 1;
XS_SOCKETERR(&item->value.frontend,
open_xs_socket(&ctx, &item->value.frontend));
} else {
zmq_socks += 1;
ZMQ_SOCKETERR(&item->value.frontend,
open_zmq_socket(&ctx, &item->value.frontend));
}
item->value.backend._name = item->key;
item->value.backend._type = "backend";
if(IS_XS(&item->value.backend)) {
xs_socks += 1;
XS_SOCKETERR(&item->value.backend,
open_xs_socket(&ctx, &item->value.backend));
} else {
zmq_socks += 1;
ZMQ_SOCKETERR(&item->value.backend,
open_zmq_socket(&ctx, &item->value.backend));
}
device_check(&item->value.frontend, &item->value.backend);
item->value.monitor._name = item->key;
item->value.monitor._type = "monitor";
if(item->value.monitor.kind) {
if(IS_XS(&item->value.monitor)) {
xs_socks += 1;
XS_SOCKETERR(&item->value.monitor,
open_xs_socket(&ctx, &item->value.monitor));
} else {
zmq_socks += 1;
ZMQ_SOCKETERR(&item->value.monitor,
open_zmq_socket(&ctx, &item->value.monitor));
}
monitor_check(&item->value.monitor);
}
}
loop(&ctx);
CONFIG_STRING_DEVICE_LOOP(item, config->Devices) {
item->value.frontend._impl->close(&item->value.frontend);
item->value.backend._impl->close(&item->value.backend);
if(item->value.monitor._impl) {
item->value.monitor._impl->close(&item->value.monitor);
}
}
#ifdef HAVE_XS
if(ctx.xs_context) {
XS_ASSERTERR(xs_term(ctx.xs_context));
}
#endif
#ifdef HAVE_ZMQ
if(ctx.zmq_context) {
ZMQ_ASSERTERR(zmq_term(ctx.zmq_context));
}
#endif
}
|
tailhook/paperjam | src/handle_zmq.c |
#include <stdio.h>
#include <errno.h>
#include <assert.h>
#include <stdlib.h>
#include <stdint.h>
#include "handle_zmq.h"
#ifndef HAVE_ZMQ
int open_zmq_socket(context *ctx, config_socket_t *sock) {
fprintf(stderr, "Paperjam was compiled without libzmq support\n");
errno = ENOTSUP;
return -1;
}
#else
#ifndef ZMQ_DONTWAIT
# define ZMQ_DONTWAIT ZMQ_NOBLOCK
#endif
#define ZMQ_MORENWAIT (ZMQ_SNDMORE|ZMQ_DONTWAIT)
#if ZMQ_VERSION_MAJOR == 2
# define zmq_msg_send(msg, sock, opt) zmq_send (sock, msg, opt)
# define zmq_msg_recv(msg, sock, opt) zmq_recv (sock, msg, opt)
# define ZMQ_POLL_MSEC 1000 // zmq_poll is usec
# define ZMQ_MORE_TYPE uint64_t
# define ZMQ_EVENTS_TYPE uint32_t
#elif ZMQ_VERSION_MAJOR == 3
# define ZMQ_POLL_MSEC 1 // zmq_poll is msec
# define ZMQ_MORE_TYPE int
#endif
static int get_fd(config_socket_t *sock);
static int check_state(config_socket_t *sock);
static int read_message(config_socket_t *sock, message *msg);
static int write_message(config_socket_t *sock, message *msg);
static int write_string(config_socket_t *sock, const char *string, int more);
static int close_socket(config_socket_t *sock);
socket_impl zmq_socket_impl = {
get_fd: get_fd,
check_state: check_state,
read_message: read_message,
write_message: write_message,
write_string: write_string,
close: close_socket
};
int open_zmq_socket(context *ctx, config_socket_t *sock) {
if(!ctx->zmq_context) {
ctx->zmq_context = zmq_init(ctx->config->Zmq.io_threads);
if(!ctx->zmq_context)
return -1;
}
int type = 0;
switch(sock->kind) {
case CONFIG_zmq_Sub:
type = ZMQ_SUB;
break;
case CONFIG_zmq_Pub:
type = ZMQ_PUB;
break;
case CONFIG_zmq_Req:
type = ZMQ_DEALER;
break;
case CONFIG_zmq_Rep:
type = ZMQ_ROUTER;
break;
case CONFIG_zmq_Push:
type = ZMQ_PUSH;
break;
case CONFIG_zmq_Pull:
type = ZMQ_PULL;
break;
default:
assert(0);
break;
}
void *s = zmq_socket(ctx->zmq_context, type);
if(!s) return -1;
CONFIG_ENDPOINT_TYPE_LOOP(addr, sock->value) {
if(addr->value.kind == CONFIG_Bind) {
ZMQ_SOCKETERR(sock, zmq_bind(s, addr->value.value));
} else {
ZMQ_SOCKETERR(sock, zmq_connect(s, addr->value.value));
}
}
sock->_state.socket = s;
if(type == ZMQ_SUB) {
if(sock->subscribe_len) {
CONFIG_STRING_LOOP(topic, sock->subscribe) {
ZMQ_SOCKETERR(sock, zmq_setsockopt(s, ZMQ_SUBSCRIBE,
topic->value, topic->value_len));
}
} else {
ZMQ_SOCKETERR(sock, zmq_setsockopt(s, ZMQ_SUBSCRIBE, NULL, 0));
}
}
uint64_t hwm = sock->hwm;
ZMQ_SOCKETERR(sock, zmq_setsockopt(sock->_state.socket,
ZMQ_HWM, &hwm, sizeof(hwm)));
if(sock->identity_len) {
char *identity = sock->identity;
ZMQ_SOCKETERR(sock, zmq_setsockopt(sock->_state.socket,
ZMQ_IDENTITY, identity, sock->identity_len));
}
if(sock->affinity) {
uint64_t affinity = sock->affinity;
ZMQ_SOCKETERR(sock, zmq_setsockopt(sock->_state.socket,
ZMQ_AFFINITY, &affinity, sizeof(affinity)));
}
if(sock->sndbuf) {
uint64_t sndbuf = sock->sndbuf;
ZMQ_SOCKETERR(sock, zmq_setsockopt(sock->_state.socket,
ZMQ_SNDBUF, &sndbuf, sizeof(sndbuf)));
}
if(sock->rcvbuf) {
uint64_t rcvbuf = sock->rcvbuf;
ZMQ_SOCKETERR(sock, zmq_setsockopt(sock->_state.socket,
ZMQ_RCVBUF, &rcvbuf, sizeof(rcvbuf)));
}
int linger = sock->linger;
ZMQ_SOCKETERR(sock, zmq_setsockopt(sock->_state.socket,
ZMQ_LINGER, &linger, sizeof(linger)));
if(sock->rate) {
int64_t rate = sock->rate;
ZMQ_SOCKETERR(sock, zmq_setsockopt(sock->_state.socket,
ZMQ_RATE, &rate, sizeof(rate)));
}
if(sock->recovery_ivl) {
int64_t ivl = sock->recovery_ivl;
ZMQ_SOCKETERR(sock, zmq_setsockopt(sock->_state.socket,
ZMQ_RECOVERY_IVL_MSEC, &ivl, sizeof(ivl)));
}
if(sock->reconnect_ivl) {
int ivl = sock->reconnect_ivl;
ZMQ_SOCKETERR(sock, zmq_setsockopt(sock->_state.socket,
ZMQ_RECONNECT_IVL, &ivl, sizeof(ivl)));
}
if(sock->reconnect_ivl_max) {
int ivl = sock->reconnect_ivl_max;
ZMQ_SOCKETERR(sock, zmq_setsockopt(sock->_state.socket,
ZMQ_RECONNECT_IVL_MAX, &ivl, sizeof(ivl)));
}
if(sock->backlog) {
int backlog = sock->backlog;
ZMQ_SOCKETERR(sock, zmq_setsockopt(sock->_state.socket,
ZMQ_BACKLOG, &backlog, sizeof(backlog)));
}
sock->_impl = &zmq_socket_impl;
return 0;
}
static int close_socket(config_socket_t *sock) {
ZMQ_ASSERTERR(zmq_close(sock));
return 0;
}
static int get_fd(config_socket_t *sock) {
int fd;
size_t sz = sizeof(fd);
int rc = zmq_getsockopt(sock->_state.socket, ZMQ_FD, &fd, &sz);
if(rc < 0) return -1;
return fd;
}
static int check_state(config_socket_t *sock) {
ZMQ_EVENTS_TYPE ev;
size_t sz = sizeof(ev);
int rc = zmq_getsockopt(sock->_state.socket, ZMQ_EVENTS, &ev, &sz);
if(rc < 0) return -1;
sock->_state.readable = (ev & ZMQ_POLLIN) ? 1 : 0;
sock->_state.writeable = (ev & ZMQ_POLLOUT) ? 1 : 0;
return 0;
}
static int read_message(config_socket_t *sock, message *msg) {
int rc = zmq_msg_init(&msg->zmq_msg);
if(rc < 0) return rc;
rc = zmq_msg_recv(&msg->zmq_msg, sock->_state.socket, ZMQ_DONTWAIT);
if(rc < 0) return rc;
ZMQ_MORE_TYPE more;
size_t sz = sizeof(more);
rc = zmq_getsockopt(sock->_state.socket, ZMQ_RCVMORE, &more, &sz);
if(rc < 0) {
int oldeno = errno;
ZMQ_ASSERTERR(zmq_msg_close(&msg->zmq_msg));
errno = oldeno;
return rc;
}
msg->zmq = 1;
msg->more = more;
return 0;
}
static int write_message(config_socket_t *sock, message *msg) {
int rc;
# if HAVE_XS
if(!msg->zmq) {
assert(msg->xs);
// TODO(tailhook) optimize copying
size_t len = xs_msg_size(&msg->xs_msg);
rc = zmq_msg_init_size(&msg->zmq_msg, len);
if(rc < 0) return rc;
memcpy(zmq_msg_data(&msg->zmq_msg), xs_msg_data(&msg->xs_msg), len);
msg->zmq = 1;
}
# else
assert(msg->zmq);
# endif
zmq_msg_t tmsg;
// TODO(tailhook) optimize this copy
zmq_msg_init(&tmsg);
rc = zmq_msg_copy(&tmsg, &msg->zmq_msg);
if(rc < 0) return rc;
rc = zmq_msg_send(&tmsg, sock->_state.socket,
msg->more ? ZMQ_MORENWAIT : ZMQ_DONTWAIT);
ZMQ_ASSERTERR(zmq_msg_close(&tmsg));
return rc;
}
static int write_string(config_socket_t *sock, const char *str, int more) {
zmq_msg_t tmsg;
int len = strlen(str);
int rc = zmq_msg_init_size(&tmsg, len);
if(rc < 0) return rc;
memcpy(zmq_msg_data(&tmsg), str, len);
rc = zmq_msg_send(&tmsg, sock->_state.socket,
more ? ZMQ_MORENWAIT : ZMQ_DONTWAIT);
ZMQ_ASSERTERR(zmq_msg_close(&tmsg));
return rc;
}
#endif //HAVE_ZMQ
|
tailhook/paperjam | src/handle_xs.h | #ifndef _H_HANDLE_XS_
#define _H_HANDLE_XS_
#include "common.h"
#define FLAG_LIBXS 0x200
#define IS_XS(sock) (((sock)->kind & LIB_MASK) == FLAG_LIBXS)
#if HAVE_XS
#include <xs.h>
#define XS_ASSERTERR(val) if((val) == -1) { \
fprintf(stderr, "Assertion error" #val ": %s\n", xs_strerror(errno)); \
abort(); \
}
#define XS_SOCKETERR(sock, val) if((val) == -1) { \
fprintf(stderr, "Error on ``%s.%s'' at %s:%d: %s\n", \
(sock)->_name, (sock)->_type, __FILE__, __LINE__, \
xs_strerror(errno)); \
abort(); \
}
#else
#define XS_ASSERTERR(val) if((val) == -1) { \
fprintf(stderr, "Assertion error" #val ": %s\n", strerror(errno)); \
abort(); \
}
#define XS_SOCKETERR(sock, val) if((val) == -1) { \
fprintf(stderr, "Error on ``%s.%s'' at %s:%d: %s\n", \
(sock)->_name, (sock)->_type, __FILE__, __LINE__, \
strerror(errno)); \
abort(); \
}
#endif
int open_xs_socket(context *, config_socket_t *sock);
#endif //_H_HANDLE_XS_
|
tailhook/paperjam | src/handle_zmq.h | #ifndef _H_HANDLE_ZMQ_
#define _H_HANDLE_ZMQ_
#include "common.h"
#define FLAG_LIBZMQ 0x100
#define IS_ZMQ(sock) (((sock)->kind & LIB_MASK) == FLAG_LIBZMQ)
#if HAVE_ZMQ
#include <zmq.h>
#define ZMQ_SOCKETERR(sock, val) if((val) == -1) { \
fprintf(stderr, "Error on ``%s.%s'' at %s:%d: %s\n", \
(sock)->_name, (sock)->_type, __FILE__, __LINE__, \
zmq_strerror(errno)); \
abort(); \
}
#define ZMQ_ASSERTERR(val) if((val) == -1) { \
fprintf(stderr, "Assertion error at %s:%d: %s\n", \
__FILE__, __LINE__, \
zmq_strerror(errno)); \
abort(); \
}
#else
#define ZMQ_SOCKETERR(sock, val) if((val) == -1) { \
fprintf(stderr, "Error on ``%s.%s'' at %s:%d: %s\n", \
(sock)->_name, (sock)->_type, __FILE__, __LINE__, \
strerror(errno)); \
abort(); \
}
#define ZMQ_ASSERTERR(val) if((val) == -1) { \
fprintf(stderr, "Assertion error at %s:%d: %s\n", \
__FILE__, __LINE__, \
strerror(errno)); \
abort(); \
}
#endif
int open_zmq_socket(context *, config_socket_t *sock);
#endif //_H_HANDLE_ZMQ_
|
tailhook/paperjam | src/zmq_cli.c | <gh_stars>1-10
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <zmq.h>
#include "pjutil.h"
static void *open_context() {
return zmq_init(1);
}
static void configure_socket(void *sock) {
int opt;
int rc;
optind = 1;
while((opt = getopt_long(cli_options.argc, cli_options.argv,
short_options, long_options, NULL)) != -1) {
switch(opt) {
case 'b':
rc = zmq_bind(sock, optarg);
assert(rc != -1);
break;
case 'c':
rc = zmq_connect(sock, optarg);
assert(rc != -1);
break;
}
}
}
static int do_receive(void *sock, zmq_msg_t *msg) {
zmq_pollitem_t item = {sock, 0, ZMQ_POLLIN, 0 };
while(get_time() < cli_options.finishtime) {
int left = -1;
if(cli_options.timeout) {
left = (int)((cli_options.finishtime - get_time())*1000);
}
int rc = zmq_poll(&item, 1, left);
rc = zmq_recv(sock, msg, ZMQ_NOBLOCK);
if(rc == -1) {
if(errno == EAGAIN) continue;
else if(errno == EFSM) {
return 1;
} else {
perror("Error reading from socket");
exit(127);
}
}
return 0;
}
return 1;
}
static int do_send(void *sock, char *data, size_t len, int more) {
zmq_pollitem_t item = {sock, 0, ZMQ_POLLOUT, 0 };
while(get_time() < cli_options.finishtime) {
int left = -1;
if(cli_options.timeout) {
left = (int)((cli_options.finishtime - get_time())*1000);
}
int rc = zmq_poll(&item, 1, left);
zmq_msg_t msg;
zmq_msg_init_data(&msg, data, len, NULL, NULL);
rc = zmq_send(sock, &msg, (more ? ZMQ_SNDMORE : 0)|ZMQ_NOBLOCK);
if(rc == -1) {
if(errno == EAGAIN) continue;
else {
perror("Error writing to socket");
exit(127);
}
}
return 0;
}
return 1;
}
static void do_finish(void *sock, void *ctx) {
int linger = -1;
if(cli_options.timeout) {
linger = (int)((cli_options.finishtime - get_time())*1000);
}
zmq_setsockopt(sock, ZMQ_LINGER, &linger, sizeof(linger));
zmq_close(sock);
zmq_term(ctx);
}
static void reader_socket(int type) {
int rc;
void *ctx = open_context();
assert(ctx);
void *sock = zmq_socket(ctx, type);
assert(sock);
configure_socket(sock);
if(type == ZMQ_SUB) {
int rc = zmq_setsockopt(sock, ZMQ_SUBSCRIBE, "", 0);
assert(rc != -1);
}
while(1) {
zmq_msg_t msg;
zmq_msg_init(&msg);
if(do_receive(sock, &msg)) break;
uint64_t more = 0;
size_t moresz = sizeof(more);
rc = zmq_getsockopt(sock, ZMQ_RCVMORE, &more, &moresz);
assert(rc != -1);
print_message(zmq_msg_data(&msg), zmq_msg_size(&msg), more);
zmq_msg_close(&msg);
}
do_finish(sock, ctx);
}
static void writer_socket(int type) {
void *ctx = open_context();
assert(ctx);
void *sock = zmq_socket(ctx, type);
assert(sock);
configure_socket(sock);
for(char **m = cli_options.messages; *m; ++m) {
if(do_send(sock, *m, strlen(*m), *(m+1) ? 1 : 0)) break;
}
do_finish(sock, ctx);
}
void run_zmq_pull() {
reader_socket(ZMQ_PULL);
}
void run_zmq_push() {
writer_socket(ZMQ_PUSH);
}
void run_zmq_sub() {
reader_socket(ZMQ_SUB);
}
void run_zmq_pub() {
writer_socket(ZMQ_PUB);
}
void run_zmq_req() {
int rc;
void *ctx = open_context();
assert(ctx);
void *sock = zmq_socket(ctx, ZMQ_REQ);
assert(sock);
configure_socket(sock);
for(char **m = cli_options.messages; *m; ++m) {
if(do_send(sock, *m, strlen(*m), *(m+1) ? 1 : 0)) break;
}
uint64_t more = 1;
size_t moresz = sizeof(more);
while(more) {
zmq_msg_t msg;
zmq_msg_init(&msg);
if(do_receive(sock, &msg)) break;
rc = zmq_getsockopt(sock, ZMQ_RCVMORE, &more, &moresz);
assert(rc != -1);
print_message(zmq_msg_data(&msg), zmq_msg_size(&msg), more);
zmq_msg_close(&msg);
}
do_finish(sock, ctx);
}
void run_zmq_rep() {
int rc;
void *ctx = open_context();
assert(ctx);
void *sock = zmq_socket(ctx, ZMQ_REP);
assert(sock);
configure_socket(sock);
while(1) {
uint64_t more = 1;
size_t moresz = sizeof(more);
while(more) {
zmq_msg_t msg;
zmq_msg_init(&msg);
if(do_receive(sock, &msg)) goto end;
rc = zmq_getsockopt(sock, ZMQ_RCVMORE, &more, &moresz);
assert(rc != -1);
print_message(zmq_msg_data(&msg), zmq_msg_size(&msg), more);
zmq_msg_close(&msg);
}
for(char **m = cli_options.messages; *m; ++m) {
if(do_send(sock, *m, strlen(*m), *(m+1) ? 1 : 0)) goto end;
}
}
end:
do_finish(sock, ctx);
}
|
tailhook/paperjam | src/pjmonitor.c | <filename>src/pjmonitor.c
#include <malloc.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <poll.h>
#include <getopt.h>
#include "config.h"
#include "handle_zmq.h"
#include "handle_xs.h"
#include "pjmon.h"
#include "print.h"
#define ASSERTERR(val) if((val) == -1) { \
fprintf(stderr, "Assertion error at %s:%d: %s\n", \
__FILE__, __LINE__, \
strerror(errno)); \
abort(); \
}
static int close_message(message *msg) {
// TODO(tailhook)
if(msg->zmq) {
#ifdef HAVE_ZMQ
ZMQ_ASSERTERR(zmq_msg_close(&msg->zmq_msg));
#else
assert(0);
#endif
}
if(msg->xs) {
#ifdef HAVE_XS
XS_ASSERTERR(xs_msg_close(&msg->xs_msg));
#else
assert(0);
#endif
}
msg->xs = 0;
msg->zmq = 0;
msg->more = 0;
return 0;
}
static int printmsg(context *ctx, config_socket_t *mon)
{
message msg;
msg.xs = 0;
msg.zmq = 0;
msg.more = 0;
int rc = mon->_impl->read_message(mon, &msg);
if(rc == -1) {
if(errno == EAGAIN) {
mon->_state.readable = 0;
return 0;
}
ASSERTERR(rc);
}
printf("[%s] ", mon->_name);
if(msg.xs) {
#ifdef HAVE_XS
print_message(
(char *)xs_msg_data(&msg.xs_msg),
(int)xs_msg_size(&msg.xs_msg),
msg.more);
#endif
} else if(msg.zmq) {
#ifdef HAVE_ZMQ
print_message(
(char *)zmq_msg_data(&msg.zmq_msg),
(int)zmq_msg_size(&msg.zmq_msg),
msg.more);
#endif
}
while(msg.more) {
close_message(&msg);
ASSERTERR(mon->_impl->read_message(mon, &msg));
if(msg.xs) {
#ifdef HAVE_XS
print_message(
(char *)xs_msg_data(&msg.xs_msg),
(int)xs_msg_size(&msg.xs_msg),
msg.more);
#endif
} else if(msg.zmq) {
#ifdef HAVE_ZMQ
print_message(
(char *)zmq_msg_data(&msg.zmq_msg),
(int)zmq_msg_size(&msg.zmq_msg),
msg.more);
#endif
}
}
close_message(&msg);
return 1;
}
static int iterate(context *ctx) {
int res = 0; // total number of messages done
int iter; // messages on single socket pair
int rc;
CONFIG_STRING_DEVICE_LOOP(item, ctx->config->Devices) {
if(item->value.monitor._state.readable) {
iter = 0;
do {
iter += 1;
rc = printmsg(ctx, &item->value.monitor);
assert(rc >= 0);
} while(rc && iter < 100);
if(iter) {
item->value.monitor._impl->check_state(&item->value.frontend);
res = 1;
}
}
}
return res;
}
void loop(context *ctx) {
int maxpoll = ctx->config->Devices_len*2;
int nsocks = 0;
struct pollfd pollitems[maxpoll];
config_socket_t *sockets[maxpoll];
CONFIG_STRING_DEVICE_LOOP(item, ctx->config->Devices) {
if(!item->value.monitor._impl) continue;
config_socket_t *sock = &item->value.monitor;
pollitems[nsocks].fd = sock->_impl->get_fd(sock);
pollitems[nsocks].events = POLLIN;
sockets[nsocks] = sock;
nsocks += 1;
sock->_impl->check_state(sock);
}
int timeout = 0;
for(;;) {
int rc = poll(pollitems, nsocks, timeout);
assert(rc >= 0); // remove
if(rc > 0) {
for(int i = 0; i < nsocks; ++i) {
if(pollitems[i].revents) {
sockets[i]->_impl->check_state(sockets[i]);
}
// TODO(tailhook) optimize if rc < nsocks
}
}
if(iterate(ctx)) {
// there is something to process, but we want to check other
// sockets too
timeout = 0;
} else {
// nothing to do, can wait indefinitely
timeout = -1;
}
}
}
int main(int argc, char **argv) {
config_main_t *config = malloc(sizeof(config_main_t));
assert(config);
config_load(config, argc, argv);
int zmq_socks = 0;
int xs_socks = 0;
context ctx;
memset(&ctx, 0, sizeof(ctx));
ctx.config = config;
config->Zmq.io_threads = 1; // no need more threads for monitor
config->Xs.io_threads = 1; // no need more threads for monitor
CONFIG_STRING_DEVICE_LOOP(item, config->Devices) {
item->value.monitor._name = item->key;
item->value.monitor._type = "monitor";
if(optind < argc) {
int i;
for(i = optind; i < argc; ++i) {
if(!strcmp(item->key, argv[i])) break;
}
if(i >= argc) continue;
}
if(item->value.monitor.kind) {
switch(item->value.monitor.kind) {
case CONFIG_zmq_Push:
item->value.monitor.kind = CONFIG_zmq_Pull;
break;
case CONFIG_zmq_Pub:
item->value.monitor.kind = CONFIG_zmq_Sub;
break;
case CONFIG_xs_Push:
item->value.monitor.kind = CONFIG_xs_Pull;
break;
case CONFIG_xs_Pub:
item->value.monitor.kind = CONFIG_xs_Sub;
break;
default:
fprintf(stderr, "Wrong monitor socket for %s", item->key);
abort();
}
CONFIG_ENDPOINT_TYPE_LOOP(addr, item->value.monitor.value) {
if(addr->value.kind == CONFIG_Bind) {
addr->value.kind = CONFIG_Connect;
} else {
addr->value.kind = CONFIG_Bind;
}
}
if(IS_XS(&item->value.monitor)) {
xs_socks += 1;
XS_SOCKETERR(&item->value.monitor,
open_xs_socket(&ctx, &item->value.monitor));
} else {
zmq_socks += 1;
ZMQ_SOCKETERR(&item->value.monitor,
open_zmq_socket(&ctx, &item->value.monitor));
}
}
}
loop(&ctx);
CONFIG_STRING_DEVICE_LOOP(item, config->Devices) {
if(item->value.monitor._impl) {
item->value.monitor._impl->close(&item->value.monitor);
}
}
#ifdef HAVE_XS
if(ctx.xs_context) {
XS_ASSERTERR(xs_term(ctx.xs_context));
}
#endif
#ifdef HAVE_ZMQ
if(ctx.zmq_context) {
ZMQ_ASSERTERR(zmq_term(ctx.zmq_context));
}
#endif
}
|
tailhook/paperjam | src/print.c | #include <stdio.h>
#include <ctype.h>
void print_message(char *data, size_t len, int more) {
FILE *stream = stdout;
fputc('"', stream);
for(char *c = data, *end = data + len; c < end; ++c) {
if(isprint(*c)) {
if(*c == '\\') {
fprintf(stream, "\\\\");
} else if(*c == '"') {
fprintf(stream, "\\\"");
} else {
fputc(*c, stream);
}
} else if(*c == '\r') {
fprintf(stream, "\\r");
} else if(*c == '\n') {
fprintf(stream, "\\n");
} else {
fprintf(stream, "-\\x%02hhx", *c);
}
}
fputc('"', stream);
if(more)
fputc(' ', stream);
else
fputc('\n', stream);
fflush(stream);
}
|
tailhook/paperjam | src/xs_cli.c | #include <assert.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <xs.h>
#include "config.h"
#include "pjutil.h"
static void *open_context() {
return xs_init();
}
static void configure_socket(void *sock) {
int opt;
int rc;
optind = 1;
while((opt = getopt_long(cli_options.argc, cli_options.argv,
short_options, long_options, NULL)) != -1) {
switch(opt) {
case 'b':
rc = xs_bind(sock, optarg);
assert(rc != -1);
break;
case 'c':
rc = xs_connect(sock, optarg);
assert(rc != -1);
break;
}
}
}
static int do_receive(void *sock, xs_msg_t *msg) {
int rc = 0;
while(get_time() < cli_options.finishtime) {
if(cli_options.timeout) {
int left = (int)((cli_options.finishtime - get_time())*1000);
// Using RCVTIMEO for reading instead xs_poll
// due to a bug in libxs 1.1.0 and surveyor socket
rc = xs_setsockopt(sock, XS_RCVTIMEO, &left, sizeof(left));
assert(rc != -1);
}
rc = xs_recvmsg(sock, msg, 0);
if(rc == -1) {
if(errno == EAGAIN) continue;
else if(errno == EFSM) {
return 1;
} else {
perror("Error reading from socket");
exit(127);
}
}
return 0;
}
return 1;
}
static int do_send(void *sock, char *data, size_t len, int more) {
int rc;
while(get_time() < cli_options.finishtime) {
if(cli_options.timeout) {
int left = (int)((cli_options.finishtime - get_time())*1000);
// Using SNDTIMEO for writing instead xs_poll
// due to a bug in libxs 1.1.0 and surveyor socket
rc = xs_setsockopt(sock, XS_SNDTIMEO, &left, sizeof(left));
assert(rc != -1);
}
rc = xs_send(sock, data, len, (more ? XS_SNDMORE : 0));
if(rc == -1) {
if(errno == EAGAIN) continue;
else {
perror("Error writing to socket");
exit(127);
}
}
return 0;
}
return 1;
}
static void do_finish(void *sock, void *ctx) {
int linger = -1;
if(cli_options.timeout) {
linger = (int)((cli_options.finishtime - get_time())*1000);
}
xs_setsockopt(sock, XS_LINGER, &linger, sizeof(linger));
xs_close(sock);
xs_term(ctx);
}
static void reader_socket(int type) {
int rc;
void *ctx = open_context();
assert(ctx);
void *sock = xs_socket(ctx, type);
assert(sock);
configure_socket(sock);
if(type == XS_SUB) {
rc = xs_setsockopt(sock, XS_SUBSCRIBE, "", 0);
assert(rc != -1);
}
while(1) {
xs_msg_t msg;
xs_msg_init(&msg);
if(do_receive(sock, &msg)) break;
uint64_t more = 0;
size_t moresz = sizeof(more);
rc = xs_getsockopt(sock, XS_RCVMORE, &more, &moresz);
assert(rc != -1);
print_message(xs_msg_data(&msg), xs_msg_size(&msg), more);
xs_msg_close(&msg);
}
do_finish(sock, ctx);
}
static void writer_socket(int type) {
void *ctx = open_context();
assert(ctx);
void *sock = xs_socket(ctx, type);
assert(sock);
configure_socket(sock);
if(type == XS_PUB) {
// Let's wait for subscriptions to be forwarded
// TODO(pc) make this interval customizable
xs_poll(NULL, 0, 100);
}
for(char **m = cli_options.messages; *m; ++m) {
if(do_send(sock, *m, strlen(*m), *(m+1) ? XS_SNDMORE : 0)) break;
}
do_finish(sock, ctx);
}
void run_xs_pull() {
reader_socket(XS_PULL);
}
void run_xs_push() {
writer_socket(XS_PUSH);
}
void run_xs_sub() {
reader_socket(XS_SUB);
}
void run_xs_pub() {
writer_socket(XS_PUB);
}
static void request(int type) {
int rc;
void *ctx = open_context();
assert(ctx);
void *sock = xs_socket(ctx, type);
assert(sock);
configure_socket(sock);
for(char **m = cli_options.messages; *m; ++m) {
if(do_send(sock, *m, strlen(*m), *(m+1) ? XS_SNDMORE : 0)) break;
}
uint64_t more = 1;
size_t moresz = sizeof(more);
while(1) {
xs_msg_t msg;
xs_msg_init(&msg);
if(do_receive(sock, &msg)) break;
rc = xs_getsockopt(sock, XS_RCVMORE, &more, &moresz);
assert(rc != -1);
print_message(xs_msg_data(&msg), xs_msg_size(&msg), more);
xs_msg_close(&msg);
}
do_finish(sock, ctx);
}
static void reply(int type) {
int rc;
void *ctx = open_context();
assert(ctx);
void *sock = xs_socket(ctx, type);
assert(sock);
configure_socket(sock);
while(1) {
uint64_t more = 1;
size_t moresz = sizeof(more);
while(more) {
xs_msg_t msg;
xs_msg_init(&msg);
if(do_receive(sock, &msg)) goto end;
rc = xs_getsockopt(sock, XS_RCVMORE, &more, &moresz);
assert(rc != -1);
print_message(xs_msg_data(&msg), xs_msg_size(&msg), more);
xs_msg_close(&msg);
}
for(char **m = cli_options.messages; *m; ++m) {
if(do_send(sock, *m, strlen(*m), *(m+1) ? 1 : 0)) goto end;
}
}
end:
do_finish(sock, ctx);
}
void run_xs_req() {
request(XS_REQ);
}
void run_xs_rep() {
reply(XS_REP);
}
# ifdef HAVE_SURVEY
void run_xs_surveyor() {
request(XS_SURVEYOR);
}
void run_xs_respondent() {
reply(XS_RESPONDENT);
}
# endif
|
tailhook/paperjam | src/zmq_cli.h | <filename>src/zmq_cli.h
#ifndef _H_ZMQ_CLI
#define _H_ZMQ_CLI
void run_zmq_pull();
void run_zmq_push();
void run_zmq_sub();
void run_zmq_pub();
void run_zmq_req();
void run_zmq_rep();
#endif // _H_ZMQ_CLI
|
tailhook/paperjam | src/handle_xs.c |
#include <stdio.h>
#include <errno.h>
#include <assert.h>
#include <stdlib.h>
#include <stdint.h>
#include "handle_xs.h"
#ifndef HAVE_XS
int open_xs_socket(context *ctx, config_socket_t *sock) {
fprintf(stderr, "Paperjam was compiled without libxs support\n");
errno = ENOTSUP;
return -1;
}
#else // HAVE_XS
#define XS_MORENWAIT (XS_DONTWAIT|XS_SNDMORE)
static int get_fd(config_socket_t *sock);
static int check_state(config_socket_t *sock);
static int read_message(config_socket_t *sock, message *msg);
static int write_message(config_socket_t *sock, message *msg);
static int write_string(config_socket_t *sock, const char *string, int more);
static int close_socket(config_socket_t *sock);
socket_impl xs_socket_impl = {
get_fd: get_fd,
check_state: check_state,
read_message: read_message,
write_message: write_message,
write_string: write_string,
close: close_socket
};
int open_xs_socket(context *ctx, config_socket_t *sock) {
if(!ctx->xs_context) {
ctx->xs_context = xs_init();
if(!ctx->xs_context)
return -1;
int threads = ctx->config->Xs.io_threads;
if(xs_setctxopt(ctx->xs_context, XS_IO_THREADS,
&threads, sizeof(threads)) == -1) {
xs_term(ctx->xs_context);
ctx->xs_context = NULL;
return -1;
}
int max_sockets = ctx->config->Xs.max_sockets;
if(xs_setctxopt(ctx->xs_context, XS_MAX_SOCKETS,
&max_sockets, sizeof(max_sockets)) == -1) {
xs_term(ctx->xs_context);
ctx->xs_context = NULL;
return -1;
}
}
int type = 0;
switch(sock->kind) {
case CONFIG_xs_Sub:
type = XS_SUB;
break;
case CONFIG_xs_Pub:
type = XS_PUB;
break;
case CONFIG_xs_Req:
type = XS_XREQ;
break;
case CONFIG_xs_Rep:
type = XS_XREP;
break;
case CONFIG_xs_Push:
type = XS_PUSH;
break;
case CONFIG_xs_Pull:
type = XS_PULL;
break;
# ifdef HAVE_SURVEY
case CONFIG_xs_Surveyor:
type = XS_XSURVEYOR;
break;
case CONFIG_xs_Respondent:
type = XS_XRESPONDENT;
break;
# else
// TODO(tailhook) check this at configuration parsing stage
case CONFIG_xs_Surveyor:
case CONFIG_xs_Respondent:
fprintf(stderr, "Survey pattern is not supported by libxs 1.0\n");
errno = ENOTSUP;
return -1;
# endif
default:
assert(0);
break;
}
void *s = xs_socket(ctx->xs_context, type);
if(!s) return -1;
CONFIG_ENDPOINT_TYPE_LOOP(addr, sock->value) {
if(addr->value.kind == CONFIG_Bind) {
XS_SOCKETERR(sock, xs_bind(s, addr->value.value));
} else {
XS_SOCKETERR(sock, xs_connect(s, addr->value.value));
}
}
sock->_state.socket = s;
if(type == XS_SUB) {
if(sock->subscribe_len) {
CONFIG_STRING_LOOP(topic, sock->subscribe) {
XS_SOCKETERR(sock, xs_setsockopt(s, XS_SUBSCRIBE,
topic->value, topic->value_len));
}
} else {
XS_SOCKETERR(sock, xs_setsockopt(s, XS_SUBSCRIBE, NULL, 0));
}
}
int hwm = sock->sndhwm;
XS_SOCKETERR(sock, xs_setsockopt(sock->_state.socket,
XS_SNDHWM, &hwm, sizeof(hwm)));
hwm = sock->rcvhwm;
XS_SOCKETERR(sock, xs_setsockopt(sock->_state.socket,
XS_RCVHWM, &hwm, sizeof(hwm)));
if(sock->identity_len) {
char *identity = sock->identity;
XS_SOCKETERR(sock, xs_setsockopt(sock->_state.socket,
XS_IDENTITY, identity, sock->identity_len));
}
if(sock->affinity) {
uint64_t affinity = sock->affinity;
XS_SOCKETERR(sock, xs_setsockopt(sock->_state.socket,
XS_AFFINITY, &affinity, sizeof(affinity)));
}
if(sock->sndbuf) {
int sndbuf = sock->sndbuf;
XS_SOCKETERR(sock, xs_setsockopt(sock->_state.socket,
XS_SNDBUF, &sndbuf, sizeof(sndbuf)));
}
if(sock->rcvbuf) {
int rcvbuf = sock->rcvbuf;
XS_SOCKETERR(sock, xs_setsockopt(sock->_state.socket,
XS_RCVBUF, &rcvbuf, sizeof(rcvbuf)));
}
int linger = sock->linger;
XS_SOCKETERR(sock, xs_setsockopt(sock->_state.socket,
XS_LINGER, &linger, sizeof(linger)));
if(sock->rate) {
int rate = sock->rate;
XS_SOCKETERR(sock, xs_setsockopt(sock->_state.socket,
XS_RATE, &rate, sizeof(rate)));
}
if(sock->recovery_ivl) {
int ivl = sock->recovery_ivl;
XS_SOCKETERR(sock, xs_setsockopt(sock->_state.socket,
XS_RECOVERY_IVL, &ivl, sizeof(ivl)));
}
if(sock->reconnect_ivl) {
int ivl = sock->reconnect_ivl;
XS_SOCKETERR(sock, xs_setsockopt(sock->_state.socket,
XS_RECONNECT_IVL, &ivl, sizeof(ivl)));
}
if(sock->reconnect_ivl_max) {
int ivl = sock->reconnect_ivl_max;
XS_SOCKETERR(sock, xs_setsockopt(sock->_state.socket,
XS_RECONNECT_IVL_MAX, &ivl, sizeof(ivl)));
}
if(sock->backlog) {
int backlog = sock->backlog;
XS_SOCKETERR(sock, xs_setsockopt(sock->_state.socket,
XS_BACKLOG, &backlog, sizeof(backlog)));
}
if(sock->maxmsgsize) {
uint64_t maxmsg = sock->maxmsgsize;
XS_SOCKETERR(sock, xs_setsockopt(sock->_state.socket,
XS_MAXMSGSIZE, &maxmsg, sizeof(maxmsg)));
}
if(sock->multicast_hops) {
int mhops = sock->multicast_hops;
XS_SOCKETERR(sock, xs_setsockopt(sock->_state.socket,
XS_MULTICAST_HOPS, &mhops, sizeof(mhops)));
}
int ipv4only = sock->ipv4only;
XS_SOCKETERR(sock, xs_setsockopt(sock->_state.socket,
XS_IPV4ONLY, &ipv4only, sizeof(ipv4only)));
#ifdef XS_KEEPALIVE
if(sock->keepalive) {
int keepalive = sock->keepalive;
XS_SOCKETERR(sock, xs_setsockopt(sock->_state.socket,
XS_KEEPALIVE, &keepalive, sizeof(keepalive)));
}
#endif
sock->_impl = &xs_socket_impl;
return 0;
}
static int close_socket(config_socket_t *sock) {
XS_ASSERTERR(xs_close(sock));
return 0;
}
static int get_fd(config_socket_t *sock) {
int fd;
size_t sz = sizeof(fd);
int rc = xs_getsockopt(sock->_state.socket, XS_FD, &fd, &sz);
if(rc < 0) return -1;
return fd;
}
static int check_state(config_socket_t *sock) {
int ev;
size_t sz = sizeof(ev);
int rc = xs_getsockopt(sock->_state.socket, XS_EVENTS, &ev, &sz);
if(rc < 0) return -1;
sock->_state.readable = (ev & XS_POLLIN) ? 1 : 0;
sock->_state.writeable = (ev & XS_POLLOUT) ? 1 : 0;
return 0;
}
static int read_message(config_socket_t *sock, message *msg) {
int rc = xs_msg_init(&msg->xs_msg);
if(rc < 0) return rc;
rc = xs_recvmsg(sock->_state.socket, &msg->xs_msg, XS_DONTWAIT);
if(rc < 0) return rc;
int more;
size_t sz = sizeof(more);
rc = xs_getsockopt(sock->_state.socket, XS_RCVMORE, &more, &sz);
if(rc < 0) {
int oldeno = errno;
XS_ASSERTERR(xs_msg_close(&msg->xs_msg));
errno = oldeno;
return rc;
}
msg->xs = 1;
msg->more = more;
return 0;
}
static int write_message(config_socket_t *sock, message *msg) {
int rc;
# if HAVE_ZMQ
if(!msg->xs) {
assert(msg->zmq);
// TODO(tailhook) optimize copying
size_t len = zmq_msg_size(&msg->zmq_msg);
rc = xs_msg_init_size(&msg->xs_msg, len);
if(rc < 0) return rc;
memcpy(xs_msg_data(&msg->xs_msg), zmq_msg_data(&msg->zmq_msg), len);
msg->xs = 1;
}
# else
assert(msg->xs);
# endif
xs_msg_t tmsg;
// TODO(tailhook) optimize this copy
xs_msg_init(&tmsg);
rc = xs_msg_copy(&tmsg, &msg->xs_msg);
if(rc < 0) return rc;
rc = xs_sendmsg(sock->_state.socket, &tmsg,
msg->more ? XS_MORENWAIT : XS_DONTWAIT);
XS_ASSERTERR(xs_msg_close(&tmsg));
return rc;
}
static int write_string(config_socket_t *sock, const char *str, int more) {
xs_msg_t tmsg;
int len = strlen(str);
int rc = xs_msg_init_size(&tmsg, len);
if(rc < 0) return rc;
memcpy(xs_msg_data(&tmsg), str, len);
rc = xs_sendmsg(sock->_state.socket, &tmsg,
more ? XS_MORENWAIT : XS_DONTWAIT);
XS_ASSERTERR(xs_msg_close(&tmsg));
return rc;
}
#endif //HAVE_XS
|
tailhook/paperjam | src/common.h | #ifndef _H_COMMON_
#define _H_COMMON_
#include "config.h"
#include CONFIG_HEADER
#ifdef HAVE_XS
#include <xs.h>
#endif
#ifdef HAVE_ZMQ
#include <zmq.h>
#endif
#define LIB_MASK 0xf00
#define IS_READONLY(sock) ((sock)->kind == CONFIG_zmq_Pull \
|| (sock)->kind == CONFIG_zmq_Sub \
|| (sock)->kind == CONFIG_xs_Sub \
|| (sock)->kind == CONFIG_xs_Pull \
)
#define IS_READABLE(sock) (IS_READONLY(sock) || IS_REQ(sock) || IS_REP(sock))
#define IS_WRITEONLY(sock) ((sock)->kind == CONFIG_zmq_Push \
|| (sock)->kind == CONFIG_zmq_Pub \
|| (sock)->kind == CONFIG_xs_Pub \
|| (sock)->kind == CONFIG_xs_Push \
)
#define IS_WRITEABLE(sock) (IS_WRITEONLY(sock) || IS_REQ(sock) || IS_REP(sock))
#define IS_REQ(sock) ((sock)->kind == CONFIG_zmq_Req \
|| (sock)->kind == CONFIG_xs_Req \
|| (sock)->kind == CONFIG_xs_Surveyor \
)
#define IS_REP(sock) ((sock)->kind == CONFIG_zmq_Rep \
|| (sock)->kind == CONFIG_xs_Rep \
|| (sock)->kind == CONFIG_xs_Respondent \
)
typedef struct message {
int more;
int xs;
int zmq;
#ifdef HAVE_XS
xs_msg_t xs_msg;
#endif
#ifdef HAVE_ZMQ
zmq_msg_t zmq_msg;
#endif
} message;
typedef struct context {
config_main_t *config;
int stat_interval;
int64_t nextstat;
void *xs_context;
void *zmq_context;
} context;
#endif // _H_COMMON_
|
tailhook/paperjam | src/support.h | #ifndef _H_SUPPORT_
#define _H_SUPPORT_
struct config_socket_s;
struct message;
struct context;
typedef struct socket_impl {
int (*close)(struct config_socket_s *sock);
int (*get_fd)(struct config_socket_s *sock);
int (*check_state)(struct config_socket_s *sock);
int (*write_string)(struct config_socket_s *sock, const char *string, int more);
int (*write_message)(struct config_socket_s *sock, struct message *msg);
int (*read_message)(struct config_socket_s *sock, struct message *msg);
} socket_impl;
typedef struct socket_state {
void *socket;
int pollindex;
int readable;
int writeable;
} socket_state;
typedef struct device_stat {
size_t input_msg;
size_t output_msg;
size_t discard_msg;
} device_stat;
#endif // _H_SUPPORT_
|
tailhook/paperjam | src/xs_cli.h | #ifndef _H_XS_CLI
#define _H_XS_CLI
void run_xs_pull();
void run_xs_push();
void run_xs_sub();
void run_xs_pub();
void run_xs_req();
void run_xs_rep();
void run_xs_surveyor();
void run_xs_respondent();
#endif // _H_XS_CLI
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.