* Static parameter passing (enabled with --static-params): uses fixed memory
  locations for parameter passing. Only applied to functions declared
  'static' that don't have their address taken. The externally-visible
  calling convention is unchanged.

* Leaf function optimization (enabled with --leaf): leaf functions (i.e.
  functions that don't call other functions) use a special block of zero
  page memory (leafregbank). By default it is 16 bytes, but this can be
  changed with --leaf-space. If --leaf is combined with --static-params,
  leaf function parameters are passed directly in zero page. All locals in
  leaf functions use zero page (space permitting); the "register" keyword
  has no effect.

* Using the hardware stack for zero page save/restore (enabled by
  --hardware-stack): uses PHA for saving locals declared as "register". This
  is much faster than using the C stack, and often (but not always) more
  compact. Since the default maximum is only 6 bytes per function, there is
  not much risk of stack overflow, but it could happen.

* Optimizes zero page global pointers (marked with #pragma zpsym): pointers
  in zero page are now used directly, instead of being treated as if they
  weren't in zero page.

* Automatically use "fastcall" (enabled by --fastcall): automatically
  applies fastcall calling convention to static functions. This just saves
  having to type "fastcall" in function declarations. Despite its name,
  fastcall is not really faster, but it is more compact for functions called
  more than once.

* String merge (enabled by --string-merge): merges duplicate string
  literals.

diff -b -up cc65.org\make\gcc.mak cc65\make\gcc.mak
--- cc65.org\make\gcc.mak	Sun Dec 11 08:40:50 2005
+++ cc65\make\gcc.mak	Wed Jul 04 14:30:06 2007
@@ -57,6 +57,7 @@ OBJS =	anonname.o	\
 	expr.o	 	\
         exprdesc.o      \
 	funcdesc.o	\
+	funcremember.o	\
 	function.o     	\
 	global.o 	\
 	goto.o	   	\
diff -b -up cc65.org\make\watcom.mak cc65\make\watcom.mak
--- cc65.org\make\watcom.mak	Fri Mar 25 18:27:40 2005
+++ cc65\make\watcom.mak	Wed Jul 04 14:30:36 2007
@@ -92,6 +92,7 @@ OBJS =	anonname.obj	\
 	expr.obj 	\
         exprdesc.obj    \
 	funcdesc.obj	\
+	funcremember.o	\
 	function.obj	\
 	global.obj	\
 	goto.obj	\

diff -b -up cc65.org\anonname.c cc65\anonname.c
--- cc65.org\anonname.c	Fri Nov 15 09:19:46 2002
+++ cc65\anonname.c	Wed Jun 27 13:12:00 2007
@@ -63,7 +63,7 @@ char* AnonName (char* Buf, const char* S
  */
 {
     static unsigned ACount = 0;
-    sprintf (Buf, "%s-%s-%04X", AnonTag, Spec, ++ACount);
+    sprintf (Buf, "%s-%s-%08X", AnonTag, Spec, ++ACount);
     return Buf;
 }
 
diff -b -up cc65.org\asmlabel.c cc65\asmlabel.c
--- cc65.org\asmlabel.c	Thu Apr 19 02:49:08 2001
+++ cc65\asmlabel.c	Tue Jul 03 07:40:38 2007
@@ -39,6 +39,16 @@
 #include "asmlabel.h"
 
 
+/*****************************************************************************/
+/*	  			     Data				     */
+/*****************************************************************************/
+
+
+
+/* Number to generate unique labels */
+static unsigned NextLabel = 0;
+
+
 
 /*****************************************************************************/
 /*	  			     Code				     */
@@ -46,11 +56,16 @@
 
 
 
+void InitLocalLabel(void)
+/* Init label generation */
+{
+	NextLabel = 0;
+}
+
+
 unsigned GetLocalLabel (void)
 /* Get an unused label. Will never return zero. */
 {
-    /* Number to generate unique labels */
-    static unsigned NextLabel = 0;
     return ++NextLabel;
 }
 
@@ -63,7 +78,7 @@ const char* LocalLabelName (unsigned L)
  */
 {		 
     static char Buf[64];
-    sprintf (Buf, "L%04X", L);
+    sprintf (Buf, "L%08X", L);
     return Buf;
 }
 
diff -b -up cc65.org\asmlabel.h cc65\asmlabel.h
--- cc65.org\asmlabel.h	Thu Apr 19 02:49:08 2001
+++ cc65\asmlabel.h	Tue Jul 03 07:40:26 2007
@@ -43,6 +43,8 @@
 /*****************************************************************************/
 
 
+void InitLocalLabel(void);
+/* Init label generation */
 
 unsigned GetLocalLabel (void);
 /* Get an unused assembler label. Will never return zero. */
diff -b -up cc65.org\asmstmt.c cc65\asmstmt.c
--- cc65.org\asmstmt.c	Sat Nov 27 16:52:06 2004
+++ cc65\asmstmt.c	Wed Jun 27 13:11:16 2007
@@ -231,12 +231,15 @@ static void ParseGVarArg (StrBuf* T, uns
 	SB_AppendStr (T, Sym->Name);
     } else if (Sym->Flags & SC_REGISTER) {
         char Buf[32];
+		if (GetLeafFlag (F_GetFuncDesc (CurrentFunc)))
+	        xsprintf (Buf, sizeof (Buf), "leafregbank+%d", Sym->V.R.RegOffs);
+		else
         xsprintf (Buf, sizeof (Buf), "regbank+%d", Sym->V.R.RegOffs);
         SB_AppendStr (T, Buf);
     } else {
 	/* Static variable */
 	char Buf [16];
-    	xsprintf (Buf, sizeof (Buf), "L%04X", Sym->V.Label);
+    	xsprintf (Buf, sizeof (Buf), "L%08X", Sym->V.Label);
     	SB_AppendStr (T, Buf);
     }
 }

diff -b -up cc65.org\codeent.c cc65\codeent.c
--- cc65.org\codeent.c	Sun Sep 11 08:52:12 2005
+++ cc65\codeent.c	Sat Jun 30 09:25:22 2007
@@ -138,7 +138,7 @@ static int NumArg (const char* Arg, unsi
 static void SetUseChgInfo (CodeEntry* E, const OPCDesc* D)
 /* Set the Use and Chg in E */
 {
-    const ZPInfo* Info;
+    ZPInfo Info;
 
     /* If this is a subroutine call, or a jump to an external function,
      * lookup the information about this function and use it. The jump itself
@@ -173,20 +173,20 @@ static void SetUseChgInfo (CodeEntry* E,
 	    case AM65_ABSX:
 	    case AM65_ABSY:
 	        Info = GetZPInfo (E->Arg);
-	        if (Info && Info->ByteUse != REG_NONE) {
+	        if (Info.Name && Info.ByteUse != REG_NONE) {
 		    if (E->OPC == OP65_ASL || E->OPC == OP65_DEC ||
 		       	E->OPC == OP65_INC || E->OPC == OP65_LSR ||
 		       	E->OPC == OP65_ROL || E->OPC == OP65_ROR ||
 		       	E->OPC == OP65_TRB || E->OPC == OP65_TSB) {
 		       	/* The zp loc is both, input and output */
-		       	E->Chg |= Info->ByteUse;
-		       	E->Use |= Info->ByteUse;
+		       	E->Chg |= Info.ByteUse;
+		       	E->Use |= Info.ByteUse;
 		    } else if ((E->Info & OF_STORE) != 0) {
 		       	/* Just output */
-		       	E->Chg |= Info->ByteUse;
+		       	E->Chg |= Info.ByteUse;
 		    } else {
 		       	/* Input only */
-		       	E->Use |= Info->ByteUse;
+		       	E->Use |= Info.ByteUse;
 		    }
 		}
 	        break;
@@ -195,9 +195,9 @@ static void SetUseChgInfo (CodeEntry* E,
 	    case AM65_ZP_INDY:
 	    case AM65_ZP_IND:
 	        Info = GetZPInfo (E->Arg);
-	        if (Info && Info->ByteUse != REG_NONE) {
+	        if (Info.Name && Info.ByteUse != REG_NONE) {
 		    /* These addressing modes will never change the zp loc */
-		    E->Use |= Info->WordUse;
+		    E->Use |= Info.WordUse;
 		}
 	        break;
 
diff -b -up cc65.org\codegen.c cc65\codegen.c
--- cc65.org\codegen.c	Sun Nov 20 08:52:22 2005
+++ cc65\codegen.c	Sun Jul 15 14:30:16 2007
@@ -58,7 +58,7 @@
 #include "textseg.h"
 #include "util.h"
 #include "codegen.h"
-
+#include "function.h"
 
 
 /*****************************************************************************/
@@ -70,7 +70,7 @@
 static void typeerror (unsigned type)
 /* Print an error message about an invalid operand type */
 {
-    Internal ("Invalid type in CF flags: %04X, type = %u", type, type & CF_TYPE);
+    Internal ("Invalid type in CF flags: %08X, type = %u", type, type & CF_TYPE);
 }
 
 
@@ -118,11 +118,19 @@ static const char* GetLabelName (unsigne
 
         case CF_REGVAR:
             /* Variable in register bank */
+			if (GetLeafFlag (F_GetFuncDesc (CurrentFunc)))
+	            xsprintf (Buf, sizeof (Buf), "leafregbank+%u", (unsigned)((Label+Offs) & 0xFFFF));
+			else
             xsprintf (Buf, sizeof (Buf), "regbank+%u", (unsigned)((Label+Offs) & 0xFFFF));
             break;
 
+        case CF_LEAFREGVAR:
+            /* Variable in leaf register bank */
+            xsprintf (Buf, sizeof (Buf), "leafregbank+%u", (unsigned)((Label+Offs) & 0xFFFF));
+            break;
+
         default:
-            Internal ("Invalid address flags: %04X", Flags);
+            Internal ("Invalid address flags: %08X", Flags);
     }
 
     /* Return a pointer to the static buffer */
@@ -180,6 +188,10 @@ void g_preamble (void)
     /* Import the stack pointer for direct auto variable access */
     AddTextLine ("\t.importzp\tsp, sreg, regsave, regbank, tmp1, ptr1, ptr2");
 
+	/* import leafregbank if leaf optimization enabled */
+	if (LeafOptimization)
+	    AddTextLine ("\t.importzp\tleafregbank");
+
     /* Define long branch macros */
     AddTextLine ("\t.macpack\tlongbranch");
 }
@@ -502,6 +514,75 @@ void g_leave (void)
 
 
 
+static void g_internal_load_regvars (int StackOffs, int RegOffs, unsigned Bytes, char* RegBank)
+/* Load a register variable from a location on the stack */
+{
+    /* Calculate the actual stack offset and check it */
+    StackOffs -= StackPtr;
+    CheckLocalOffs (StackOffs);
+
+    /* Generate code */
+    if (Bytes == 1) {
+
+        ldyconst (StackOffs);
+        AddCodeLine ("lda (sp),y");
+        AddCodeLine ("sta %s+%d", RegBank, RegOffs);
+
+    } else if (Bytes == 2) {
+
+        ldyconst (StackOffs);
+        AddCodeLine ("lda (sp),y");
+        AddCodeLine ("sta %s+%d", RegBank, RegOffs);
+        AddCodeLine ("iny");
+        AddCodeLine ("lda (sp),y");
+        AddCodeLine ("sta %s+%d", RegBank, RegOffs+1);
+
+    } else if (Bytes == 4) {
+
+        ldyconst (StackOffs);
+        AddCodeLine ("lda (sp),y");
+        AddCodeLine ("sta %s+%d", RegBank, RegOffs);
+        AddCodeLine ("iny");
+        AddCodeLine ("lda (sp),y");
+        AddCodeLine ("sta %s+%d", RegBank, RegOffs+1);
+        AddCodeLine ("iny");
+        AddCodeLine ("lda (sp),y");
+        AddCodeLine ("sta %s+%d", RegBank, RegOffs+2);
+        AddCodeLine ("iny");
+        AddCodeLine ("lda (sp),y");
+        AddCodeLine ("sta %s+%d", RegBank, RegOffs+3);
+
+	} else {
+
+		Internal ("g_internal_load_regvars: %d bytes not supported", Bytes);
+
+/*
+        ldyconst (StackOffs);
+        ldxconst (RegOffs);
+        ldaconst (Bytes);
+        AddCodeLine ("jsr regload");
+*/
+    }
+}
+
+
+
+void g_load_leafregvars (int StackOffs, int RegOffs, unsigned Bytes)
+/* Load a leaf register variable from a location on the stack */
+{
+	g_internal_load_regvars (StackOffs, RegOffs, Bytes, "leafregbank");
+}
+
+
+
+void g_load_regvars (int StackOffs, int RegOffs, unsigned Bytes)
+/* Load a register variable from a location on the stack */
+{
+	g_internal_load_regvars (StackOffs, RegOffs, Bytes, "regbank");
+}
+
+
+
 void g_swap_regvars (int StackOffs, int RegOffs, unsigned Bytes)
 /* Swap a register variable with a location on the stack */
 {
@@ -519,8 +600,8 @@ void g_swap_regvars (int StackOffs, int 
         } else {
             ldyconst (StackOffs);
             AddCodeLine ("lda (sp),y");
-            AddCodeLine ("ldx regbank%+d", RegOffs);
-            AddCodeLine ("sta regbank%+d", RegOffs);
+            AddCodeLine ("ldx regbank+%d", RegOffs);
+            AddCodeLine ("sta regbank+%d", RegOffs);
             AddCodeLine ("txa");
             AddCodeLine ("sta (sp),y");
         }
@@ -542,19 +623,46 @@ void g_swap_regvars (int StackOffs, int 
 
 
 
+void g_load_regvars_static (unsigned Label, int RegOffs, unsigned Bytes)
+/* Restore a register variable from a static location */
+{
+    /* Generate code */
+    if (Bytes == 1 || Bytes == 2 || Bytes == 4) {
+        AddCodeLine ("lda %s", LocalLabelName (Label));
+        AddCodeLine ("sta regbank+%d", RegOffs);
+
+		if (Bytes == 2 || Bytes == 4) {
+			AddCodeLine ("lda %s+1", LocalLabelName (Label));
+			AddCodeLine ("sta regbank+%d", RegOffs+1);
+
+			if (Bytes == 4) {
+				AddCodeLine ("lda %s+2", LocalLabelName (Label));
+				AddCodeLine ("sta regbank+%d", RegOffs+2);
+				AddCodeLine ("lda %s+3", LocalLabelName (Label));
+				AddCodeLine ("sta regbank+%d", RegOffs+3);
+			}
+		}
+	} else {
+
+		Internal ("g_load_regvars_static: %d bytes not implemented", (int)Bytes);
+    }
+}
+
+
+
 void g_save_regvars (int RegOffs, unsigned Bytes)
 /* Save register variables */
 {
     /* Don't loop for up to two bytes */
     if (Bytes == 1) {
 
-        AddCodeLine ("lda regbank%+d", RegOffs);
+        AddCodeLine ("lda regbank+%d", RegOffs);
         AddCodeLine ("jsr pusha");
 
     } else if (Bytes == 2) {
 
-        AddCodeLine ("lda regbank%+d", RegOffs);
-        AddCodeLine ("ldx regbank%+d", RegOffs+1);
+        AddCodeLine ("lda regbank+%d", RegOffs);
+        AddCodeLine ("ldx regbank+%d", RegOffs+1);
         AddCodeLine ("jsr pushax");
 
     } else {
@@ -565,7 +673,7 @@ void g_save_regvars (int RegOffs, unsign
         ldyconst (Bytes - 1);
         ldxconst (Bytes);
         g_defcodelabel (Label);
-        AddCodeLine ("lda regbank%+d,x", RegOffs-1);
+        AddCodeLine ("lda regbank+%d,x", RegOffs-1);
         AddCodeLine ("sta (sp),y");
         AddCodeLine ("dey");
         AddCodeLine ("dex");
@@ -579,6 +687,36 @@ void g_save_regvars (int RegOffs, unsign
 
 
 
+void g_save_regvars_hardwarestack (int RegOffs, unsigned Bytes)
+/* Save register variables on hardware stack */
+{
+	unsigned i;
+
+	PRECONDITION (Bytes > 0);
+
+	for (i=Bytes; i > 0; i--)
+	{
+        AddCodeLine ("lda regbank+%d", RegOffs+i-1);
+        AddCodeLine ("pha");
+	}
+}
+
+
+
+void g_restore_regvars_hardwarestack (int RegOffs, unsigned Bytes)
+/* Restore register variables from hardware stack */
+{
+	unsigned i;
+
+	for (i=0; i < Bytes; i++)
+	{
+        AddCodeLine ("pla");
+        AddCodeLine ("sta regbank+%d", RegOffs+i);
+	}
+}
+
+
+
 void g_restore_regvars (int StackOffs, int RegOffs, unsigned Bytes)
 /* Restore register variables */
 {
@@ -591,28 +729,28 @@ void g_restore_regvars (int StackOffs, i
 
         ldyconst (StackOffs);
         AddCodeLine ("lda (sp),y");
-        AddCodeLine ("sta regbank%+d", RegOffs);
+        AddCodeLine ("sta regbank+%d", RegOffs);
 
     } else if (Bytes == 2) {
 
         ldyconst (StackOffs);
         AddCodeLine ("lda (sp),y");
-        AddCodeLine ("sta regbank%+d", RegOffs);
+        AddCodeLine ("sta regbank+%d", RegOffs);
         AddCodeLine ("iny");
         AddCodeLine ("lda (sp),y");
-        AddCodeLine ("sta regbank%+d", RegOffs+1);
+        AddCodeLine ("sta regbank+%d", RegOffs+1);
 
     } else if (Bytes == 3 && IS_Get (&CodeSizeFactor) >= 133) {
 
         ldyconst (StackOffs);
         AddCodeLine ("lda (sp),y");
-        AddCodeLine ("sta regbank%+d", RegOffs);
+        AddCodeLine ("sta regbank+%d", RegOffs);
         AddCodeLine ("iny");
         AddCodeLine ("lda (sp),y");
-        AddCodeLine ("sta regbank%+d", RegOffs+1);
+        AddCodeLine ("sta regbank+%d", RegOffs+1);
         AddCodeLine ("iny");
         AddCodeLine ("lda (sp),y");
-        AddCodeLine ("sta regbank%+d", RegOffs+2);
+        AddCodeLine ("sta regbank+%d", RegOffs+2);
 
     } else if (StackOffs <= RegOffs) {
 
@@ -624,7 +762,7 @@ void g_restore_regvars (int StackOffs, i
         ldyconst (StackOffs);
         g_defcodelabel (Label);
         AddCodeLine ("lda (sp),y");
-        AddCodeLine ("sta regbank%+d,y", RegOffs - StackOffs);
+        AddCodeLine ("sta regbank+%d,y", RegOffs - StackOffs);
         AddCodeLine ("iny");
         AddCodeLine ("cpy #$%02X", StackOffs + Bytes);
         AddCodeLine ("bne %s", LocalLabelName (Label));
@@ -640,7 +778,7 @@ void g_restore_regvars (int StackOffs, i
         ldxconst (Bytes - 1);
         g_defcodelabel (Label);
         AddCodeLine ("lda (sp),y");
-        AddCodeLine ("sta regbank%+d,x", RegOffs);
+        AddCodeLine ("sta regbank+%d,x", RegOffs);
         AddCodeLine ("dey");
         AddCodeLine ("dex");
         AddCodeLine ("bpl %s", LocalLabelName (Label));
@@ -1030,6 +1168,41 @@ void g_putstatic (unsigned flags, unsign
 
 
 
+void g_putstatic_y (unsigned flags, unsigned long label, long offs)
+/* Store the primary register (but Y instead of A) into the specified static memory cell */
+{
+    /* Create the correct label name */
+    const char* lbuf = GetLabelName (flags, label, offs);
+
+    /* Check the size and generate the correct store operation */
+    switch (flags & CF_TYPE) {
+
+        case CF_CHAR:
+            AddCodeLine ("sty %s", lbuf);
+            break;
+
+        case CF_INT:
+            AddCodeLine ("sty %s", lbuf);
+            AddCodeLine ("stx %s+1", lbuf);
+            break;
+
+        case CF_LONG:
+            AddCodeLine ("sty %s", lbuf);
+            AddCodeLine ("stx %s+1", lbuf);
+            AddCodeLine ("ldy sreg");
+            AddCodeLine ("sty %s+2", lbuf);
+            AddCodeLine ("ldy sreg+1");
+            AddCodeLine ("sty %s+3", lbuf);
+            break;
+
+        default:
+            typeerror (flags);
+
+    }
+}
+
+
+
 void g_putlocal (unsigned Flags, int Offs, long Val)
 /* Put data into local object. */
 {
@@ -2165,6 +2338,64 @@ void g_addaddr_static (unsigned flags, u
 
 
 
+void g_save_ax (unsigned flags)
+/* Push A or A&X on hardware stack */
+{
+    /* Check the size and determine operation */
+    switch (flags & CF_TYPE) {
+
+        case CF_CHAR:
+            AddCodeLine ("pha");
+            break;
+
+        case CF_INT:
+        case CF_LONG:
+			/* pha/txa/pha is one byte shorter but 2 cycles slower. Hmm... */
+			AddCodeLine ("pha");
+			AddCodeLine ("txa");
+			AddCodeLine ("pha");
+#if 0
+            AddCodeLine ("sta regsave");
+            AddCodeLine ("stx regsave+1");
+#endif
+            break;
+
+        default:
+            typeerror (flags);
+    }
+}
+
+
+
+void g_restore_ax (unsigned flags)
+/* Pop A or A&X from hardware stack */
+{
+    /* Check the size and determine operation */
+    switch (flags & CF_TYPE) {
+
+        case CF_CHAR:
+            AddCodeLine ("pla");
+            break;
+
+        case CF_INT:
+        case CF_LONG:
+			/* pla/tax/pla is one byte shorter but 2 cycles slower. Hmm... */
+			AddCodeLine ("pla");
+			AddCodeLine ("tax");
+			AddCodeLine ("pla");
+#if 0
+            AddCodeLine ("lda regsave");
+            AddCodeLine ("ldx regsave+1");
+#endif
+            break;
+
+        default:
+            typeerror (flags);
+    }
+}
+
+
+
 void g_save (unsigned flags)
 /* Copy primary register to hold register. */
 {
@@ -2344,6 +2575,38 @@ void g_test (unsigned flags)
             typeerror (flags);
 
     }
+}
+
+
+
+void g_store (unsigned flags, unsigned long val, unsigned Label)
+/* Store the primary register or a constant value */
+{
+    if (flags & CF_CONST && (flags & CF_TYPE) != CF_LONG) {
+
+        /* We have a constant 8 or 16 bit value */
+        if ((flags & CF_TYPE) == CF_CHAR && (flags & CF_FORCECHAR)) {
+
+            /* Handle as 8 bit value */
+            ldaconst (val);
+
+        } else {
+
+            /* Handle as 16 bit value */
+            g_getimmed (flags, val, 0);
+        }
+
+    } else {
+
+        /* Value is not 16 bit or not constant */
+        if (flags & CF_CONST) {
+            /* Constant 32 bit value, load into eax */
+            g_getimmed (flags, val, 0);
+        }
+    }
+
+	/* Store the primary register */
+	g_putstatic (flags, Label, 0);
 }
 
 
diff -b -up cc65.org\codegen.h cc65\codegen.h
--- cc65.org\codegen.h	Sat Jun 05 07:35:54 2004
+++ cc65\codegen.h	Sun Jul 15 14:13:06 2007
@@ -76,12 +76,13 @@
 #define CF_REG		0x0800	/* Value is in primary register */
 
 /* Type of static address */
-#define CF_ADDRMASK    	0xF000 	/* Type of address */
+#define CF_ADDRMASK    	0x1F000 	/* Type of address */
 #define CF_STATIC	0x0000	/* Static local */
 #define CF_EXTERNAL	0x1000	/* Static external */
 #define CF_ABSOLUTE	0x2000	/* Numeric absolute address */
 #define CF_LOCAL       	0x4000 	/* Auto variable */
 #define CF_REGVAR	0x8000	/* Register variable */
+#define CF_LEAFREGVAR	0x10000	/* Leaf register variable */
 
 
 
@@ -232,6 +233,8 @@ void g_leave (void);
 /*****************************************************************************/
 
 
+void g_load_leafregvars (int StackOffs, int RegOffs, unsigned Bytes);
+/* Load a register variable from a location on the stack */
 
 void g_swap_regvars (int StackOffs, int RegOffs, unsigned Bytes);
 /* Swap a register variable with a location on the stack */
@@ -242,6 +245,17 @@ void g_save_regvars (int RegOffs, unsign
 void g_restore_regvars (int StackOffs, int RegOffs, unsigned Bytes);
 /* Restore register variables */
 
+void g_load_regvars_static (unsigned Label, int RegOffs, unsigned Bytes);
+/* Load a register variable from a static location */
+
+void g_save_regvars_hardwarestack (int RegOffs, unsigned Bytes);
+/* Save register variables on hardware stack */
+
+void g_restore_regvars_hardwarestack (int RegOffs, unsigned Bytes);
+/* Restore register variables from hardware stack */
+
+void g_load_regvars (int StackOffs, int RegOffs, unsigned Bytes);
+/* Load a register variable from a location on the stack */
 
 
 /*****************************************************************************/
@@ -283,6 +297,9 @@ void g_leavariadic (int Offs);
 void g_putstatic (unsigned flags, unsigned long label, long offs);
 /* Store the primary register into the specified static memory cell */
 
+void g_putstatic_y (unsigned flags, unsigned long label, long offs);
+/* Store the primary register (but Y instead of A) into the specified static memory cell */
+
 void g_putlocal (unsigned Flags, int Offs, long Val);
 /* Put data into local object. */
 
@@ -354,6 +371,11 @@ void g_addaddr_static (unsigned flags, u
 /*****************************************************************************/
 
 
+void g_save_ax (unsigned flags);
+/* Push A or A&X on hardware stack */
+
+void g_restore_ax (unsigned flags);
+/* Pop A or A&X from hardware stack */
 
 void g_save (unsigned flags);
 /* Copy primary register to hold register. */
@@ -368,6 +390,9 @@ void g_cmp (unsigned flags, unsigned lon
 
 void g_test (unsigned flags);
 /* Test the value in the primary and set the condition codes */
+
+void g_store (unsigned flags, unsigned long val, unsigned Label);
+/* Store the primary register or a constant value */
 
 void g_push (unsigned flags, unsigned long val);
 /* Push the primary register or a constant value onto the stack */
diff -b -up cc65.org\codeinfo.c cc65\codeinfo.c
--- cc65.org\codeinfo.c	Sun Apr 16 17:35:24 2006
+++ cc65\codeinfo.c	Sat Jun 30 22:49:22 2007
@@ -49,6 +49,7 @@
 #include "reginfo.h"
 #include "symtab.h"
 #include "codeinfo.h"
+#include "ident.h"
 
 
 
@@ -284,7 +285,9 @@ static const FuncInfo FuncInfoTable[] = 
 #define FuncInfoCount	(sizeof(FuncInfoTable) / sizeof(FuncInfoTable[0]))
 
 /* Table with names of zero page locations used by the compiler */
+/* Must be sorted! Binary search used. */
 static const ZPInfo ZPInfoTable[] = {
+    {  11, "leafregbank",REG_NONE,    	REG_NONE        },
     {  	0, "ptr1",      REG_PTR1_LO, 	REG_PTR1        },
     {   0, "ptr1+1",    REG_PTR1_HI, 	REG_PTR1        },
     {  	0, "ptr2",      REG_PTR2_LO, 	REG_PTR2        },
@@ -442,14 +445,87 @@ static int CompareZPInfo (const void* Na
 
 
 
-const ZPInfo* GetZPInfo (const char* Name)
-/* If the given name is a zero page symbol, return a pointer to the info
- * struct for this symbol, otherwise return NULL.
+static SymEntry* FindZPGlobal (const char *Name)
+/* Accepts an assembly name and return a zero page global symbol, if available */
+{
+	if (Name[0] == '_') {
+
+		char noplus[IDENTSIZE+1];
+		unsigned i;
+		SymEntry* Sym;
+
+		Name++;
+
+		/* Strip off everything after '+' */
+
+		for (i=0; i < IDENTSIZE; i++) {
+			noplus[i] = Name[i];
+			if (Name[i] == 0 || Name[i] == '+')
+				break;
+		}
+
+		if (Name[i] == '+' && !IsDigit(Name[i+1]))
+			return NULL;
+
+		noplus[i] = 0;
+
+		Sym = FindGlobalSym (noplus);
+
+		if (Sym && Sym->Flags & SC_ZEROPAGE)
+			return Sym;
+	}
+
+	return NULL;
+}
+
+
+
+ZPInfo GetZPInfo (const char* Name)
+/* If the given name is a zero page symbol, return the info
+ * struct for this symbol. If not found, ZPInfo.Name will be NULL.
  */
 {
     /* Search for the zp location in the list */
-    return bsearch (Name, ZPInfoTable, ZPInfoCount,
+	ZPInfo* pzp = bsearch (Name, ZPInfoTable, ZPInfoCount,
 	       	    sizeof(ZPInfo), CompareZPInfo);
+
+	if (pzp) {
+		return *pzp;
+	} else {
+		/* Check global symbols */
+
+		ZPInfo zp;
+		SymEntry* Sym;
+
+		zp.ByteUse = REG_NONE;
+		zp.WordUse = REG_NONE;
+
+		if (Sym = FindZPGlobal (Name)) {
+			zp.Len = strlen (Sym->AsmName);
+			zp.Name = Sym->AsmName;
+		} else {
+			zp.Len = 0;
+			zp.Name = 0;
+		}
+
+		return zp;
+	}
+}
+
+
+
+unsigned IsZeroPage (const char* Name)
+/* Return 1 if name is "regbank+", "leafregbank+", or a zero page global */
+{
+	if ((strncmp (Name, "regbank+", 8) == 0 || strncmp (Name, "leafregbank+", 12) == 0) &&
+		(IsDigit (Name[8]) || IsDigit (Name[12])))
+		return 1;
+
+	/* Check global symbols */
+	if (FindZPGlobal (Name))
+		return 1;
+
+	return 0;
 }
 
 
diff -b -up cc65.org\codeinfo.h cc65\codeinfo.h
--- cc65.org\codeinfo.h	Thu Oct 17 17:37:02 2002
+++ cc65\codeinfo.h	Sat Jun 30 20:33:24 2007
@@ -96,7 +96,7 @@ struct RegContents;
 typedef struct ZPInfo ZPInfo;
 struct ZPInfo {
     unsigned char  Len;		/* Length of the following string */
-    char           Name[11];    /* Name of zero page symbol */
+    char*          Name;    /* Name of zero page symbol */
     unsigned short ByteUse;     /* Register info for this symbol */
     unsigned short WordUse;     /* Register info for 16 bit access */
 };
@@ -132,10 +132,13 @@ void GetFuncInfo (const char* Name, unsi
  * load all registers.
  */
 
-const ZPInfo* GetZPInfo (const char* Name);
-/* If the given name is a zero page symbol, return a pointer to the info
- * struct for this symbol, otherwise return NULL.
+ZPInfo GetZPInfo (const char* Name);
+/* If the given name is a zero page symbol, return the info
+ * struct for this symbol. ZPInfo.Name will be NULL if not found.
  */
+
+unsigned IsZeroPage (const char* Name);
+/* Return 1 if name is "regbank+", "leafregbank+", or a zero page global */
 
 unsigned GetRegInfo (struct CodeSeg* S, unsigned Index, unsigned Wanted);
 /* Determine register usage information for the instructions starting at the
diff -b -up cc65.org\codeopt.c cc65\codeopt.c
--- cc65.org\codeopt.c	Mon Apr 24 19:45:44 2006
+++ cc65\codeopt.c	Sat Jun 30 20:31:36 2007
@@ -511,8 +511,11 @@ static unsigned OptPtrStore1 (CodeSeg* S
 
             /* Get the preceeding two instructions and check them. We check
              * for:
-             *          lda     regbank+n
-             *          ldx     regbank+n+1
+             *          lda     [leaf]regbank+n
+             *          ldx     [leaf]regbank+n+1
+			 * or
+             *          lda     _zpglobal
+             *          ldx     _zpglobal+1
              */
             if (I > 1) {
                 CodeEntry* P[2];
@@ -523,7 +526,7 @@ static unsigned OptPtrStore1 (CodeSeg* S
                     P[1]->OPC == OP65_LDX &&
                     P[1]->AM  == AM65_ZP  &&
                     !CE_HasLabel (P[1])   &&
-                    strncmp (P[0]->Arg, "regbank+", 8) == 0) {
+                    IsZeroPage (P[0]->Arg)) {
 
                     unsigned Len = strlen (P[0]->Arg);
 
@@ -1228,7 +1231,7 @@ static unsigned OptPtrLoad6 (CodeSeg* S)
      	/* Check for the sequence */
        	if (L[0]->OPC == OP65_LDA                               &&
             L[0]->AM == AM65_ZP                                 &&
-            strncmp (L[0]->Arg, "regbank+", 8) == 0             &&
+            IsZeroPage (L[0]->Arg)                              &&
             (Len = strlen (L[0]->Arg)) > 0                      &&
        	    CS_GetEntries (S, L+1, I+1, 14)    	                &&
             !CS_RangeHasLabel (S, I+1, 7)                       &&
diff -b -up cc65.org\codeseg.c cc65\codeseg.c
--- cc65.org\codeseg.c	Sun Feb 19 08:29:38 2006
+++ cc65\codeseg.c	Sat Jun 30 09:23:10 2007
@@ -373,7 +373,7 @@ static CodeEntry* ParseInsn (CodeSeg* S,
 	      	if ((OPC->Info & OF_BRA) != 0) {
 		    /* Branch */
 		    AM = AM65_BRA;
-		} else if (GetZPInfo(Arg) != 0) {
+		} else if (GetZPInfo(Arg).Name != 0) {
 		    AM = AM65_ZP;
 		} else {
 		    AM = AM65_ABS;
@@ -388,7 +388,7 @@ static CodeEntry* ParseInsn (CodeSeg* S,
 	      	    Reg = toupper (*L);
 		    L = SkipSpace (L+1);
 		    if (Reg == 'X') {
-			if (GetZPInfo(Arg) != 0) {
+			if (GetZPInfo(Arg).Name != 0) {
 			    AM = AM65_ZPX;
 			} else {
 			    AM = AM65_ABSX;
diff -b -up cc65.org\compile.c cc65\compile.c
--- cc65.org\compile.c	Sun Jan 09 14:03:56 2005
+++ cc65\compile.c	Wed Jul 04 13:45:50 2007
@@ -59,10 +59,21 @@
 #include "preproc.h"
 #include "standard.h"
 #include "symtab.h"
+#include "macrotab.h"
+#include "tgttrans.h"
+#include "stackptr.h"
+#include "funcremember.h"
 
 
 
 /*****************************************************************************/
+/*		    	      	     Data				     */
+/*****************************************************************************/
+
+unsigned char PassCount = 1;			/* pass (1 or 2) */
+unsigned char SuppressWarnings = 0;		/* disable warnings independent of user options */
+
+/*****************************************************************************/
 /*		    	      	     Code				     */
 /*****************************************************************************/
 
@@ -271,8 +282,8 @@ static void Parse (void)
 
 
 
-void Compile (const char* FileName)
-/* Top level compile routine. Will setup things and call the parser. */
+static void CompilePass (const char* FileName)
+/* Pass compile routine. Will setup things and call the parser. */
 {
     char        DateStr[32];
     char        TimeStr[32];
@@ -323,12 +334,18 @@ void Compile (const char* FileName)
     DefineTextMacro ("__DATE__", DateStr);
     DefineTextMacro ("__TIME__", TimeStr);
 
+	/* Initialize label generation */
+	InitLocalLabel ();
+
+	/* Initialize stack pointer */
+	StackPtr = 0;
+
+	/* initialize segments */
+	InitSegments ();
+
     /* Initialize the literal pool */
     InitLiteralPool ();
 
-    /* Create the base lexical level */
-    EnterGlobalLevel ();
-
     /* Generate the code generator preamble */
     g_preamble ();
 
@@ -351,6 +368,56 @@ void Compile (const char* FileName)
 
         /* Ok, start the ball rolling... */
         Parse ();
+    }
+}
+
+
+
+void Compile (const char* FileName)
+/* Top level compile routine. Calls CompilePass to do the work for each pass. */
+{
+	PassCount = 1;
+
+	/* save global state that should be the same for both passes */
+	SnapshotGlobal ();
+	SnapshotMacros ();
+	SnapshotSegNames ();
+
+    /* Create the base lexical level */
+    EnterGlobalLevel ();
+
+	/* pass 1 */
+	CompilePass (FileName);
+
+	if (!PreprocessOnly)
+	{
+		if (ErrorCount == 0 && (LeafOptimization || StaticParams || AutoFastcall))
+		{
+			PassCount = 2;
+
+			/* Leave the main lexical level */
+			LeaveGlobalLevel ();
+
+			/* restore global state for pass 2 */
+			RestoreGlobal ();
+			RestoreMacros ();
+			RestoreSegNames ();
+
+			/* re-init translation table in case a pragma modified it during pass 1 */
+			TgtTranslateInit ();
+
+			/* suppress warnings in pass 2 */
+			SuppressWarnings = 1;
+
+			/* Create the base lexical level */
+			EnterGlobalLevel ();
+
+			/* pass 2 */
+			CompilePass (FileName);
+
+			/* un-suppress warnings in case the output code wants to warn about something */
+			SuppressWarnings = 0;
+		}
 
         /* Dump the literal pool. */
         DumpLiteralPool ();
@@ -361,8 +428,9 @@ void Compile (const char* FileName)
         if (Debug) {
             PrintLiteralPoolStats (stdout);
             PrintMacroStats (stdout);
+			PrintFuncRememberStats (stdout);
+			PrintGlobalSymTables (stdout);
         }
-
     }
 
     /* Leave the main lexical level */
@@ -371,7 +439,3 @@ void Compile (const char* FileName)
     /* Print an error report */
     ErrorReport ();
 }
-
-
-
-
diff -b -up cc65.org\compile.h cc65\compile.h
--- cc65.org\compile.h	Tue May 22 16:03:26 2001
+++ cc65\compile.h	Tue Jun 26 22:49:22 2007
@@ -37,6 +37,14 @@
 #define COMPILE_H
 
 
+/*****************************************************************************/
+/*		    	      	     Data				     */
+/*****************************************************************************/
+
+extern unsigned char PassCount;				/* pass (1 or 2) */
+extern unsigned char SuppressWarnings;		/* disable warnings independent of user options */
+extern unsigned char StickyStaticLocals;	/* set if static locals enabled at any point */
+
 
 /*****************************************************************************/
 /*		    		     Code				     */
diff -b -up cc65.org\coptstop.c cc65\coptstop.c
--- cc65.org\coptstop.c	Sun Apr 16 16:32:10 2006
+++ cc65\coptstop.c	Sat Jun 30 20:33:26 2007
@@ -42,7 +42,8 @@
 #include "codeent.h"
 #include "codeinfo.h"
 #include "coptstop.h"
-
+#include "ident.h"
+#include "symtab.h"
 
 
 /*****************************************************************************/
@@ -335,17 +336,17 @@ static int IsRegVar (StackOpData* D)
         (P = D->PrevEntry) != 0                          &&
         P->OPC == OP65_LDX                               &&
         P->AM == AM65_ZP                                 &&
-        strncmp (P->Arg, "regbank+", 7) == 0             &&
-        IsDigit (P->Arg[8])                              &&
+        IsZeroPage (P->Arg)                              &&
         (P = CS_GetEntry (D->Code, D->PushIndex-2)) != 0 &&
         P->OPC == OP65_LDA                               &&
         P->AM == AM65_ZP                                 &&
-        strncmp (P->Arg, "regbank+", 7) == 0             &&
-        IsDigit (P->Arg[8])) {
+        IsZeroPage (P->Arg)) {
+
         /* Ok, it loads the register variable */
         D->ZPHi = D->PrevEntry->Arg;
         D->ZPLo = P->Arg;
         return 1;
+
     } else {
         return 0;
     }
diff -b -up cc65.org\datatype.c cc65\datatype.c
--- cc65.org\datatype.c	Sun Feb 19 08:29:38 2006
+++ cc65\datatype.c	Mon Jul 02 22:06:10 2007
@@ -46,7 +46,9 @@
 #include "funcdesc.h"
 #include "global.h"
 #include "symtab.h"
-
+#include "debugflag.h"
+#include "funcremember.h"
+#include "compile.h"
 
 
 /*****************************************************************************/
@@ -206,6 +208,11 @@ Type* PointerTo (const Type* T)
     /* Allocate the new type string */
     Type* P = TypeAlloc	(Size + 1);
 
+	if (IsTypeFunc (T) && PassCount == 1) {
+		/* mark function as having had address taken - this info is needed for some optimizations */
+		SetFuncRememberFlags (GetFuncDesc (T)->Pass2, FR_ADDRESSTAKEN);
+	}
+
     /* Create the return type... */
     P[0].C = T_PTR;
     memcpy (P+1, T, Size * sizeof (Type));
@@ -349,6 +356,17 @@ void PrintFuncSig (FILE* F, const char* 
 
     /* End of parameter list */
     fprintf (F, ")");
+
+	if (Debug) {
+		if (GetLeafFlag (D))
+			fprintf (F, " [leaf]");
+		if (D->Pass2->Flags & FR_ADDRESSTAKEN)
+			fprintf (F, " [address taken]");
+		if (D->Pass2->Flags & FR_EXTERN)
+			fprintf (F, " [extern]");
+		if (D->Pass2->Flags & FR_VARIADIC)
+			fprintf (F, " [variadic]");
+	}
 }
 
 
Common subdirectories: cc65.org\Debug and cc65\Debug
diff -b -up cc65.org\declare.c cc65\declare.c
--- cc65.org\declare.c	Sun Mar 18 14:26:00 2007
+++ cc65\declare.c	Mon Jul 09 09:29:18 2007
@@ -59,6 +59,7 @@
 #include "standard.h"
 #include "symtab.h"
 #include "typeconv.h"
+#include "compile.h"
 
 
 
@@ -852,7 +853,6 @@ static void ParseAnsiParamList (FuncDesc
 static FuncDesc* ParseFuncDecl (const DeclSpec* Spec)
 /* Parse the argument list of a function. */
 {
-    unsigned Offs;
     SymEntry* Sym;
 
     /* Create a new function descriptor */
@@ -910,22 +910,7 @@ static FuncDesc* ParseFuncDecl (const De
      */
     F->LastParam = GetSymTab()->SymTail;
 
-    /* Assign offsets. If the function has a variable parameter list,
-     * there's one additional byte (the arg size).
-     */
-    Offs = (F->Flags & FD_VARIADIC)? 1 : 0;
-    Sym = F->LastParam;
-    while (Sym) {
-	unsigned Size = CheckedSizeOf (Sym->Type);
-        if (SymIsRegVar (Sym)) {
-            Sym->V.R.SaveOffs = Offs;
-        } else {
-     	    Sym->V.Offs = Offs;
-        }
-       	Offs += Size;
-	F->ParamSize += Size;
-     	Sym = Sym->PrevSym;
-    }
+	AssignStackOffsetsToParams (F);
 
     /* Add the default address size for the function */
     if (CodeAddrSize == ADDR_SIZE_FAR) {
@@ -999,6 +984,9 @@ static void ApplyFunctionModifiers (Type
 
     /* Add the new modifers */
     F->Flags |= Flags;
+
+	/* Re-compute stack offsets in case FD_FASTCALL was set */
+	AssignStackOffsetsToParams (F);
 }
 
 
@@ -1292,6 +1280,7 @@ static void DefineData (ExprDesc* Expr)
        	     * allowed.
        	     */
        	    if (IS_Get (&AllowRegVarAddr) == 0) {
+				if (PassCount == 1)
        	      	Error ("Cannot take the address of a register variable");
        	    }
             g_defdata (CF_REGVAR, Expr->Name, Expr->IVal);
diff -b -up cc65.org\error.c cc65\error.c
--- cc65.org\error.c	Sun Nov 20 17:51:50 2005
+++ cc65\error.c	Mon Jun 25 07:42:38 2007
@@ -47,7 +47,7 @@
 #include "scanner.h"
 #include "stmt.h"
 #include "error.h"
-
+#include "compile.h"
 
 
 /*****************************************************************************/
@@ -71,6 +71,7 @@ unsigned WarningCount	= 0;
 static void IntWarning (const char* Filename, unsigned LineNo, const char* Msg, va_list ap)
 /* Print warning message - internal function. */
 {
+	if (!SuppressWarnings) {
     if (!IS_Get (&WarnDisable)) {
        	fprintf (stderr, "%s(%u): Warning: ", Filename, LineNo);
      	vfprintf (stderr, Msg, ap);
@@ -81,6 +82,7 @@ static void IntWarning (const char* File
         }
      	++WarningCount;
     }
+	}
 }
 
 
diff -b -up cc65.org\expr.c cc65\expr.c
--- cc65.org\expr.c	Sun Mar 18 15:15:36 2007
+++ cc65\expr.c	Mon Jul 09 09:31:22 2007
@@ -36,7 +36,8 @@
 #include "typecmp.h"
 #include "typeconv.h"
 #include "expr.h"
-
+#include "compile.h"
+#include "funcremember.h"
 
 
 /*****************************************************************************/
@@ -285,6 +286,119 @@ void PushAddr (const ExprDesc* Expr)
 
 
 
+static void FunctionStaticParamList (FuncDesc* Func)
+/* Parse a function parameter list and pass the parameters to the called
+ * function. Depending on several criteria this may be done by just pushing
+ * each parameter separately, or creating the parameter frame once and then
+ * storing into this frame.
+ */
+{
+    ExprDesc Expr;
+
+    /* Initialize variables */
+    SymEntry* Param    	  = 0;	/* Keep gcc silent */
+    unsigned  ParamCount  = 0;	/* Number of parameters pushed */
+    int	      Ellipsis    = 0;	/* Function is variadic */
+
+    /* Parse the actual parameter list */
+    while (CurTok.Tok != TOK_RPAREN) {
+
+    	unsigned Flags;
+
+    	/* Count arguments */
+    	++ParamCount;
+
+		/* Fetch the pointer to the next argument, check for too many args */
+		if (ParamCount <= Func->ParamCount) {
+			/* Beware: If there are parameters with identical names, they
+			 * cannot go into the same symbol table, which means that in this
+			 * case of errorneous input, the number of nodes in the symbol
+			 * table and ParamCount are NOT equal. We have to handle this case
+			 * below to avoid segmentation violations. Since we know that this
+			 * problem can only occur if there is more than one parameter,
+			 * we will just use the last one.
+			 */
+			if (ParamCount == 1) {
+	       		/* First argument */
+	       		Param = Func->SymTab->SymHead;
+			} else if (Param->NextSym != 0) {
+	     		/* Next argument */
+	     		Param = Param->NextSym;
+	     		CHECK ((Param->Flags & SC_PARAM) != 0);
+			}
+		} else if (!Ellipsis) {
+			/* Too many arguments. Do we have an open param list? */
+			if ((Func->Flags & FD_VARIADIC) == 0) {
+	      		/* End of param list reached, no ellipsis */
+     	      		Error ("Too many arguments in function call");
+   			}
+			/* Assume an ellipsis even in case of errors to avoid an error
+			 * message for each other argument.
+			 */
+			Ellipsis = 1;
+     	}
+
+        /* Evaluate the parameter expression */
+        hie1 (&Expr);
+
+      	/* If we don't have an argument spec, accept anything, otherwise
+		 * convert the actual argument to the type needed.
+		 */
+        Flags = CF_NONE;
+       	if (!Ellipsis) {
+
+			/* Convert the argument to the parameter type if needed */
+			TypeConversion (&Expr, Param->Type);
+
+			/* If we have a prototype, chars may be pushed as chars */
+			Flags |= CF_FORCECHAR;
+
+       	} else {
+
+            /* No prototype available. Convert array to "pointer to first
+             * element", and function to "pointer to function".
+             */
+            Expr.Type = PtrConversion (Expr.Type);
+
+        }
+
+        /* Load the value into the primary if it is not already there */
+        LoadExpr (Flags, &Expr);
+
+		/* Use the type of the argument for the push */
+       	Flags |= TypeOf (Expr.Type);
+
+		/* If this is a fastcall function, don't store the last argument */
+       	if (ParamCount != Func->ParamCount || (Func->Flags & FD_FASTCALL) == 0) {
+
+			if (Param->Flags & SC_REGISTER) {
+				if (GetLeafFlag (Func))
+					g_store (Flags | CF_LEAFREGVAR, Expr.IVal, Param->V.R.RegOffs);
+				else
+					g_store (Flags, Expr.IVal, Param->V.R.Label);
+			}
+			else if (Param->Flags & SC_STATIC) {
+				g_store (Flags, Expr.IVal, Param->V.Label);
+			} else {
+				Internal ("Unexpected symbol type");
+			}
+		}
+
+		/* Check for end of argument list */
+     	if (CurTok.Tok != TOK_COMMA) {
+     	    break;
+		}
+     	NextToken ();
+    }
+
+    /* Check if we had enough parameters */
+    if (ParamCount < Func->ParamCount) {
+      	Error ("Too few arguments in function call");
+    }
+}
+
+
+
 static unsigned FunctionParamList (FuncDesc* Func)
 /* Parse a function parameter list and pass the parameters to the called
  * function. Depending on several criteria this may be done by just pushing
@@ -324,7 +438,6 @@ static unsigned FunctionParamList (FuncD
 	FrameSize   = Func->ParamSize;
 	if (FrameParams > 0 && (Func->Flags & FD_FASTCALL) != 0) {
 	    /* Last parameter is not pushed */
-	    FrameSize -= CheckedSizeOf (Func->LastParam->Type);
 	    --FrameParams;
 	}
 
@@ -465,7 +578,7 @@ static void FunctionCall (ExprDesc* Expr
 {
     FuncDesc*	  Func;	       	  /* Function descriptor */
     int           IsFuncPtr;      /* Flag */
-    unsigned 	  ParamSize;	  /* Number of parameter bytes */
+    unsigned 	  ParamSize = 0;  /* Number of parameter bytes */
     CodeMark   	  Mark;
     int           PtrOffs = 0;    /* Offset of function pointer on stack */
     int           IsFastCall = 0; /* True if it's a fast call function */
@@ -519,8 +632,40 @@ static void FunctionCall (ExprDesc* Expr
         }
     }
 
+	if (PassCount > 1) {
+		FuncRemember* FR = Func->Pass2;
+
+		if (Debug && !FR) {
+			Internal ("FunctionCall: %s not found in FuncRemember table", (char*) Expr->Name);
+		}
+
+		/* Force fastcall calling convention if desired */
+		if (AutoFastcall && FR &&
+			!(GetFuncRememberFlags (FR) & FR_STDCALL)) {
+
+			Func->Flags |= FD_FASTCALL;
+
+			AssignStackOffsetsToParams (Func);
+		}
+
+		/* Determine whether the function we're calling takes its parameters statically */
+		if (StaticParams && FR &&
+			!(GetFuncRememberFlags (FR) & FR_STDCALL)) {
+
+			/* init parameter symbols */
+			InitStaticParams (Func);
+
+			/* Parse the parameter list (static call) */
+			FunctionStaticParamList (Func);
+
+		} else {
     /* Parse the parameter list */
     ParamSize = FunctionParamList (Func);
+		}
+	} else {
+		/* Parse the parameter list */
+		ParamSize = FunctionParamList (Func);
+	}
 
     /* We need the closing paren here */
     ConsumeRParen ();
@@ -756,7 +901,7 @@ static void Primary (ExprDesc* E)
             /* String literal */
             E->Type  = GetCharArrayType (GetLiteralPoolOffs () - CurTok.IVal);
             E->Flags = E_LOC_LITERAL | E_RTYPE_RVAL;
-            E->IVal  = CurTok.IVal;
+			E->IVal  = RemoveDuplicateLiteral (CurTok.IVal);
             E->Name  = LiteralPoolLabel;
             NextToken ();
             break;
@@ -1153,6 +1298,11 @@ static void hie11 (ExprDesc *Expr)
                     ED_MakeConstAbs (Expr, 0, GetImplicitFuncType ());
                     Expr->Name = (long) IllegalFunc;
                 }
+
+				/* we're not in a leaf routine */
+				if (PassCount == 1)
+					SetLeafFlag (F_GetFuncDesc(CurrentFunc), 0);
+
                 /* Call the function */
                 FunctionCall (Expr);
                 break;
diff -b -up cc65.org\exprdesc.c cc65\exprdesc.c
--- cc65.org\exprdesc.c	Sun Feb 19 08:29:38 2006
+++ cc65\exprdesc.c	Sun Jun 24 02:33:12 2007
@@ -44,7 +44,7 @@
 #include "stackptr.h"
 #include "symentry.h"
 #include "exprdesc.h"
-
+#include "function.h"
 
 
 /*****************************************************************************/
@@ -98,6 +98,9 @@ const char* ED_GetLabelName (const ExprD
 
         case E_LOC_REGISTER:
             /* Register variable */
+			if (GetLeafFlag (F_GetFuncDesc (CurrentFunc)))
+	      	    SB_Printf (&Buf, "leafregbank+%u", (unsigned)((Offs + Expr->Name) & 0xFFFFU));
+			else
       	    SB_Printf (&Buf, "regbank+%u", (unsigned)((Offs + Expr->Name) & 0xFFFFU));
             break;
 
diff -b -up cc65.org\funcdesc.c cc65\funcdesc.c
--- cc65.org\funcdesc.c	Sun Aug 10 13:05:18 2003
+++ cc65\funcdesc.c	Mon Jul 02 15:55:58 2007
@@ -35,11 +35,13 @@
 
 /* common */
 #include "xmalloc.h"
+#include "check.h"
 
 /* cc65 */
 #include "funcdesc.h"
-
-
+#include "compile.h"
+#include "global.h"
+#include "funcremember.h"
 
 /*****************************************************************************/
 /*	       	      	       	     Code				     */
@@ -60,6 +62,8 @@ FuncDesc* NewFuncDesc (void)
     F->ParamCount = 0;
     F->ParamSize  = 0;
     F->LastParam  = 0;
+	F->RegOffs    = 0;
+	F->Pass2      = 0;
 
     /* Return the new struct */
     return F;
@@ -72,6 +76,30 @@ void FreeFuncDesc (FuncDesc* F)
 {
     /* Free the structure */
     xfree (F);
+}
+
+
+
+void SetLeafFlag (FuncDesc* Func, unsigned flag)
+/* set function leaf status */
+{
+	PRECONDITION (PassCount == 1);
+
+	if (flag)
+		SetFuncRememberFlags (Func->Pass2, FR_LEAF);
+	else
+		ClearFuncRememberFlags (Func->Pass2, FR_LEAF);
+}
+
+
+
+unsigned GetLeafFlag (const FuncDesc* Func)
+/* get function leaf status */
+{
+	if (PassCount > 1 && LeafOptimization && (GetFuncRememberFlags (Func->Pass2) & FR_LEAF))
+		return 1;
+	else
+		return 0;
 }
 
 
diff -b -up cc65.org\funcdesc.h cc65\funcdesc.h
--- cc65.org\funcdesc.h	Fri Nov 28 18:12:14 2003
+++ cc65\funcdesc.h	Mon Jul 02 15:55:22 2007
@@ -56,6 +56,7 @@
 #define FD_OLDSTYLE    	       	0x0100U	/* Old style (K&R) function	     */
 #define FD_OLDSTYLE_INTRET    	0x0200U	/* K&R func has implicit int return  */
 #define FD_UNNAMED_PARAMS      	0x0400U	/* Function has unnamed params	     */
+#define FD_STATICPARAMS	0x0800U	/* Static parameters	     */
 
 /* Bits that must be ignored when comparing funcs */
 #define FD_IGNORE 	(FD_IMPLICIT | FD_UNNAMED_PARAMS)
@@ -71,6 +72,8 @@ struct FuncDesc {
     unsigned		ParamCount;	/* Number of parameters		     */
     unsigned		ParamSize;	/* Size of the parameters	     */
     struct SymEntry*	LastParam;	/* Pointer to last parameter	     */
+    unsigned            RegOffs;	/* Register variable space offset */
+	struct FuncRemember*	Pass2;	/* Info to remember for pass 2	*/
 };
 
 
@@ -87,6 +90,11 @@ FuncDesc* NewFuncDesc (void);
 void FreeFuncDesc (FuncDesc* D);
 /* Free a function descriptor */
 
+void SetLeafFlag (FuncDesc* Func, unsigned flag);
+/* set function leaf status */
+
+unsigned GetLeafFlag (const FuncDesc* Func);
+/* get function leaf status */
 
 
 /* End of funcdesc.h */

diff -b -up cc65.org\function.c cc65\function.c
--- cc65.org\function.c	Sun Feb 19 08:29:38 2006
+++ cc65\function.c	Sun Jul 15 16:35:44 2007
@@ -53,7 +53,8 @@
 #include "stmt.h"
 #include "symtab.h"
 #include "function.h"
-
+#include "compile.h"
+#include "funcremember.h"
 
 
 /*****************************************************************************/
@@ -70,7 +71,6 @@ struct Function {
     int			Reserved;   	/* Reserved local space */
     unsigned	  	RetLab;	    	/* Return code label */
     int			TopLevelSP;	/* SP at function top level */
-    unsigned            RegOffs;        /* Register variable space offset */
 };
 
 /* Pointer to current function */
@@ -84,7 +84,7 @@ Function* CurrentFunc = 0;
 
 
 
-static Function* NewFunction (struct SymEntry* Sym)
+Function* NewFunction (struct SymEntry* Sym)
 /* Create a new function activation structure and return it */
 {
     /* Allocate a new structure */
@@ -97,7 +97,6 @@ static Function* NewFunction (struct Sym
     F->Reserved	  = 0;
     F->RetLab	  = GetLocalLabel ();
     F->TopLevelSP = 0;
-    F->RegOffs    = RegisterSpace;
 
     /* Return the new structure */
     return F;
@@ -105,7 +104,7 @@ static Function* NewFunction (struct Sym
 
 
 
-static void FreeFunction (Function* F)
+void FreeFunction (Function* F)
 /* Free a function activation structure */
 {
     xfree (F);
@@ -113,6 +112,14 @@ static void FreeFunction (Function* F)
 
 
 
+FuncDesc* F_GetFuncDesc (const Function* F)
+/* Return the FuncDesc of a function */
+{
+	return F->Desc;
+}
+
+
+
 const char* F_GetFuncName (const Function* F)
 /* Return the name of the current function */
 {
@@ -224,47 +231,22 @@ void F_AllocLocalSpace (Function* F)
 
 
 
-int F_AllocRegVar (Function* F, const Type* Type)
-/* Allocate a register variable for the given variable type. If the allocation
- * was successful, return the offset of the register variable in the register
- * bank (zero page storage). If there is no register space left, return -1.
- */
-{
-    /* Allow register variables only on top level and if enabled */
-    if (IS_Get (&EnableRegVars) && GetLexicalLevel () == LEX_LEVEL_FUNCTION) {
-
-      	/* Get the size of the variable */
-      	unsigned Size = CheckedSizeOf (Type);
-
-      	/* Do we have space left? */
-      	if (F->RegOffs >= Size) {
-      	    /* Space left. We allocate the variables from high to low addresses,
-      	     * so the adressing is compatible with the saved values on stack.
-      	     * This allows shorter code when saving/restoring the variables.
-      	     */
-      	    F->RegOffs -= Size;
-      	    return F->RegOffs;
-      	}
-    }
-
-    /* No space left or no allocation */
-    return -1;
-}
-
-
-
 static void F_RestoreRegVars (Function* F)
 /* Restore the register variables for the local function if there are any. */
 {
     const SymEntry* Sym;
 
     /* If we don't have register variables in this function, bail out early */
-    if (F->RegOffs == RegisterSpace) {
+    if (F->Desc->RegOffs == (GetLeafFlag (F->Desc) ? LeafRegisterSpace : RegisterSpace)) {
        	return;
     }
 
     /* Save the accumulator if needed */
     if (!F_HasVoidReturn (F)) {
+		if (UseHardwareStack)
+			/* Can't use pha */
+			AddCodeLine ("tay");
+		else
        	g_save (CF_CHAR | CF_FORCECHAR);
     }
 
@@ -310,6 +292,9 @@ static void F_RestoreRegVars (Function* 
             }
 
             /* Restore the memory range */
+			if (UseHardwareStack)
+				g_restore_regvars_hardwarestack (Sym->V.R.RegOffs, Bytes);
+			else
             g_restore_regvars (Offs, Sym->V.R.RegOffs, Bytes);
 
         }
@@ -320,6 +305,10 @@ static void F_RestoreRegVars (Function* 
 
     /* Restore the accumulator if needed */
     if (!F_HasVoidReturn (F)) {
+		if (UseHardwareStack)
+			/* Can't use pha/pla */
+			AddCodeLine ("tya");
+		else
      	g_restore (CF_CHAR | CF_FORCECHAR);
     }
 }
@@ -332,6 +321,225 @@ static void F_RestoreRegVars (Function* 
 
 
 
+int AllocRegVar (FuncDesc* F, const Type* Type)
+/* Allocate a register variable for the given variable type. If the allocation
+ * was successful, return the offset of the register variable in the register
+ * bank (zero page storage). If there is no register space left, return -1.
+ */
+{
+    /* Allow register variables only on top level and if enabled, or if leaf function */
+    if ((IS_Get (&EnableRegVars) && GetLexicalLevel () == LEX_LEVEL_FUNCTION) || GetLeafFlag (F)) {
+
+      	/* Get the size of the variable */
+      	unsigned Size = CheckedSizeOf (Type);
+
+      	/* Do we have space left? */
+      	if (F->RegOffs >= Size) {
+      	    /* Space left. We allocate the variables from high to low addresses,
+      	     * so the adressing is compatible with the saved values on stack.
+      	     * This allows shorter code when saving/restoring the variables.
+      	     */
+      	    F->RegOffs -= Size;
+      	    return F->RegOffs;
+      	}
+    }
+
+    /* No space left or no allocation */
+    return -1;
+}
+
+
+
+void AssignStackOffsetsToParams (FuncDesc* F)
+/* Assign stack offsets to parameters. If the function has a variable parameter list,
+ * there's one additional byte (the arg size). If the function is 'fastcall', the offsets
+ * and size are adjusted to reflect that the last argument is not pushed.
+ */
+{
+	int Offs;
+	SymEntry* Sym = F->LastParam;
+
+	if (F->Flags & FD_VARIADIC) {
+		Offs = 1;
+	} else if (Sym && (F->Flags & FD_FASTCALL)) {
+		Offs = -(int)CheckedSizeOf (Sym->Type);
+	} else {
+		Offs = 0;
+	}
+
+	F->ParamSize = 0;
+
+	while (Sym) {
+		unsigned Size = CheckedSizeOf (Sym->Type);
+
+        if (SymIsRegVar (Sym)) {
+            Sym->V.R.SaveOffs = Offs;
+        } else if (Sym->Flags & SC_AUTO) {
+     	    Sym->V.Offs = Offs;
+        }
+       	Offs += Size;
+		F->ParamSize += Size;
+
+     	Sym = Sym->PrevSym;
+    }
+
+	if (F->ParamSize && (F->Flags & FD_FASTCALL))
+		F->ParamSize -= CheckedSizeOf (F->LastParam->Type);
+}
+
+
+
+void CopyStaticParams (FuncDesc* New, FuncDesc* Old, const char *Name)
+/* Copy flags and labels from function call parameters (previously
+ * initialized with InitStaticParams) to a fresh set of function definition
+ * parameters.
+ */
+{
+    SymEntry* OldParam;
+    SymEntry* NewParam;
+
+	PRECONDITION (Old->Flags & FD_STATICPARAMS);
+	PRECONDITION (PassCount > 1);
+
+	/* Walk through the parameter list, copying the info we need */
+	OldParam = Old->SymTab->SymHead;
+	NewParam = New->SymTab->SymHead;
+	while (OldParam && (OldParam->Flags & SC_PARAM) != 0) {
+
+		if (!NewParam || (OldParam->Flags & SC_PARAM) == 0) {
+			Internal ("Pass 2: Conflicting types for `%s'", Name);
+			return;
+		}
+
+		/* Copy flags */
+		NewParam->Flags = OldParam->Flags;
+
+		/* Check for a register variable */
+		if (SymIsRegVar (OldParam)) {
+
+			/* Copy the register offset */
+			NewParam->V.R.RegOffs = OldParam->V.R.RegOffs;
+
+			/* Copy label (used for non-leaf routines) */
+			NewParam->V.R.Label = OldParam->V.R.Label;
+			ChangeAsmName (NewParam, LocalLabelName (NewParam->V.R.Label));
+
+		} else {
+			if (OldParam->Flags & SC_STATIC) {
+
+				/* Copy label */
+				NewParam->V.Label = OldParam->V.Label;
+				ChangeAsmName (NewParam, LocalLabelName (NewParam->V.Label));
+
+			} else {
+				Internal ("CopyStaticParams: failed");
+			}
+		}
+
+		/* Next parameter */
+		OldParam = OldParam->NextSym;
+		NewParam = NewParam->NextSym;
+	}
+
+	if (NewParam)
+		Internal ("Pass 2: Conflicting types for `%s'", Name);
+
+	/* Copy current register allocation */
+	New->RegOffs = Old->RegOffs;
+
+	/* mark as having been initialized */
+	New->Flags |= FD_STATICPARAMS;
+}
+
+
+
+void InitStaticParams (FuncDesc* D)
+/* Set up parameter symbols for static calls 
+ * This is called from two places, NewFunc and FunctionStaticParamList. It may be called
+ * more than once, and either NewFunc or FunctionStaticParamList may be the first to call it
+ * (FunctionStaticParamList will be first if there's a forward-reference call).
+ */
+{
+    SymEntry* Param;
+
+	/* get leaf status */
+	unsigned LeafFlag = GetLeafFlag (D);
+
+	PRECONDITION (PassCount > 1);
+
+	/* If already initialized, return */
+	if (D->Flags & FD_STATICPARAMS)
+		return;
+
+	/* Initialize RegOffs field of FuncDesc */
+	D->RegOffs = GetLeafFlag (D) ? LeafRegisterSpace : RegisterSpace;
+
+	/* Walk through the parameter list and allocate register variable space
+	 * for parameters declared as register.
+	 */
+	Param = D->SymTab->SymHead;
+	while (Param && (Param->Flags & SC_PARAM) != 0) {
+
+		/* If leaf, automatically make it a register */
+		if (LeafFlag && (Param->Flags & SC_AUTO))
+			CvtAutoToRegVar (Param);
+
+		/* Check for a register variable. */
+		if (SymIsRegVar (Param)) {
+
+			/* Allocate space */
+			int Reg = AllocRegVar (D, Param->Type);
+
+			/* Could we allocate a register? */
+			if (Reg < 0) {
+
+				/* No register available: Convert parameter to static */
+				CvtRegVarToStatic (Param);
+
+			} else {
+
+				/* Remember the register offset */
+				Param->V.R.RegOffs = Reg;
+
+				if (!LeafFlag) {
+
+					/* get a static label */
+					Param->V.R.Label = GetLocalLabel ();
+					ChangeAsmName (Param, LocalLabelName (Param->V.R.Label));
+				}
+			}
+
+		} else {
+			if (Param->Flags & SC_AUTO)
+				CvtAutoVarToStatic (Param);
+			else
+				Internal ("InitStaticParams: failed");
+		}
+
+		/* Next parameter */
+		Param = Param->NextSym;
+	}
+
+	/* mark as having been initialized */
+	D->Flags |= FD_STATICPARAMS;
+}
+
+
+
+static unsigned GetSymBaseType (SymEntry* Sym)
+/* Get the base type for NewFunc */
+{
+	if (IsTypeFunc (Sym->Type)) {
+		/* Pointer to function */
+		/* (What is the purpose of this???) */
+		return CF_PTR;	/* same as CF_INT */
+	} else {
+		return TypeOf (Sym->Type) | CF_FORCECHAR;
+	}
+}
+
+
+
 void NewFunc (SymEntry* Func)
 /* Parse argument declarations and function body. */
 {
@@ -341,12 +549,29 @@ void NewFunc (SymEntry* Func)
     /* Get the function descriptor from the function entry */
     FuncDesc* D = Func->V.F.Func;
 
+	/* get leaf status (always 0 if pass 1) */
+	unsigned LeafFlag = GetLeafFlag (D);
+
+	/* Preset leaf state (pass 1 only). Will be reset if we hit a function call. */
+	if (PassCount == 1)
+		SetLeafFlag (D, 1);
+
     /* Allocate the function activation record for the function */
     CurrentFunc = NewFunction (Func);
 
     /* Reenter the lexical level */
     ReenterFunctionLevel (D);
 
+	/* Force fastcall calling convention if desired */
+	if (AutoFastcall) {
+		if (PassCount > 1 &&
+			!(GetFuncRememberFlags (D->Pass2) & FR_STDCALL)) {
+
+			D->Flags |= FD_FASTCALL;
+			AssignStackOffsetsToParams (D);
+		}
+	}
+
     /* Declare two special functions symbols: __fixargs__ and __argsize__.
      * The latter is different depending on the type of the function (variadic
      * or not).
@@ -364,9 +589,6 @@ void NewFunc (SymEntry* Func)
     /* Function body now defined */
     Func->Flags |= SC_DEF;
 
-    /* Allocate code and data segments for this function */
-    Func->V.F.Seg = PushSegments (Func);
-
     /* Special handling for main() */
     if (strcmp (Func->Name, "main") == 0) {
         /* Main cannot be a fastcall function */
@@ -390,22 +612,95 @@ void NewFunc (SymEntry* Func)
         }
     }
 
-    /* If this is a fastcall function, push the last parameter onto the stack */
+	/* Setup the stack */
+	StackPtr = 0;
+
+	/* determine whether function should receive its args statically */
+	if (PassCount > 1 && StaticParams &&
+		!(GetFuncRememberFlags (D->Pass2) & FR_STDCALL)) {
+
+		/* Yes, the function is receiving its args statically. */
+
+		/* Flag for case of nonleaf+fastcall+register */
+		unsigned NonLeafFastcallRegister = 0;
+
+		/* init parameter symbols */
+		InitStaticParams (D);
+
+		/* nothing pushed on stack */
+		D->ParamSize = 0;
+
+        /* Uninitialized data, use BSS segment */
+        g_usebss ();
+
+		/* Walk through the parameter list and allocate static space for parameters. */
+		Param = D->SymTab->SymHead;
+		while (Param && (Param->Flags & SC_PARAM) != 0) {
+
+			/* Check for a register variable. */
+			if (SymIsRegVar (Param)) {
+
+				if (!LeafFlag) {
+
+					/* Optimize this case:
+					 * 1. Non-leaf
+					 * 2. Fastcall
+					 * 3. Last param 'register'
+					 *
+					 * Don't reserve static space because it isn't needed in this case.
+					 */
+					if (IsFastCallFunc (Func->Type) && Param == D->LastParam) {
+
+						/* Remember for later */
+						NonLeafFastcallRegister = 1;
+
+					}
+					else {
+						/* allocate space for static register */
+						g_defdatalabel (Param->V.R.Label);
+						g_res (SizeOf (Param->Type));
+					}
+				}
+
+			} else {
+				/* allocate space for static non-register */
+		        g_defdatalabel (Param->V.Label);
+				g_res (SizeOf (Param->Type));
+			}
+
+			/* Next parameter */
+			Param = Param->NextSym;
+		}
+
+		/* Allocate code and data segments for this function */
+		Func->V.F.Seg = PushSegments (Func);
+
+		if (NonLeafFastcallRegister) {
+			/* Save the accumulator (and X if needed) for later. */
+			if (UseHardwareStack) {
+				AddCodeLine ("tay");
+			}
+			else {
+				g_save_ax (GetSymBaseType (Param));
+			}
+		}
+
+		/* If this is a fastcall function, store the last parameter */
     if (IsFastCallFunc (Func->Type) && D->ParamCount > 0) {
 
-     	unsigned Flags;
+     		unsigned Flags = GetSymBaseType (D->LastParam);
 
      	/* Fastcall functions may never have an ellipsis or the compiler is buggy */
      	CHECK ((D->Flags & FD_VARIADIC) == 0);
 
-     	/* Generate the push */
-     	if (IsTypeFunc (D->LastParam->Type)) {
-	    /* Pointer to function */
-	    Flags = CF_PTR;
-	} else {
-    	    Flags = TypeOf (D->LastParam->Type) | CF_FORCECHAR;
+			if (D->LastParam->Flags & SC_REGISTER) {
+				if (LeafFlag) {
+					g_putstatic (Flags | CF_REGVAR, 0, D->LastParam->V.R.RegOffs);
+				}	/* else do nothing since nonleaf+fastcall+register has been handled */
+			}
+			else {
+				g_putstatic (Flags | CF_STATIC, D->LastParam->V.Label, 0);
 	}
-	g_push (Flags, 0);
     }
 
     /* Generate function entry code if needed */
@@ -416,21 +711,76 @@ void NewFunc (SymEntry* Func)
     	g_stackcheck ();
     }
 
-    /* Setup the stack */
-    StackPtr = 0;
+		/* Walk through the parameter list and generate code to save the contents
+		 * of the register bank and load with the static params.
+		 */
+		if (!LeafFlag) {
+			Param = D->SymTab->SymHead;
+			while (Param && (Param->Flags & SC_PARAM) != 0) {
+
+				/* Check for a register variable */
+				if (SymIsRegVar (Param)) {
+
+					/* Save regbank register */
+					if (UseHardwareStack) {
+						g_save_regvars_hardwarestack (Param->V.R.RegOffs, CheckedSizeOf (Param->Type));
+					} else {
+						g_save_regvars (Param->V.R.RegOffs, CheckedSizeOf (Param->Type));
+						Param->V.R.SaveOffs = StackPtr;
+					}
+
+					if (Param == D->LastParam && NonLeafFastcallRegister)
+					{
+						/* Handle case of nonleaf+fastcall+register. Restore
+						 * A/X and then store last parameter in regbank.
+						 */
+						unsigned Flags = GetSymBaseType (Param);
+
+						if (UseHardwareStack) {
+							g_putstatic_y (Flags | CF_REGVAR, Param->V.R.RegOffs, 0);
+						}
+						else {
+							g_restore_ax (Flags);
+							g_putstatic (Flags | CF_REGVAR, Param->V.R.RegOffs, 0);
+						}
+
+					} else {
+						g_load_regvars_static (Param->V.R.Label, Param->V.R.RegOffs, CheckedSizeOf (Param->Type));
+					}
+				}
+
+				/* Next parameter */
+				Param = Param->NextSym;
+			}
+		}
+
+	} else {
+		/* args received on stack */
+
+		/* Flag for case of nonleaf+fastcall+register */
+		unsigned FastcallRegisterFlag = 0;
+
+		/* Initialize RegOffs field of FuncDesc */
+		D->RegOffs = GetLeafFlag (D) ? LeafRegisterSpace : RegisterSpace;
+
+		/* Allocate code and data segments for this function */
+		Func->V.F.Seg = PushSegments (Func);
 
     /* Walk through the parameter list and allocate register variable space
-     * for parameters declared as register. Generate code to swap the contents
-     * of the register bank with the save area on the stack.
+		 * for parameters declared as register.
      */
     Param = D->SymTab->SymHead;
     while (Param && (Param->Flags & SC_PARAM) != 0) {
 
+			/* If fastcall+leaf and this is the last param, force register */
+			if (Param == D->LastParam && LeafFlag && IsFastCallFunc (Func->Type) && (Param->Flags & SC_AUTO))
+				CvtAutoToRegVar (Param);
+
         /* Check for a register variable */
         if (SymIsRegVar (Param)) {
 
             /* Allocate space */
-            int Reg = F_AllocRegVar (CurrentFunc, Param->Type);
+				int Reg = AllocRegVar (D, Param->Type);
 
             /* Could we allocate a register? */
             if (Reg < 0) {
@@ -439,16 +789,117 @@ void NewFunc (SymEntry* Func)
             } else {
                 /* Remember the register offset */
                 Param->V.R.RegOffs = Reg;
+				}
+			}
+
+			/* Next parameter */
+			Param = Param->NextSym;
+		}
+
+		/* If this is a fastcall function, push the last parameter onto the stack */
+		if (IsFastCallFunc (Func->Type) && D->ParamCount > 0) {
+
+     		unsigned Flags = GetSymBaseType (D->LastParam);
+
+     		/* Fastcall functions may never have an ellipsis or the compiler is buggy */
+     		CHECK ((D->Flags & FD_VARIADIC) == 0);
+
+			if (D->LastParam->Flags & SC_REGISTER) {
+
+				/* Remember for later */
+				FastcallRegisterFlag = 1;
+
+				if (LeafFlag) {
+					g_putstatic (Flags | CF_REGVAR, 0, D->LastParam->V.R.RegOffs);
+				} else {
+					if (UseHardwareStack) {
+						AddCodeLine ("sta regsave");
+					}
+					else {
+						g_save_ax (Flags);
+					}
+				}
+			} else if (IS_Get (&StaticLocals)) {
+				/* If static locals enabled, store fastcall param in static location */
+
+				/* Uninitialized data, use BSS segment */
+				g_usebss ();
+
+				/* Convert to static */
+				CvtAutoVarToStatic (D->LastParam);
 
-                /* Generate swap code */
-                g_swap_regvars (Param->V.R.SaveOffs, Reg, CheckedSizeOf (Param->Type));
+				/* allocate space */
+		        g_defdatalabel (D->LastParam->V.Label);
+				g_res (SizeOf (D->LastParam->Type));
 
+				/* Do the store */
+				g_putstatic (Flags | CF_STATIC, D->LastParam->V.Label, 0);
+			}
+			else {
+				g_push (Flags, 0);
+			}
+		}
+
+		/* Generate function entry code if needed */
+		g_enter (TypeOf (Func->Type), F_GetParamSize (CurrentFunc));
+
+		/* If stack checking code is requested, emit a call to the helper routine */
+		if (IS_Get (&CheckStack)) {
+    		g_stackcheck ();
+		}
+
+		/* Walk through the parameter list and generate code to swap the contents
+		 * of the register bank with the save area on the stack.
+		 */
+		Param = D->SymTab->SymHead;
+		while (Param && (Param->Flags & SC_PARAM) != 0) {
+
+			/* Check for a register variable */
+			if (SymIsRegVar (Param)) {
+
+				if (Param == D->LastParam && FastcallRegisterFlag) {
+
+					if (!LeafFlag) {
+						/* Handle case of nonleaf+fastcall+register. Restore
+						 * A/X and then store last parameter in regbank.
+						 */
+						unsigned Flags = GetSymBaseType (Param);
+
+						if (UseHardwareStack) {
+							g_save_regvars_hardwarestack (Param->V.R.RegOffs, CheckedSizeOf (Param->Type));
+							AddCodeLine ("lda regsave");
+						}
+						else {
+							g_save_regvars (Param->V.R.RegOffs, CheckedSizeOf (Param->Type));
+							Param->V.R.SaveOffs = StackPtr;
+							g_restore_ax (Flags);
+						}
+
+						g_putstatic (Flags | CF_REGVAR, Param->V.R.RegOffs, 0);
+
+					}	/* else do nothing */
+				} else {
+
+					/* Generate swap or load code */
+					if (LeafFlag) {
+						g_load_leafregvars (Param->V.R.SaveOffs, Param->V.R.RegOffs, CheckedSizeOf (Param->Type));
+					}
+					else {
+						if (UseHardwareStack) {
+							g_save_regvars_hardwarestack (Param->V.R.RegOffs, CheckedSizeOf (Param->Type));
+							g_load_regvars (Param->V.R.SaveOffs, Param->V.R.RegOffs, CheckedSizeOf (Param->Type));
+						}
+						else {
+							g_swap_regvars (Param->V.R.SaveOffs, Param->V.R.RegOffs, CheckedSizeOf (Param->Type));
+						}
+					}
             }
         }
 
         /* Next parameter */
         Param = Param->NextSym;
     }
+	}
 
     /* Need a starting curly brace */
     ConsumeLCurly ();
@@ -475,6 +926,7 @@ void NewFunc (SymEntry* Func)
     g_defcodelabel (F_GetRetLab (CurrentFunc));
 
     /* Restore the register variables */
+	if (!LeafFlag)
     F_RestoreRegVars (CurrentFunc);
 
     /* Generate the exit code */
diff -b -up cc65.org\function.h cc65\function.h
--- cc65.org\function.h	Sun Feb 19 08:29:38 2006
+++ cc65\function.h	Mon Jul 09 09:28:20 2007
@@ -56,7 +56,8 @@ extern Function* CurrentFunc;
 /*	      		    	     Code		     		     */
 /*****************************************************************************/
 
-
+FuncDesc* F_GetFuncDesc (const Function* F);
+/* Return the FuncDesc of a function */
 
 const char* F_GetFuncName (const Function* F);
 /* Return the name of the current function */
@@ -98,14 +99,35 @@ void F_AllocLocalSpace (Function* F);
  * nothing if there is no reserved local space.
  */
 
-int F_AllocRegVar (Function* F, const Type* Type);
+int AllocRegVar (FuncDesc* F, const Type* Type);
 /* Allocate a register variable for the given variable type. If the allocation
  * was successful, return the offset of the register variable in the register
  * bank (zero page storage). If there is no register space left, return -1.
  */
 
+void AssignStackOffsetsToParams (FuncDesc* F);
+/* Assign stack offsets to parameters. If the function has a variable parameter list,
+ * there's one additional byte (the arg size). If the function is 'fastcall', the offsets
+ * and size are adjusted to reflect that the last argument is not pushed.
+ */
+
+void CopyStaticParams (FuncDesc* New, FuncDesc* Old, const char *Name);
+/* Copy flags and labels from function call parameters (previously
+ * initialized with InitStaticParams) to a fresh set of function definition
+ * parameters.
+ */
+
+void InitStaticParams (FuncDesc *D);
+/* Set up parameter symbols for static calls */
+
 void NewFunc (struct SymEntry* Func);
 /* Parse argument declarations and function body. */
+
+Function* NewFunction (struct SymEntry* Sym);
+/* Create a new function activation structure and return it */
+
+void FreeFunction (Function* F);
+/* Free a function activation structure */
 
 
 
diff -b -up cc65.org\global.c cc65\global.c
--- cc65.org\global.c	Thu Sep 16 08:42:40 2004
+++ cc65\global.c	Wed Jul 04 06:24:12 2007
@@ -33,6 +33,9 @@
 
 
 
+#include <memory.h>
+
+
 #include "global.h"
 
 
@@ -48,19 +51,85 @@ unsigned char DebugInfo		= 0;	/* Add deb
 unsigned char CreateDep		= 0;	/* Create a dependency file */
 unsigned char PreprocessOnly    = 0;    /* Just preprocess the input */
 unsigned      RegisterSpace     = 6;    /* Space available for register vars */
+unsigned char LeafOptimization  =  0;	/* Enable leaf function optimization */
+unsigned char UseHardwareStack  =  0;	/* Use hardware stack for register saving */
+unsigned      LeafRegisterSpace = 16;	/* Space available for leaf register vars */
+unsigned char AutoFastcall      =  0;	/* Use fastcall calling convention for static functions */
+unsigned char StaticParams      =  0;	/* Use static locations for parameter passing */
+unsigned char StringMerge       =  0;	/* Merge identical string literals */
+
 
 /* Stackable options */
 IntStack WarnDisable        = INTSTACK(0);  /* Suppress warnings */
+static IntStack WarnDisableSnapshot;
+
 IntStack WritableStrings    = INTSTACK(0);  /* Literal strings are r/w */
+static IntStack WritableStringsSnapshot;
+
 IntStack InlineStdFuncs     = INTSTACK(0);  /* Inline some known functions */
+static IntStack InlineStdFuncsSnapshot;
+
 IntStack EnableRegVars      = INTSTACK(0);  /* Enable register variables */
+static IntStack EnableRegVarsSnapshot;
+
 IntStack AllowRegVarAddr    = INTSTACK(0);  /* Allow taking addresses of register vars */
+static IntStack AllowRegVarAddrSnapshot;
+
 IntStack RegVarsToCallStack = INTSTACK(0);  /* Save reg variables on call stack */
+static IntStack RegVarsToCallStackSnapshot;
+
 IntStack StaticLocals       = INTSTACK(0);  /* Make local variables static */
+static IntStack StaticLocalsSnapshot;
+
 IntStack SignedChars        = INTSTACK(0);  /* Make characters signed by default */
+static IntStack SignedCharsSnapshot;
+
 IntStack CheckStack         = INTSTACK(0);  /* Generate stack overflow checks */
+static IntStack CheckStackSnapshot;
+
 IntStack Optimize      	    = INTSTACK(0);  /* Optimize flag */
+static IntStack OptimizeSnapshot;
+
 IntStack CodeSizeFactor	    = INTSTACK(100);/* Size factor for generated code */
+static IntStack CodeSizeFactorSnapshot;
+
+
+
+/*****************************************************************************/
+/*     	      	    	       	     Code               				     */
+/*****************************************************************************/
 
 
+void SnapshotGlobal (void)
+/* save global settings for pass 2 */
+{
+	memcpy (&WarnDisableSnapshot, &WarnDisable, sizeof WarnDisableSnapshot);
+	memcpy (&WritableStringsSnapshot, &WritableStrings, sizeof WritableStringsSnapshot);
+	memcpy (&InlineStdFuncsSnapshot, &InlineStdFuncs, sizeof InlineStdFuncsSnapshot);
+	memcpy (&EnableRegVarsSnapshot, &EnableRegVars, sizeof EnableRegVarsSnapshot);
+	memcpy (&AllowRegVarAddrSnapshot, &AllowRegVarAddr, sizeof AllowRegVarAddrSnapshot);
+	memcpy (&RegVarsToCallStackSnapshot, &RegVarsToCallStack, sizeof RegVarsToCallStackSnapshot);
+	memcpy (&StaticLocalsSnapshot, &StaticLocals, sizeof StaticLocalsSnapshot);
+	memcpy (&SignedCharsSnapshot, &SignedChars, sizeof SignedCharsSnapshot);
+	memcpy (&CheckStackSnapshot, &CheckStack, sizeof CheckStackSnapshot);
+	memcpy (&OptimizeSnapshot, &Optimize, sizeof OptimizeSnapshot);
+	memcpy (&CodeSizeFactorSnapshot, &CodeSizeFactor, sizeof CodeSizeFactorSnapshot);
+}
+
+
+void RestoreGlobal (void)
+/* restore settings saved by SnapshotGlobal */
+{
+	memcpy (&WarnDisable, &WarnDisableSnapshot, sizeof WarnDisable);
+	memcpy (&WritableStrings, &WritableStringsSnapshot, sizeof WritableStrings);
+	memcpy (&InlineStdFuncs, &InlineStdFuncsSnapshot, sizeof InlineStdFuncs);
+	memcpy (&EnableRegVars, &EnableRegVarsSnapshot, sizeof EnableRegVars);
+	memcpy (&AllowRegVarAddr, &AllowRegVarAddrSnapshot, sizeof AllowRegVarAddr);
+	memcpy (&RegVarsToCallStack, &RegVarsToCallStackSnapshot, sizeof RegVarsToCallStack);
+	memcpy (&StaticLocals, &StaticLocalsSnapshot, sizeof StaticLocals);
+	memcpy (&SignedChars, &SignedCharsSnapshot, sizeof SignedChars);
+	memcpy (&CheckStack, &CheckStackSnapshot, sizeof CheckStack);
+	memcpy (&Optimize, &OptimizeSnapshot, sizeof Optimize);
+	memcpy (&CodeSizeFactor, &CodeSizeFactorSnapshot, sizeof CodeSizeFactor);
+}
 
diff -b -up cc65.org\global.h cc65\global.h
--- cc65.org\global.h	Thu Sep 16 08:42:42 2004
+++ cc65\global.h	Wed Jul 04 06:07:32 2007
@@ -55,6 +55,12 @@ extern unsigned char	DebugInfo;		/* Add 
 extern unsigned char	CreateDep;		/* Create a dependency file */
 extern unsigned char    PreprocessOnly;         /* Just preprocess the input */
 extern unsigned         RegisterSpace;          /* Space available for register vars */
+extern unsigned char	LeafOptimization;	/* Enable leaf function optimization */
+extern unsigned char	UseHardwareStack;	/* Use hardware stack for saving registers */
+extern unsigned         LeafRegisterSpace;	/* Space available for leaf register vars */
+extern unsigned char	AutoFastcall;		/* Use fastcall calling convention for static functions */
+extern unsigned char	StaticParams;		/* Use static locations for parameter passing */
+extern unsigned char	StringMerge;		/* Merge identical string literals */
 
 /* Stackable options */
 extern IntStack         WarnDisable;            /* Suppress warnings */
@@ -68,6 +74,18 @@ extern IntStack         SignedChars;		/*
 extern IntStack         CheckStack;		/* Generate stack overflow checks */
 extern IntStack         Optimize;		/* Optimize flag */
 extern IntStack         CodeSizeFactor;		/* Size factor for generated code */
+
+
+
+/*****************************************************************************/
+/*     	      	    	       	     Code               				     */
+/*****************************************************************************/
+
+void SnapshotGlobal (void);
+/* save global settings for pass 2 */
+
+void RestoreGlobal (void);
+/* restore settings saved by SnapshotGlobal */
 
 
 
diff -b -up cc65.org\litpool.c cc65\litpool.c
--- cc65.org\litpool.c	Wed Jun 02 17:33:36 2004
+++ cc65\litpool.c	Wed Jul 04 06:02:56 2007
@@ -45,6 +45,7 @@
 #include "error.h"
 #include "global.h"
 #include "litpool.h"
+#include "debugflag.h"
 
 
 
@@ -56,7 +57,7 @@
 
 unsigned 	      LiteralPoolLabel 	= 0;	/* Pool asm label */
 static StrBuf         LiteralPool       = STATIC_STRBUF_INITIALIZER;
-
+static unsigned	ResetMinimum = 0;
 
 
 /*****************************************************************************/
@@ -70,6 +71,10 @@ void InitLiteralPool (void)
 {
     /* Get the pool label */
     LiteralPoolLabel = GetLocalLabel ();
+
+	/* clear pool */
+	ResetMinimum = 0;
+	ResetLiteralPoolOffs (0);
 }
 
 
@@ -125,6 +130,11 @@ void ResetLiteralPoolOffs (unsigned Offs
  */
 {
     CHECK (Offs <= SB_GetLen (&LiteralPool));
+
+	/* Disallow attempts to delete a duplicate string (this happens in StdFunc_strlen) */
+	if (Offs < ResetMinimum)
+		return;
+
     SB_Cut (&LiteralPool, Offs);
 }
 
@@ -182,4 +192,41 @@ void PrintLiteralPoolStats (FILE* F)
 }
 
 
+
+unsigned RemoveDuplicateLiteral (unsigned Offs)
+/* Compares the literal starting at Offs and extending to the end of the buffer
+ * with the rest of the buffer. If an exact duplicate is found, it returns the offset
+ * of the duplicate and cuts the buffer. If no duplicate, it returns the input.
+ */
+{
+	if (StringMerge && IS_Get (&WritableStrings) == 0) {
+		/* Search for duplicate */
+
+		char* Buf = SB_GetConstBuf (&LiteralPool);
+		char *S = Buf+Offs;
+		unsigned BufSize = SB_GetLen (&LiteralPool);
+		unsigned SourceSize = BufSize - Offs;
+
+	    CHECK (Offs < BufSize);
+
+		if (Offs >= SourceSize) {
+			unsigned i;
+			for (i=0; i <= Offs-SourceSize; i++) {
+				if (!memcmp (S, &Buf[i], SourceSize)) {
+
+					/* Delete new string */
+					ResetLiteralPoolOffs (Offs);
+
+					/* Prevent deletion of duplicate */
+					ResetMinimum = Offs;
+
+					return i;
+				}
+			}
+		}
+	}
+
+	/* No duplicate found; return input offset */
+    return Offs;
+}
 
diff -b -up cc65.org\litpool.h cc65\litpool.h
--- cc65.org\litpool.h	Sun Sep 09 16:49:20 2001
+++ cc65\litpool.h	Mon Jul 02 21:49:36 2007
@@ -99,6 +99,12 @@ void GetLiteralStrBuf (StrBuf* Target, u
 void PrintLiteralPoolStats (FILE* F);
 /* Print statistics about the literal space used */
 
+unsigned RemoveDuplicateLiteral (unsigned Offs);
+/* Compares the literal starting at Offs and extending to the end of the buffer
+ * with the rest of the buffer. If an exact duplicate is found, it returns the offset
+ * of the duplicate and cuts the buffer. If no duplicate, it returns the input.
+ */
+
 
 
 /* End of litpool.h */
diff -b -up cc65.org\loadexpr.c cc65\loadexpr.c
--- cc65.org\loadexpr.c	Thu Jun 10 04:48:02 2004
+++ cc65\loadexpr.c	Fri Jun 29 10:14:16 2007
@@ -39,6 +39,7 @@
 #include "exprdesc.h"
 #include "global.h"
 #include "loadexpr.h"
+#include "compile.h"
 
 
 
@@ -74,6 +75,7 @@ static void LoadConstant (unsigned Flags
 	     * allowed.
 	     */
 	    if (IS_Get (&AllowRegVarAddr) == 0) {
+			if (PassCount == 1)
 	     	Error ("Cannot take the address of a register variable");
 	    }
        	    g_getimmed ((Flags | CF_REGVAR) & ~CF_CONST, Expr->Name, Expr->IVal);
diff -b -up cc65.org\locals.c cc65\locals.c
--- cc65.org\locals.c	Sun Jan 09 14:03:56 2005
+++ cc65\locals.c	Wed Jul 04 13:07:36 2007
@@ -75,8 +75,14 @@ static unsigned ParseRegisterDecl (Decla
     unsigned Size = SizeOf (Decl->Type);
 
     /* Save the current contents of the register variable on stack */
+	if (!GetLeafFlag (F_GetFuncDesc (CurrentFunc))) {
     F_AllocLocalSpace (CurrentFunc);
+
+		if (UseHardwareStack)
+			g_save_regvars_hardwarestack (Reg, Size);
+		else
     g_save_regvars (Reg, Size);
+	}
 
     /* Check for an optional initialization */
     if (CurTok.Tok == TOK_ASSIGN) {
@@ -411,11 +417,17 @@ static void ParseOneDecl (const DeclSpec
     /* Handle anything that needs storage (no functions, no typdefs) */
     if ((SC & SC_FUNC) != SC_FUNC && (SC & SC_TYPEDEF) != SC_TYPEDEF) {
 
+        int Reg = 0;    /* Initialize to avoid gcc complains */
+
+		/* If leaf function, convert to register type */
+		if ((SC & SC_AUTO) == SC_AUTO && GetLeafFlag (F_GetFuncDesc (CurrentFunc))) {
+            SC = (SC & ~SC_AUTO) | SC_REGISTER;
+		}
+
         /* If we have a register variable, try to allocate a register and
          * convert the declaration to "auto" if this is not possible.
          */
-        int Reg = 0;    /* Initialize to avoid gcc complains */
-        if ((SC & SC_REGISTER) != 0 && (Reg = F_AllocRegVar (CurrentFunc, Decl.Type)) < 0) {
+        if ((SC & SC_REGISTER) != 0 && (Reg = AllocRegVar (F_GetFuncDesc (CurrentFunc), Decl.Type)) < 0) {
             /* No space for this register variable, convert to auto */
             SC = (SC & ~SC_REGISTER) | SC_AUTO;
         }
@@ -427,11 +439,16 @@ static void ParseOneDecl (const DeclSpec
        	} else if ((SC & SC_AUTO) == SC_AUTO) {
             /* Auto variable */
             SymData = ParseAutoDecl (&Decl, &SC);
-       	} else if ((SC & SC_STATIC) == SC_STATIC) {
+       	} else if ((SC & (SC_STATIC | SC_EXTERN)) == SC_STATIC) {
             /* Static variable */
             SymData = ParseStaticDecl (&Decl, &SC);
+       	} else if ((SC & (SC_STATIC | SC_EXTERN)) == (SC_STATIC | SC_EXTERN)) {
+            /* Extern variable */
+		    if (CurTok.Tok == TOK_ASSIGN) {
+				Error ("Can't initialize extern");
+			}
        	} else {
-            Internal ("Invalid storage class in ParseOneDecl: %04X", SC);
+            Internal ("Invalid storage class in ParseOneDecl: %08X", SC);
         }
 
         /* If the standard was not set explicitly to C89, print a warning
diff -b -up cc65.org\macrotab.c cc65\macrotab.c
--- cc65.org\macrotab.c	Sun Jul 24 18:14:42 2005
+++ cc65\macrotab.c	Thu Jun 21 21:29:54 2007
@@ -55,6 +55,7 @@
 /* The macro hash table */
 #define MACRO_TAB_SIZE	211
 static Macro* MacroTab[MACRO_TAB_SIZE];
+static Macro* MacroTabSnapshot[MACRO_TAB_SIZE];
 
 
 
@@ -305,3 +306,61 @@ void PrintMacroStats (FILE* F)
 
 
 
+static Macro* CloneMacro (Macro* M)
+{
+    unsigned I;
+    Macro* newM = NewMacro (M->Name);
+
+    /* Initialize the data */
+    newM->Expanding   = M->Expanding;
+    newM->ArgCount    = M->ArgCount;	/* Flag: Not a function like macro */
+    newM->MaxArgs	  = M->MaxArgs;
+    newM->Variadic    = M->Variadic;
+	SB_Copy (&newM->Replacement, &M->Replacement);
+
+    for (I = 0; I < CollCount (&M->FormalArgs); ++I) {
+	    CollAppend (&newM->FormalArgs, xstrdup (CollAtUnchecked (&M->FormalArgs, I)));
+	}
+
+    /* Return the new macro */
+    return newM;
+}
+
+
+void SnapshotMacros(void)
+{
+    unsigned I;
+    Macro* M;
+    Macro* newM;
+
+	memcpy (MacroTabSnapshot, MacroTab, sizeof MacroTabSnapshot);
+	memset (MacroTab, 0, sizeof MacroTab);
+
+    for (I = 0; I < MACRO_TAB_SIZE; ++I) {
+		M = MacroTabSnapshot [I];
+		while (M) {
+	     	newM = CloneMacro (M);
+			InsertMacro (newM);
+			M = M->Next;
+		}
+    }
+}
+
+
+
+void RestoreMacros(void)
+{
+    unsigned I;
+    Macro* M;
+
+    for (I = 0; I < MACRO_TAB_SIZE; ++I) {
+		M = MacroTab [I];
+		while (M) {
+			Macro* t = M;
+			M = M->Next;
+	     	FreeMacro (t);
+		}
+    }
+
+	memcpy (MacroTab, MacroTabSnapshot, sizeof MacroTab);
+}
diff -b -up cc65.org\macrotab.h cc65\macrotab.h
--- cc65.org\macrotab.h	Sun Jul 24 18:14:42 2005
+++ cc65\macrotab.h	Thu Jun 21 21:20:50 2007
@@ -70,6 +70,8 @@ struct Macro {
 /*   	    	 	   	     Code	    			     */
 /*****************************************************************************/
 
+void SnapshotMacros(void);
+void RestoreMacros(void);
 
 
 Macro* NewMacro (const char* Name);
diff -b -up cc65.org\main.c cc65\main.c
--- cc65.org\main.c	Wed Aug 31 17:48:08 2005
+++ cc65\main.c	Wed Jul 04 06:23:10 2007
@@ -114,9 +114,13 @@ static void Usage (void)
             "  --debug-opt name\tDebug optimization steps\n"
             "  --disable-opt name\tDisable an optimization step\n"
             "  --enable-opt name\tEnable an optimization step\n"
+            "  --fastcall\t\tUse fastcall calling convention for static functions\n"
             "  --forget-inc-paths\tForget include search paths\n"
+            "  --hardware-stack\tUse hardware stack for saving register variables\n"
             "  --help\t\tHelp (this text)\n"
             "  --include-dir dir\tSet an include directory search path\n"
+            "  --leaf\t\tEnable leaf function optimization\n"
+            "  --leaf-space b\tSet space available for leaf function optimization\n"
             "  --list-opt-steps\tList all optimizer steps and exit\n"
             "  --memory-model model\tSet the memory model\n"
             "  --register-space b\tSet space available for register variables\n"
@@ -125,6 +129,8 @@ static void Usage (void)
             "  --signed-chars\tDefault characters are signed\n"
             "  --standard std\tLanguage standard (c89, c99, cc65)\n"
             "  --static-locals\tMake local variables static\n"
+            "  --static-params\tUse static locations for parameter passing\n"
+            "  --string-merge\tMerge identical string literals\n"
             "  --target sys\t\tSet the target system\n"
             "  --verbose\t\tIncrease verbosity\n"
             "  --version\t\tPrint the compiler version number\n"
@@ -592,6 +598,17 @@ static void OptRegisterSpace (const char
 
 
 
+static void OptLeafRegisterSpace (const char* Opt, const char* Arg)
+/* Handle the --leaf-space option */
+{
+    /* Numeric argument expected */
+    if (sscanf (Arg, "%u", &LeafRegisterSpace) != 1 || LeafRegisterSpace > 256) {
+       	AbEnd ("Argument for option %s is invalid", Opt);
+    }
+}
+
+
+
 static void OptRegisterVars (const char* Opt attribute ((unused)),
                              const char* Arg attribute ((unused)))
 /* Handle the --register-vars option */
@@ -684,6 +701,51 @@ static void OptWritableStrings (const ch
 
 
 
+static void OptLeaf (const char* Opt attribute ((unused)),
+	       		        const char* Arg attribute ((unused)))
+/* Enable leaf function optimization */
+{
+	LeafOptimization = 1;
+}
+
+
+
+static void OptHardwareStack (const char* Opt attribute ((unused)),
+	       		        const char* Arg attribute ((unused)))
+/* Use hardware stack */
+{
+	UseHardwareStack = 1;
+}
+
+
+
+static void OptFastcall (const char* Opt attribute ((unused)),
+	       		        const char* Arg attribute ((unused)))
+/* Enable automatic fastcall */
+{
+	AutoFastcall = 1;
+}
+
+
+
+static void OptStaticParams (const char* Opt attribute ((unused)),
+	       		        const char* Arg attribute ((unused)))
+/* Enable automatic fastcall */
+{
+	StaticParams = 1;
+}
+
+
+
+static void OptStringMerge (const char* Opt attribute ((unused)),
+	       		        const char* Arg attribute ((unused)))
+/* Enable string merge */
+{
+	StringMerge = 1;
+}
+
+
+
 int main (int argc, char* argv[])
 {
     /* Program long options */
@@ -701,9 +763,13 @@ int main (int argc, char* argv[])
         { "--debug-opt",        1,      OptDebugOpt             },
 	{ "--disable-opt",	1,	OptDisableOpt		},
 	{ "--enable-opt",	1,	OptEnableOpt  	       	},
+       	{ "--fastcall",	0,     	OptFastcall      },
        	{ "--forget-inc-paths",	0,     	OptForgetIncPaths       },
+       	{ "--hardware-stack",	0,     	OptHardwareStack      },
 	{ "--help",	 	0, 	OptHelp	     		},
 	{ "--include-dir",     	1,   	OptIncludeDir		},
+       	{ "--leaf",	0,     	OptLeaf      },
+        { "--leaf-space",   1,      OptLeafRegisterSpace        },
 	{ "--list-opt-steps",   0,      OptListOptSteps         },
         { "--memory-model",     1,      OptMemoryModel          },
         { "--register-space",   1,      OptRegisterSpace        },
@@ -712,6 +778,8 @@ int main (int argc, char* argv[])
 	{ "--signed-chars",	0, 	OptSignedChars	       	},
         { "--standard",         1,      OptStandard             },
        	{ "--static-locals",   	0, 	OptStaticLocals	       	},
+       	{ "--static-params",	0,     	OptStaticParams      },
+       	{ "--string-merge",	0,     	OptStringMerge      },
 	{ "--target",	  	1,  	OptTarget    	       	},
 	{ "--verbose",	       	0, 	OptVerbose   	       	},
 	{ "--version",	       	0,	OptVersion   	       	},
Common subdirectories: cc65.org\make and cc65\make
diff -b -up cc65.org\pragma.c cc65\pragma.c
--- cc65.org\pragma.c	Tue Jun 15 17:05:40 2004
+++ cc65\pragma.c	Fri Jun 29 13:41:34 2007
@@ -50,7 +50,7 @@
 #include "scanstrbuf.h"
 #include "symtab.h"
 #include "pragma.h"
-
+#include "compile.h"
 
 
 /*****************************************************************************/
diff -b -up cc65.org\segments.c cc65\segments.c
--- cc65.org\segments.c	Mon Mar 08 18:33:28 2004
+++ cc65\segments.c	Fri Jun 22 10:21:28 2007
@@ -69,6 +69,7 @@ Segments* GS = 0;
 
 /* Actual names for the segments */
 static StrStack SegmentNames[SEG_COUNT];
+static StrStack SegmentNamesSnapshot[SEG_COUNT];
 
 /* We're using a collection for the stack instead of a linked list. Since
  * functions may not be nested (at least in the current implementation), the
@@ -82,6 +83,66 @@ static Collection SegmentStack = STATIC_
 /*****************************************************************************/
 /*  		    		     Code				     */
 /*****************************************************************************/
+
+
+void InitSegments(void)
+/* initialize segment stack */
+{
+	CS = 0;
+	GS = 0;
+	InitCollection (&SegmentStack);
+}
+
+
+static void SS_Clone (StrStack* D, const StrStack* S)
+/* Clone a StrStack. Should be moved to strstack.c */
+{
+	unsigned I;
+
+	D->Count = S->Count;
+
+	for (I=0; I < S->Count; I++)
+	{
+		D->Stack[I] = xstrdup (S->Stack[I]);
+	}
+}
+
+
+void SnapshotSegNames(void)
+/* Take a snapshot of current segment names */
+{
+	unsigned I;
+
+	for (I=0; I < SEG_COUNT; I++)
+	{
+		SS_Clone (&SegmentNamesSnapshot[I], &SegmentNames[I]);
+	}
+}
+
+
+void FreeSegNames (void)
+/* free current segment names */
+{
+	unsigned I;
+	for (I=0; I < SEG_COUNT; I++)
+	{
+		unsigned S;
+		for (S=0; S < SegmentNames[I].Count; S++)
+		{
+			xfree (SegmentNames[I].Stack[S]);
+		}
+	}
+}
+
+
+
+void RestoreSegNames(void)
+/* restore segment name snapshot */
+{
+	FreeSegNames ();
+
+	memcpy (SegmentNames, SegmentNamesSnapshot, sizeof SegmentNames);
+}
 
 
 
diff -b -up cc65.org\segments.h cc65\segments.h
--- cc65.org\segments.h	Mon Mar 08 18:33:28 2004
+++ cc65\segments.h	Fri Jun 22 10:22:16 2007
@@ -100,7 +100,17 @@ extern Segments* GS;
 /*		  	    	     Code				     */
 /*****************************************************************************/
 
+void InitSegments(void);
+/* initialize segment stack */
 
+void SnapshotSegNames(void);
+/* Take a snapshot of current segment names */
+
+void FreeSegNames (void);
+/* free current segment names */
+
+void RestoreSegNames(void);
+/* restore segment name snapshot */
 
 void InitSegNames (void);
 /* Initialize the segment names */
diff -b -up cc65.org\symentry.c cc65\symentry.c
--- cc65.org\symentry.c	Sun Feb 19 08:29:38 2006
+++ cc65\symentry.c	Tue Jul 10 14:40:14 2007
@@ -37,11 +37,12 @@
 
 /* common */
 #include "xmalloc.h"
+#include "check.h"
 
 /* cc65 */
 #include "anonname.h"
 #include "symentry.h"
-
+#include "asmlabel.h"
 
 
 /*****************************************************************************/
@@ -133,7 +134,7 @@ void DumpSymEntry (FILE* F, const SymEnt
      	}
     }
     if (SymFlags != 0) {
-	fprintf (F, "%04X", SymFlags);
+	fprintf (F, "%08X", SymFlags);
     }
     fprintf (F, "\n");
 
@@ -152,11 +153,67 @@ void DumpSymEntry (FILE* F, const SymEnt
 void CvtRegVarToAuto (SymEntry* Sym)
 /* Convert a register variable to an auto variable */
 {
+	PRECONDITION (Sym->Flags & SC_REGISTER);
+
     /* Change the storage class */
     Sym->Flags = (Sym->Flags & ~(SC_REGISTER | SC_STATIC | SC_EXTERN)) | SC_AUTO;
 
     /* Transfer the stack offset from register save area to actual offset */
     Sym->V.Offs = Sym->V.R.SaveOffs;
+
+	/* set asm name */
+	ChangeAsmName (Sym, LocalLabelName (Sym->V.Offs));
+}
+
+
+
+void CvtAutoToRegVar (SymEntry* Sym)
+/* Convert an auto variable to a register variable */
+{
+	PRECONDITION (Sym->Flags & SC_AUTO);
+
+    /* Change the storage class */
+    Sym->Flags = (Sym->Flags & ~(SC_AUTO | SC_STATIC | SC_EXTERN)) | SC_REGISTER;
+
+    /* Transfer the stack offset to register save area */
+    Sym->V.R.SaveOffs = Sym->V.Offs;
+
+	/* set asm name */
+	ChangeAsmName (Sym, LocalLabelName (Sym->V.R.SaveOffs));
+}
+
+
+
+void CvtRegVarToStatic (SymEntry* Sym)
+/* Convert a register variable to a static variable */
+{
+	PRECONDITION (Sym->Flags & SC_REGISTER);
+
+    /* Change the storage class */
+    Sym->Flags = (Sym->Flags & ~(SC_REGISTER | SC_AUTO | SC_EXTERN)) | SC_STATIC;
+
+	/* get a unique label number for this static */
+	Sym->V.Label = GetLocalLabel ();
+
+	/* set asm name */
+	ChangeAsmName (Sym, LocalLabelName (Sym->V.Label));
+}
+
+
+
+void CvtAutoVarToStatic (SymEntry* Sym)
+/* Convert an auto variable to a static variable */
+{
+	PRECONDITION (Sym->Flags & SC_AUTO);
+
+    /* Change the storage class */
+    Sym->Flags = (Sym->Flags & ~(SC_REGISTER | SC_AUTO | SC_EXTERN)) | SC_STATIC;
+
+	/* get a unique label number for this static */
+	Sym->V.Label = GetLocalLabel ();
+
+	/* set asm name */
+	ChangeAsmName (Sym, LocalLabelName (Sym->V.Label));
 }
 
 
diff -b -up cc65.org\symentry.h cc65\symentry.h
--- cc65.org\symentry.h	Sun Feb 19 08:29:38 2006
+++ cc65\symentry.h	Tue Jul 10 14:41:50 2007
@@ -118,6 +118,7 @@ struct SymEntry {
         struct {
             int                 RegOffs;
             int                 SaveOffs;
+            unsigned            Label;	/* label name for static parameter passing */
         } R;
 
        	/* Value for constants (including enums) */
@@ -209,6 +210,15 @@ INLINE const char* SymGetAsmName (const 
 
 void CvtRegVarToAuto (SymEntry* Sym);
 /* Convert a register variable to an auto variable */
+
+void CvtAutoToRegVar (SymEntry* Sym);
+/* Convert an auto variable to a register variable */
+
+void CvtRegVarToStatic (SymEntry* Sym);
+/* Convert a register variable to a static variable */
+
+void CvtAutoVarToStatic (SymEntry* Sym);
+/* Convert an auto variable to a static variable */
 
 void ChangeSymType (SymEntry* Entry, Type* T);
 /* Change the type of the given symbol */
diff -b -up cc65.org\symtab.c cc65\symtab.c
--- cc65.org\symtab.c	Sun Feb 19 08:29:38 2006
+++ cc65\symtab.c	Mon Jul 09 10:03:54 2007
@@ -57,6 +57,9 @@
 #include "symentry.h"
 #include "typecmp.h"
 #include "symtab.h"
+#include "funcremember.h"
+#include "compile.h"
+#include "function.h"
 
 
 
@@ -229,12 +232,6 @@ void LeaveGlobalLevel (void)
     /* Check the tables */
     CheckSymTable (SymTab0);
 
-    /* Dump the tables if requested */
-    if (Debug) {
-     	PrintSymTable (SymTab0, stdout, "Global symbol table");
-     	PrintSymTable (TagTab0, stdout, "Global tag table");
-    }
-
     /* Don't delete the symbol and struct tables! */
     SymTab = 0;
     TagTab = 0;
@@ -674,10 +671,16 @@ SymEntry* AddLocalSym (const char* Name,
         } else if ((Flags & SC_REGISTER) == SC_REGISTER) {
             Entry->V.R.RegOffs  = Offs;
             Entry->V.R.SaveOffs = StackPtr;
-        } else if ((Flags & SC_STATIC) == SC_STATIC) {
+        } else if ((Flags & (SC_STATIC | SC_EXTERN)) == SC_STATIC) {
             /* Generate the assembler name from the label number */
             Entry->V.Label = Offs;
             Entry->AsmName = xstrdup (LocalLabelName (Entry->V.Label));
+        } else if ((Flags & (SC_STATIC | SC_EXTERN)) == (SC_STATIC | SC_EXTERN)) {
+			/* Add the assembler name of the symbol */
+			unsigned Len = strlen (Name);
+			Entry->AsmName = xmalloc (Len + 2);
+			Entry->AsmName[0] = '_';
+			memcpy (Entry->AsmName+1, Name, Len+1);
         } else if ((Flags & SC_STRUCTFIELD) == SC_STRUCTFIELD) {
             Entry->V.Offs = Offs;
         } else {
@@ -716,6 +719,27 @@ SymEntry* AddGlobalSym (const char* Name
      	    return Entry;
      	}
 
+		/* If pass 2, and a function using static params, copy the static params
+		 * from a previous function call. We need to do this because the function call
+		 * used unique numeric labels which can't be regenerated later, and obviously
+		 * the function calls and function definition must use the same labels.
+		 */
+		if (PassCount > 1 && IsFunc && IsTypeFunc (Entry->Type)) {
+			FuncDesc* FD = GetFuncDesc (T);
+			FuncDesc* OldFD = GetFuncDesc (Entry->Type);
+
+			if (OldFD->Flags & FD_STATICPARAMS) {
+
+				CopyStaticParams (FD, OldFD, Name);
+			}
+
+			/* Copy fastcall flag if it might have been set by AutoFastcall */
+			if (AutoFastcall && (OldFD->Flags & FD_FASTCALL)) {
+				FD->Flags |= FD_FASTCALL;
+				AssignStackOffsetsToParams (FD);
+			}
+		}
+
     	/* Get the type string of the existing symbol */
     	EType = Entry->Type;
 
@@ -756,6 +780,13 @@ SymEntry* AddGlobalSym (const char* Name
 	    if (IsFunc) {
 		/* Get the function descriptor from the new type */
 		FuncDesc* F = GetFuncDesc (T);
+
+		/* Attach an existing FuncRemember to the new FuncDesc and update flags.
+		 * Note: Could instead simply copy Pass2 from the old FuncDesc, but don't
+		 * forget to update the flags, too.
+		 */
+		F->Pass2 = AddFuncRemember (Name, Flags, F->Flags);
+
 		/* Use this new function descriptor */
 		Entry->V.F.Func = F;
 		SetFuncDesc (EType, F);
@@ -781,6 +812,9 @@ SymEntry* AddGlobalSym (const char* Name
 	if (IsFunc) {
 	    Entry->V.F.Func = GetFuncDesc (Entry->Type);
 	    Entry->V.F.Seg  = 0;
+
+		/* Create (or in pass 2, find) a FuncRemember and attach to FuncDesc */
+		Entry->V.F.Func->Pass2 = AddFuncRemember (Name, Flags, Entry->V.F.Func->Flags);
 	}
 
         /* Add the assembler name of the symbol */
@@ -837,8 +871,12 @@ void MakeZPSym (const char* Name)
 
     /* Mark the symbol as zeropage */
     if (Entry) {
+		if (Entry->Flags & SC_EXTERN) {
 	Entry->Flags |= SC_ZEROPAGE;
     } else {
+			Error ("Zero page symbol not extern: `%s'", Name);
+		}
+    } else {
      	Error ("Undefined symbol: `%s'", Name);
     }
 }
@@ -876,6 +914,15 @@ void PrintSymTable (const SymTable* Tab,
      	}
     }
     fprintf (F, "\n\n\n");
+}
+
+
+
+void PrintGlobalSymTables (FILE* F)
+/* Print the global sym and tag tables */
+{
+    PrintSymTable (SymTab0, F, "Global symbol table");
+    PrintSymTable (TagTab0, F, "Global tag table");
 }
 
 
diff -b -up cc65.org\symtab.h cc65\symtab.h
--- cc65.org\symtab.h	Sun Feb 19 08:29:38 2006
+++ cc65\symtab.h	Wed Jul 04 13:46:32 2007
@@ -182,6 +182,9 @@ void MakeZPSym (const char* Name);
 void PrintSymTable (const SymTable* Tab, FILE* F, const char* Header, ...);
 /* Write the symbol table to the given file */
 
+void PrintGlobalSymTables (FILE* F);
+/* Print the global sym and tag tables */
+
 void EmitExternals (void);
 /* Write import/export statements for external symbols */
 
/*****************************************************************************/
/*                                                                           */
/*				  funcremember.h	                        			     */
/*                                                                           */
/*	       Remember function data in pass 1 for use in pass 2          	     */
/*                                                                           */
/*                                                                           */
/*                                                                           */
/* (C) 2000-2005, Ullrich von Bassewitz                                      */
/*                Rmerstrae 52                                             */
/*                D-70794 Filderstadt                                        */
/* EMail:         uz@cc65.org                                                */
/*                                                                           */
/*                                                                           */
/* This software is provided 'as-is', without any expressed or implied       */
/* warranty.  In no event will the authors be held liable for any damages    */
/* arising from the use of this software.                                    */
/*                                                                           */
/* Permission is granted to anyone to use this software for any purpose,     */
/* including commercial applications, and to alter it and redistribute it    */
/* freely, subject to the following restrictions:                            */
/*                                                                           */
/* 1. The origin of this software must not be misrepresented; you must not   */
/*    claim that you wrote the original software. If you use this software   */
/*    in a product, an acknowledgment in the product documentation would be  */
/*    appreciated but is not required.                                       */
/* 2. Altered source versions must be plainly marked as such, and must not   */
/*    be misrepresented as being the original software.                      */
/* 3. This notice may not be removed or altered from any source              */
/*    distribution.                                                          */
/*                                                                           */
/*****************************************************************************/



#ifndef FUNCREMEMBER_H
#define FUNCREMEMBER_H

#include <stdio.h>

/* common */
#include "inline.h"



/*****************************************************************************/
/*   		 		     data				     */
/*****************************************************************************/



/* Structure describing a function */
typedef struct FuncRemember FuncRemember;
struct FuncRemember {
    FuncRemember*	Next;	        /* Next function with same hash value */
	unsigned		Flags;
    char			Name[1];   	/* Name, dynamically allocated */
};

/* Flags */
#define FR_LEAF	1	/* function is leaf (calls no functions) */
#define FR_ADDRESSTAKEN	2	/* function had its address taken (might be target of indirect call) */
#define FR_EXTERN	4	/* copy of SC_EXTERN */
#define FR_VARIADIC	8	/* copy of FD_VARIADIC */

/* True if standard calling convention must be used */
#define FR_STDCALL (FR_ADDRESSTAKEN | FR_EXTERN | FR_VARIADIC)

/*****************************************************************************/
/*   	    	 	   	     Code	    			     */
/*****************************************************************************/

FuncRemember* NewFuncRemember (const char* Name);
/* Allocate a FuncRemember structure with the given name. The structure is not
 * inserted into the FuncRemember table.
 */

void FreeFuncRemember (FuncRemember* M);
/* Delete a function definition. The function will NOT remove the FuncRemember from the
 * table, use UndefineFuncRemember for that.
 */

void InsertFuncRemember (FuncRemember* M);
/* Insert the given FuncRemember into the FuncTab table. */

int UndefineFuncRemember (const char* Name);
/* Search for the FuncRemember with the given name and remove it from the FuncRemember
 * table if it exists. Return 1 if a FuncRemember was found and deleted, return
 * 0 otherwise.
 */

FuncRemember* FindFuncRemember (const char* Name);
/* Find a FuncRemember with the given name. Return the FuncRemember definition or NULL */

FuncRemember* AddFuncRemember (const char* Name, unsigned SymFlags, unsigned FuncFlags);
/* Add a FuncRemember with the given name or return an existing FuncRemember with
 * the same name.
 */

void FreeAllFuncRemember(void);
/* Free all FuncRemember entries in table */

void PrintFuncRememberStats (FILE* F);
/* Print FuncRemember statistics to the given text file. */

void SetFuncRememberFlags (FuncRemember* FR, unsigned Flags);
/* Set FuncRemember flags (pass 1 only) */

void ClearFuncRememberFlags (FuncRemember* FR, unsigned Flags);
/* Clear FuncRemember flags (pass 1 only) */

unsigned GetFuncRememberFlags (FuncRemember* FR);
/* Get FuncRemember flags (pass 2 only) */



/* End of funcremember.h */
#endif



/*****************************************************************************/
/*                                                                           */
/*				  funcremember.c                           				     */
/*                                                                           */
/*	       Remember function data in pass 1 for use in pass 2          	     */
/*                                                                           */
/*                                                                           */
/*                                                                           */
/* (C) 2000-2005, Ullrich von Bassewitz                                      */
/*                Rmerstrae 52                                             */
/*                D-70794 Filderstadt                                        */
/* EMail:         uz@cc65.org                                                */
/*                                                                           */
/*                                                                           */
/* This software is provided 'as-is', without any expressed or implied       */
/* warranty.  In no event will the authors be held liable for any damages    */
/* arising from the use of this software.                                    */
/*                                                                           */
/* Permission is granted to anyone to use this software for any purpose,     */
/* including commercial applications, and to alter it and redistribute it    */
/* freely, subject to the following restrictions:                            */
/*                                                                           */
/* 1. The origin of this software must not be misrepresented; you must not   */
/*    claim that you wrote the original software. If you use this software   */
/*    in a product, an acknowledgment in the product documentation would be  */
/*    appreciated but is not required.                                       */
/* 2. Altered source versions must be plainly marked as such, and must not   */
/*    be misrepresented as being the original software.                      */
/* 3. This notice may not be removed or altered from any source              */
/*    distribution.                                                          */
/*                                                                           */
/*****************************************************************************/



#include <stdio.h>
#include <string.h>

/* common */
#include "hashstr.h"
#include "xmalloc.h"

/* cc65 */
#include "error.h"
#include "funcremember.h"
#include "symentry.h"
#include "compile.h"
#include "check.h"



/*****************************************************************************/
/*				     data				     */
/*****************************************************************************/



/* The function hash table */
#define FUNCTION_TAB_SIZE	211
static FuncRemember* FuncTab[FUNCTION_TAB_SIZE];



/*****************************************************************************/
/*	   		   	     code				     */
/*****************************************************************************/



FuncRemember* NewFuncRemember (const char* Name)
/* Allocate a FuncRemember structure with the given name. The structure is not
 * inserted into the FuncRemember table.
 */
{
    /* Get the length of the FuncRemember name */
    unsigned Len = strlen(Name);

    /* Allocate the structure */
    FuncRemember* M = (FuncRemember*) xmalloc (sizeof(FuncRemember) + Len);

    /* Initialize the data */
    memcpy (M->Name, Name, Len+1);
	M->Flags = 0;

    /* Return the new FuncRemember */
    return M;
}



void FreeFuncRemember (FuncRemember* M)
/* Delete a function definition. The function will NOT remove the FuncRemember from the
 * table, use UndefineFuncRemember for that.
 */
{
    xfree (M);
}



void InsertFuncRemember (FuncRemember* M)
/* Insert the given FuncRemember into the FuncTab table. */
{
    /* Get the hash value of the FuncRemember name */
    unsigned Hash = HashStr (M->Name) % FUNCTION_TAB_SIZE;

    /* Insert the FuncRemember */
    M->Next = FuncTab[Hash];
    FuncTab[Hash] = M;
}



int UndefineFuncRemember (const char* Name)
/* Search for the FuncRemember with the given name and remove it from the FuncRemember
 * table if it exists. Return 1 if a FuncRemember was found and deleted, return
 * 0 otherwise.
 */
{
    /* Get the hash value of the FuncRemember name */
    unsigned Hash = HashStr (Name) % FUNCTION_TAB_SIZE;

    /* Search the hash chain */
    FuncRemember* L = 0;
    FuncRemember* M = FuncTab[Hash];
    while (M) {
	if (strcmp (M->Name, Name) == 0) {

	    /* Found it */
	    if (L == 0) {
	       	/* First in chain */
	       	FuncTab[Hash] = M->Next;
	    } else {
	       	L->Next = M->Next;
	    }

	    /* Delete the FuncRemember */
	    FreeFuncRemember (M);

	    /* Done */
	    return 1;
	}

	/* Next FuncRemember */
	L = M;
	M = M->Next;
    }

    /* Not found */
    return 0;
}



FuncRemember* FindFuncRemember (const char* Name)
/* Find a FuncRemember with the given name. Return the FuncRemember definition or NULL */
{
    /* Get the hash value of the FuncRemember name */
    unsigned Hash = HashStr (Name) % FUNCTION_TAB_SIZE;

    /* Search the hash chain */
    FuncRemember* M = FuncTab[Hash];
    while (M) {
	if (strcmp (M->Name, Name) == 0) {
	    /* Found it */
	    return M;
	}

	/* Next FuncRemember */
	M = M->Next;
    }

    /* Not found */
    return 0;
}



void FreeAllFuncRemember(void)
/* Free all FuncRemember entries in table */
{
    unsigned I;
    FuncRemember* M;

    for (I = 0; I < FUNCTION_TAB_SIZE; ++I) {
		M = FuncTab [I];
		while (M) {
	     	FreeFuncRemember (M);
			M = M->Next;
		}
    }
}



void PrintFuncRememberStats (FILE* F)
/* Print FuncRemember statistics to the given text file. */
{
    unsigned I;
    FuncRemember* M;

    fprintf (F, "\n\nFuncRemember Hash Table Summary\n");
    for (I = 0; I < FUNCTION_TAB_SIZE; ++I) {
       	fprintf (F, "%3u : ", I);
	M = FuncTab [I];
	if (M) {
	    while (M) {
			unsigned Flags = M->Flags;
	     	fprintf (F, "%s ", M->Name);
			if (Flags & FR_LEAF)
				fprintf (F, ", leaf");
			if (Flags & FR_ADDRESSTAKEN)
				fprintf (F, ", address taken");
			if (Flags & FR_EXTERN)
				fprintf (F, ", extern");
			if (Flags & FR_VARIADIC)
				fprintf (F, ", variadic");
			M = M->Next;
	    }
	    fprintf (F, "\n");
	} else {
	    fprintf (F, "empty\n");
	}
    }
}



void SetFuncRememberFlags (FuncRemember* FR, unsigned Flags)
/* Set FuncRemember flags (pass 1 only) */
{
	PRECONDITION (PassCount == 1);

	FR->Flags |= Flags;
}



void ClearFuncRememberFlags (FuncRemember* FR, unsigned Flags)
/* Clear FuncRemember flags (pass 1 only) */
{
	PRECONDITION (PassCount == 1);

	FR->Flags &= ~Flags;
}



unsigned GetFuncRememberFlags (FuncRemember* FR)
/* Get FuncRemember flags (pass 2 only) */
{
	PRECONDITION (PassCount > 1);

	return FR->Flags;
}



FuncRemember* AddFuncRemember (const char* Name, unsigned SymFlags, unsigned FuncFlags)
/* Add a FuncRemember with the given name or return an existing FuncRemember with
 * the same name.
 */
{
	FuncRemember* F = FindFuncRemember (Name);

	if (PassCount == 1) {
		if (!F) {
			F = NewFuncRemember (Name);
			InsertFuncRemember (F);
		}

		if (SymFlags & SC_EXTERN)
			SetFuncRememberFlags (F, FR_EXTERN);

		if (FuncFlags & FD_VARIADIC)
			SetFuncRememberFlags (F, FR_VARIADIC);

	} else {
		if (!F) {
			Internal ("AddFuncRemember: %s not found", Name);
		}
	}

	return F;
}



