Index: EcnlProtoTool/trunk/tcc-0.9.27/i386-asm.c
===================================================================
--- EcnlProtoTool/trunk/tcc-0.9.26/i386-asm.c	(revision 321)
+++ EcnlProtoTool/trunk/tcc-0.9.27/i386-asm.c	(revision 331)
@@ -22,30 +22,34 @@
 #include "tcc.h"
 
-// #define NB_ASM_REGS 8
 #define MAX_OPERANDS 3
-#define NB_SAVED_REGS 3
 
 #define TOK_ASM_first TOK_ASM_clc
 #define TOK_ASM_last TOK_ASM_emms
-
-#define OPC_JMP        0x01  /* jmp operand */
-#define OPC_B          0x02  /* only used with OPC_WL */
-#define OPC_WL         0x04  /* accepts w, l or no suffix */
+#define TOK_ASM_alllast TOK_ASM_subps
+
+#define OPC_B          0x01  /* only used with OPC_WL */
+#define OPC_WL         0x02  /* accepts w, l or no suffix */
 #define OPC_BWL        (OPC_B | OPC_WL) /* accepts b, w, l or no suffix */
-#define OPC_REG        0x08 /* register is added to opcode */
-#define OPC_MODRM      0x10 /* modrm encoding */
-#define OPC_FWAIT      0x20 /* add fwait opcode */
-#define OPC_TEST       0x40 /* test opcodes */
-#define OPC_SHIFT      0x80 /* shift opcodes */
-#define OPC_D16      0x0100 /* generate data16 prefix */
-#define OPC_ARITH    0x0200 /* arithmetic opcodes */
-#define OPC_SHORTJMP 0x0400 /* short jmp operand */
-#define OPC_FARITH   0x0800 /* FPU arithmetic opcodes */
+#define OPC_REG        0x04 /* register is added to opcode */
+#define OPC_MODRM      0x08 /* modrm encoding */
+
+#define OPCT_MASK      0x70
+#define OPC_FWAIT      0x10 /* add fwait opcode */
+#define OPC_SHIFT      0x20 /* shift opcodes */
+#define OPC_ARITH      0x30 /* arithmetic opcodes */
+#define OPC_FARITH     0x40 /* FPU arithmetic opcodes */
+#define OPC_TEST       0x50 /* test opcodes */
+#define OPCT_IS(v,i) (((v) & OPCT_MASK) == (i))
+
+#define OPC_0F        0x100 /* Is secondary map (0x0f prefix) */
+#define OPC_48        0x200 /* Always has REX prefix */
 #ifdef TCC_TARGET_X86_64
 # define OPC_WLQ     0x1000  /* accepts w, l, q or no suffix */
 # define OPC_BWLQ    (OPC_B | OPC_WLQ) /* accepts b, w, l, q or no suffix */
 # define OPC_WLX     OPC_WLQ
+# define OPC_BWLX    OPC_BWLQ
 #else
 # define OPC_WLX     OPC_WL
+# define OPC_BWLX    OPC_BWL
 #endif
 
@@ -68,4 +72,8 @@
     OPT_SEG,
     OPT_ST,
+#ifdef TCC_TARGET_X86_64
+    OPT_REG8_LOW, /* %spl,%bpl,%sil,%dil, encoded like ah,ch,dh,bh, but
+		     with REX prefix, not used in insn templates */
+#endif
     OPT_IM8,
     OPT_IM8S,
@@ -83,11 +91,11 @@
     /* composite types */
     OPT_COMPOSITE_FIRST,
-    OPT_IM,     /* IM8 | IM16 | IM32 | IM64 */
+    OPT_IM,     /* IM8 | IM16 | IM32 */
     OPT_REG,    /* REG8 | REG16 | REG32 | REG64 */
     OPT_REGW,   /* REG16 | REG32 | REG64 */
-    OPT_IMW,    /* IM16 | IM32 | IM64 */
-#ifdef TCC_TARGET_X86_64
-    OPT_IMNO64, /* IM16 | IM32 */
-#endif
+    OPT_IMW,    /* IM16 | IM32 */
+    OPT_MMXSSE, /* MMX | SSE */
+    OPT_DISP,   /* Like OPT_ADDR, but emitted as displacement (for jumps) */
+    OPT_DISP8,  /* Like OPT_ADDR, but only 8bit (short jumps) */
     /* can be ored with any OPT_xxx */
     OPT_EA = 0x80
@@ -115,9 +123,13 @@
 #define OP_INDIR  (1 << OPT_INDIR)
 #ifdef TCC_TARGET_X86_64
-# define OP_REG64  (1 << OPT_REG64)
-# define OP_IM64   (1 << OPT_IM64)
+# define OP_REG64 (1 << OPT_REG64)
+# define OP_REG8_LOW (1 << OPT_REG8_LOW)
+# define OP_IM64  (1 << OPT_IM64)
+# define OP_EA32  (OP_EA << 1)
 #else
 # define OP_REG64 0
+# define OP_REG8_LOW 0
 # define OP_IM64  0
+# define OP_EA32  0
 #endif
 
@@ -126,10 +138,8 @@
 
 #ifdef TCC_TARGET_X86_64
-# define OP_IM      OP_IM64
 # define TREG_XAX   TREG_RAX
 # define TREG_XCX   TREG_RCX
 # define TREG_XDX   TREG_RDX
 #else
-# define OP_IM      OP_IM32
 # define TREG_XAX   TREG_EAX
 # define TREG_XCX   TREG_ECX
@@ -211,9 +221,13 @@
 static const ASMInstr asm_instrs[] = {
 #define ALT(x) x
+/* This removes a 0x0f in the second byte */
+#define O(o) ((uint64_t) ((((o) & 0xff00) == 0x0f00) ? ((((o) >> 8) & ~0xff) | ((o) & 0xff)) : (o)))
+/* This constructs instr_type from opcode, type and group.  */
+#define T(o,i,g) ((i) | ((g) << OPC_GROUP_SHIFT) | ((((o) & 0xff00) == 0x0f00) ? OPC_0F : 0))
 #define DEF_ASM_OP0(name, opcode)
-#define DEF_ASM_OP0L(name, opcode, group, instr_type) { TOK_ASM_ ## name, opcode, (instr_type | group << OPC_GROUP_SHIFT), 0 },
-#define DEF_ASM_OP1(name, opcode, group, instr_type, op0) { TOK_ASM_ ## name, opcode, (instr_type | group << OPC_GROUP_SHIFT), 1, { op0 }},
-#define DEF_ASM_OP2(name, opcode, group, instr_type, op0, op1) { TOK_ASM_ ## name, opcode, (instr_type | group << OPC_GROUP_SHIFT), 2, { op0, op1 }},
-#define DEF_ASM_OP3(name, opcode, group, instr_type, op0, op1, op2) { TOK_ASM_ ## name, opcode, (instr_type | group << OPC_GROUP_SHIFT), 3, { op0, op1, op2 }},
+#define DEF_ASM_OP0L(name, opcode, group, instr_type) { TOK_ASM_ ## name, O(opcode), T(opcode, instr_type, group), 0, { 0 } },
+#define DEF_ASM_OP1(name, opcode, group, instr_type, op0) { TOK_ASM_ ## name, O(opcode), T(opcode, instr_type, group), 1, { op0 }},
+#define DEF_ASM_OP2(name, opcode, group, instr_type, op0, op1) { TOK_ASM_ ## name, O(opcode), T(opcode, instr_type, group), 2, { op0, op1 }},
+#define DEF_ASM_OP3(name, opcode, group, instr_type, op0, op1, op2) { TOK_ASM_ ## name, O(opcode), T(opcode, instr_type, group), 3, { op0, op1, op2 }},
 #ifdef TCC_TARGET_X86_64
 # include "x86_64-asm.h"
@@ -242,8 +256,4 @@
 {
     int shift, v;
-#ifdef I386_ASM_16
-    if (s1->seg_size == 16)
-        tcc_error("invalid effective address");
-#endif
     v = asm_int_expr(s1);
     switch(v) {
@@ -268,7 +278,48 @@
 }
 
-static int asm_parse_reg(void)
+#ifdef TCC_TARGET_X86_64
+static int asm_parse_numeric_reg(int t, unsigned int *type)
+{
+    int reg = -1;
+    if (t >= TOK_IDENT && t < tok_ident) {
+	const char *s = table_ident[t - TOK_IDENT]->str;
+	char c;
+	*type = OP_REG64;
+	if (*s == 'c') {
+	    s++;
+	    *type = OP_CR;
+	}
+	if (*s++ != 'r')
+	  return -1;
+	/* Don't allow leading '0'.  */
+	if ((c = *s++) >= '1' && c <= '9')
+	  reg = c - '0';
+	else
+	  return -1;
+	if ((c = *s) >= '0' && c <= '5')
+	  s++, reg = reg * 10 + c - '0';
+	if (reg > 15)
+	  return -1;
+	if ((c = *s) == 0)
+	  ;
+	else if (*type != OP_REG64)
+	  return -1;
+	else if (c == 'b' && !s[1])
+	  *type = OP_REG8;
+	else if (c == 'w' && !s[1])
+	  *type = OP_REG16;
+	else if (c == 'd' && !s[1])
+	  *type = OP_REG32;
+	else
+	  return -1;
+    }
+    return reg;
+}
+#endif
+
+static int asm_parse_reg(unsigned int *type)
 {
     int reg = 0;
+    *type = 0;
     if (tok != '%')
         goto error_32;
@@ -276,11 +327,15 @@
     if (tok >= TOK_ASM_eax && tok <= TOK_ASM_edi) {
         reg = tok - TOK_ASM_eax;
+	*type = OP_REG32;
 #ifdef TCC_TARGET_X86_64
     } else if (tok >= TOK_ASM_rax && tok <= TOK_ASM_rdi) {
         reg = tok - TOK_ASM_rax;
-#endif
-#ifdef I386_ASM_16
-    } else if (tok >= TOK_ASM_ax && tok <= TOK_ASM_di) {
-        reg = tok - TOK_ASM_ax;
+	*type = OP_REG64;
+    } else if (tok == TOK_ASM_rip) {
+        reg = -2; /* Probably should use different escape code. */
+	*type = OP_REG64;
+    } else if ((reg = asm_parse_numeric_reg(tok, type)) >= 0
+	       && (*type == OP_REG32 || *type == OP_REG64)) {
+	;
 #endif
     } else {
@@ -330,5 +385,5 @@
                 if (tok != TOK_PPNUM)
                     goto reg_error;
-                p = tokc.cstr->data;
+                p = tokc.str.data;
                 reg = p[0] - '0';
                 if ((unsigned)reg >= 8 || p[1] != '\0')
@@ -341,7 +396,14 @@
                 op->type |= OP_ST0;
             goto no_skip;
+#ifdef TCC_TARGET_X86_64
+	} else if (tok >= TOK_ASM_spl && tok <= TOK_ASM_dil) {
+	    op->type = OP_REG8 | OP_REG8_LOW;
+	    op->reg = 4 + tok - TOK_ASM_spl;
+        } else if ((op->reg = asm_parse_numeric_reg(tok, &op->type)) >= 0) {
+	    ;
+#endif
         } else {
         reg_error:
-            tcc_error("unknown register");
+            tcc_error("unknown register %%%s", get_tok_str(tok, &tokc));
         }
         next();
@@ -351,7 +413,6 @@
         next();
         asm_expr(s1, &e);
-        op->type = OP_IM;
-        op->e.v = e.v;
-        op->e.sym = e.sym;
+        op->type = OP_IM32;
+        op->e = e;
         if (!op->e.sym) {
             if (op->e.v == (uint8_t)op->e.v)
@@ -362,6 +423,6 @@
                 op->type |= OP_IM16;
 #ifdef TCC_TARGET_X86_64
-            if (op->e.v == (uint32_t)op->e.v)
-                op->type |= OP_IM32;
+            if (op->e.v != (int32_t)op->e.v && op->e.v != (uint32_t)op->e.v)
+                op->type = OP_IM64;
 #endif
         }
@@ -374,6 +435,5 @@
         if (tok != '(') {
             asm_expr(s1, &e);
-            op->e.v = e.v;
-            op->e.sym = e.sym;
+            op->e = e;
         } else {
             next();
@@ -391,14 +451,16 @@
                 op->e.sym = e.sym;
             }
+	    op->e.pcrel = 0;
         }
         if (tok == '(') {
+	    unsigned int type = 0;
             next();
             if (tok != ',') {
-                op->reg = asm_parse_reg();
+                op->reg = asm_parse_reg(&type);
             }
             if (tok == ',') {
                 next();
                 if (tok != ',') {
-                    op->reg2 = asm_parse_reg();
+                    op->reg2 = asm_parse_reg(&type);
                 }
                 if (tok == ',') {
@@ -407,4 +469,6 @@
                 }
             }
+	    if (type & OP_REG32)
+	        op->type |= OP_EA32;
             skip(')');
         }
@@ -418,9 +482,14 @@
 ST_FUNC void gen_expr32(ExprValue *pe)
 {
-    gen_addr32(pe->sym ? VT_SYM : 0, pe->sym, pe->v);
+    if (pe->pcrel)
+        /* If PC-relative, always set VT_SYM, even without symbol,
+	   so as to force a relocation to be emitted.  */
+	gen_addrpc32(VT_SYM, pe->sym, pe->v);
+    else
+	gen_addr32(pe->sym ? VT_SYM : 0, pe->sym, pe->v);
 }
 
 #ifdef TCC_TARGET_X86_64
-static void gen_expr64(ExprValue *pe)
+ST_FUNC void gen_expr64(ExprValue *pe)
 {
     gen_addr64(pe->sym ? VT_SYM : 0, pe->sym, pe->v);
@@ -432,10 +501,11 @@
 {
     Sym *sym = pe->sym;
-    if (sym && sym->r == cur_text_section->sh_num) {
+    ElfSym *esym = elfsym(sym);
+    if (esym && esym->st_shndx == cur_text_section->sh_num) {
         /* same section: we can output an absolute value. Note
            that the TCC compiler behaves differently here because
            it always outputs a relocation to ease (future) code
            elimination in the linker */
-        gen_le32(pe->v + sym->jnext - ind - 4);
+        gen_le32(pe->v + esym->st_value - ind - 4);
     } else {
         if (sym && sym->type.t == VT_VOID) {
@@ -447,37 +517,6 @@
 }
 
-#ifdef I386_ASM_16
-static void gen_expr16(ExprValue *pe)
-{
-    if (pe->sym)
-        greloc(cur_text_section, pe->sym, ind, R_386_16);
-    gen_le16(pe->v);
-}
-static void gen_disp16(ExprValue *pe)
-{
-    Sym *sym;
-    sym = pe->sym;
-    if (sym) {
-        if (sym->r == cur_text_section->sh_num) {
-            /* same section: we can output an absolute value. Note
-               that the TCC compiler behaves differently here because
-               it always outputs a relocation to ease (future) code
-               elimination in the linker */
-            gen_le16(pe->v + sym->jnext - ind - 2);
-        } else {
-            greloc(cur_text_section, sym, ind, R_386_PC16);
-            gen_le16(pe->v - 2);
-        }
-    } else {
-        /* put an empty PC32 relocation */
-        put_elf_reloc(symtab_section, cur_text_section,
-                      ind, R_386_PC16, 0);
-        gen_le16(pe->v - 2);
-    }
-}
-#endif
-
 /* generate the modrm operand */
-static inline void asm_modrm(int reg, Operand *op)
+static inline int asm_modrm(int reg, Operand *op)
 {
     int mod, reg1, reg2, sib_reg1;
@@ -487,14 +526,18 @@
     } else if (op->reg == -1 && op->reg2 == -1) {
         /* displacement only */
-#ifdef I386_ASM_16
-        if (tcc_state->seg_size == 16) {
-            g(0x06 + (reg << 3));
-            gen_expr16(&op->e);
-        } else if (tcc_state->seg_size == 32)
-#endif
-        {
-            g(0x05 + (reg << 3));
-            gen_expr32(&op->e);
-        }
+#ifdef TCC_TARGET_X86_64
+	g(0x04 + (reg << 3));
+	g(0x25);
+#else
+	g(0x05 + (reg << 3));
+#endif
+	gen_expr32(&op->e);
+#ifdef TCC_TARGET_X86_64
+    } else if (op->reg == -2) {
+        ExprValue *pe = &op->e;
+        g(0x05 + (reg << 3));
+        gen_addrpc32(pe->sym ? VT_SYM : 0, pe->sym, pe->v);
+        return ind;
+#endif
     } else {
         sib_reg1 = op->reg;
@@ -514,7 +557,4 @@
         if (op->reg2 != -1)
             reg1 = 4;
-#ifdef I386_ASM_16
-        if (tcc_state->seg_size == 32) {
-#endif
         g(mod + (reg << 3) + reg1);
         if (reg1 == 4) {
@@ -525,52 +565,113 @@
             g((op->shift << 6) + (reg2 << 3) + sib_reg1);
         }
-#ifdef I386_ASM_16
-        } else if (tcc_state->seg_size == 16) {
-            /* edi = 7, esi = 6 --> di = 5, si = 4 */
-            if ((reg1 == 6) || (reg1 == 7)) {
-                reg1 -= 2;
-            /* ebx = 3 --> bx = 7 */
-            } else if (reg1 == 3) {
-                reg1 = 7;
-            /* o32 = 5 --> o16 = 6 */
-            } else if (reg1 == 5) {
-                reg1 = 6;
-            /* sib not valid in 16-bit mode */
-            } else if (reg1 == 4) {
-                reg2 = op->reg2;
-		/* bp + si + offset */
-		if ((sib_reg1 == 5) && (reg2 == 6)) {
-		    reg1 = 2;
-		/* bp + di + offset */
-		} else if ((sib_reg1 == 5) && (reg2 == 7)) {
-		    reg1 = 3;
-		/* bx + si + offset */
-		} else if ((sib_reg1 == 3) && (reg2 == 6)) {
-		    reg1 = 0;
-		/* bx + di + offset */
-		} else if ((sib_reg1 == 3) && (reg2 == 7)) {
-		    reg1 = 1;
-		} else {
-		    tcc_error("invalid effective address");
-		}
-		if (op->e.v == 0)
-		    mod = 0;
-            } else {
-                tcc_error("invalid register");
-            }
-            g(mod + (reg << 3) + reg1);
-        }
-#endif
         /* add offset */
         if (mod == 0x40) {
             g(op->e.v);
         } else if (mod == 0x80 || op->reg == -1) {
-#ifdef I386_ASM_16
-            if (tcc_state->seg_size == 16)
-                gen_expr16(&op->e);
-            else if (tcc_state->seg_size == 32)
-#endif
-                gen_expr32(&op->e);
-        }
+	    gen_expr32(&op->e);
+        }
+    }
+    return 0;
+}
+
+#ifdef TCC_TARGET_X86_64
+#define REX_W 0x48
+#define REX_R 0x44
+#define REX_X 0x42
+#define REX_B 0x41
+
+static void asm_rex(int width64, Operand *ops, int nb_ops, int *op_type,
+		    int regi, int rmi)
+{
+  unsigned char rex = width64 ? 0x48 : 0;
+  int saw_high_8bit = 0;
+  int i;
+  if (rmi == -1) {
+      /* No mod/rm byte, but we might have a register op nevertheless
+         (we will add it to the opcode later).  */
+      for(i = 0; i < nb_ops; i++) {
+	  if (op_type[i] & (OP_REG | OP_ST)) {
+	      if (ops[i].reg >= 8) {
+		  rex |= REX_B;
+		  ops[i].reg -= 8;
+	      } else if (ops[i].type & OP_REG8_LOW)
+		  rex |= 0x40;
+	      else if (ops[i].type & OP_REG8 && ops[i].reg >= 4)
+		  /* An 8 bit reg >= 4 without REG8 is ah/ch/dh/bh */
+		  saw_high_8bit = ops[i].reg;
+	      break;
+	  }
+      }
+  } else {
+      if (regi != -1) {
+	  if (ops[regi].reg >= 8) {
+	      rex |= REX_R;
+	      ops[regi].reg -= 8;
+	  } else if (ops[regi].type & OP_REG8_LOW)
+	      rex |= 0x40;
+	  else if (ops[regi].type & OP_REG8 && ops[regi].reg >= 4)
+	      /* An 8 bit reg >= 4 without REG8 is ah/ch/dh/bh */
+	      saw_high_8bit = ops[regi].reg;
+      }
+      if (ops[rmi].type & (OP_REG | OP_MMX | OP_SSE | OP_CR | OP_EA)) {
+	  if (ops[rmi].reg >= 8) {
+	      rex |= REX_B;
+	      ops[rmi].reg -= 8;
+	  } else if (ops[rmi].type & OP_REG8_LOW)
+	      rex |= 0x40;
+	  else if (ops[rmi].type & OP_REG8 && ops[rmi].reg >= 4)
+	      /* An 8 bit reg >= 4 without REG8 is ah/ch/dh/bh */
+	      saw_high_8bit = ops[rmi].reg;
+      }
+      if (ops[rmi].type & OP_EA && ops[rmi].reg2 >= 8) {
+	  rex |= REX_X;
+	  ops[rmi].reg2 -= 8;
+      }
+  }
+  if (rex) {
+      if (saw_high_8bit)
+	  tcc_error("can't encode register %%%ch when REX prefix is required",
+		    "acdb"[saw_high_8bit-4]);
+      g(rex);
+  }
+}
+#endif
+
+static void maybe_print_stats (void)
+{
+  static int already = 1;
+  if (!already)
+    /* print stats about opcodes */
+    {
+        const struct ASMInstr *pa;
+        int freq[4];
+        int op_vals[500];
+        int nb_op_vals, i, j;
+
+	already = 1;
+        nb_op_vals = 0;
+        memset(freq, 0, sizeof(freq));
+        for(pa = asm_instrs; pa->sym != 0; pa++) {
+            freq[pa->nb_ops]++;
+            //for(i=0;i<pa->nb_ops;i++) {
+                for(j=0;j<nb_op_vals;j++) {
+                    //if (pa->op_type[i] == op_vals[j])
+                    if (pa->instr_type == op_vals[j])
+                        goto found;
+                }
+                //op_vals[nb_op_vals++] = pa->op_type[i];
+                op_vals[nb_op_vals++] = pa->instr_type;
+            found: ;
+            //}
+        }
+        for(i=0;i<nb_op_vals;i++) {
+            int v = op_vals[i];
+            //if ((v & (v - 1)) != 0)
+                printf("%3d: %08x\n", i, v);
+        }
+        printf("size=%d nb=%d f0=%d f1=%d f2=%d f3=%d\n",
+               (int)sizeof(asm_instrs),
+	       (int)sizeof(asm_instrs) / (int)sizeof(ASMInstr),
+               freq[0], freq[1], freq[2], freq[3]);
     }
 }
@@ -579,12 +680,16 @@
 {
     const ASMInstr *pa;
-    int i, modrm_index, reg, v, op1, is_short_jmp, seg_prefix;
+    int i, modrm_index, modreg_index, reg, v, op1, seg_prefix, pc;
     int nb_ops, s;
     Operand ops[MAX_OPERANDS], *pop;
     int op_type[3]; /* decoded op type */
-#ifdef I386_ASM_16
-    static int a32 = 0, o32 = 0, addr32 = 0, data32 = 0;
-#endif
-
+    int alltypes;   /* OR of all operand types */
+    int autosize;
+    int p66;
+#ifdef TCC_TARGET_X86_64
+    int rex64;
+#endif
+
+    maybe_print_stats();
     /* force synthetic ';' after prefix instruction, so we can handle */
     /* one-line things like "rep stosb" instead of only "rep\nstosb" */
@@ -596,4 +701,5 @@
     nb_ops = 0;
     seg_prefix = 0;
+    alltypes = 0;
     for(;;) {
         if (tok == ';' || tok == TOK_LINEFEED)
@@ -609,9 +715,7 @@
            next();
            parse_operand(s1, pop);
-#ifndef I386_ASM_16
            if (!(pop->type & OP_EA)) {
                tcc_error("segment prefix must be followed by memory reference");
            }
-#endif
         }
         pop++;
@@ -622,27 +726,50 @@
     }
 
-    is_short_jmp = 0;
     s = 0; /* avoid warning */
 
+again:
     /* optimize matching by using a lookup table (no hashing is needed
        !) */
     for(pa = asm_instrs; pa->sym != 0; pa++) {
+	int it = pa->instr_type & OPCT_MASK;
         s = 0;
-        if (pa->instr_type & OPC_FARITH) {
+        if (it == OPC_FARITH) {
             v = opcode - pa->sym;
             if (!((unsigned)v < 8 * 6 && (v % 6) == 0))
                 continue;
-        } else if (pa->instr_type & OPC_ARITH) {
+        } else if (it == OPC_ARITH) {
             if (!(opcode >= pa->sym && opcode < pa->sym + 8*NBWLX))
                 continue;
             s = (opcode - pa->sym) % NBWLX;
-        } else if (pa->instr_type & OPC_SHIFT) {
+	    if ((pa->instr_type & OPC_BWLX) == OPC_WLX)
+	      {
+		/* We need to reject the xxxb opcodes that we accepted above.
+		   Note that pa->sym for WLX opcodes is the 'w' token,
+		   to get the 'b' token subtract one.  */
+		if (((opcode - pa->sym + 1) % NBWLX) == 0)
+		    continue;
+	        s++;
+	      }
+        } else if (it == OPC_SHIFT) {
             if (!(opcode >= pa->sym && opcode < pa->sym + 7*NBWLX))
                 continue;
             s = (opcode - pa->sym) % NBWLX;
-        } else if (pa->instr_type & OPC_TEST) {
+        } else if (it == OPC_TEST) {
             if (!(opcode >= pa->sym && opcode < pa->sym + NB_TEST_OPCODES))
                 continue;
+	    /* cmovxx is a test opcode but accepts multiple sizes.
+	       The suffixes aren't encoded in the table, instead we
+	       simply force size autodetection always and deal with suffixed
+	       variants below when we don't find e.g. "cmovzl".  */
+	    if (pa->instr_type & OPC_WLX)
+	        s = NBWLX - 1;
         } else if (pa->instr_type & OPC_B) {
+#ifdef TCC_TARGET_X86_64
+	    /* Some instructions don't have the full size but only
+	       bwl form.  insb e.g. */
+	    if ((pa->instr_type & OPC_WLQ) != OPC_WLQ
+		&& !(opcode >= pa->sym && opcode < pa->sym + NBWLX-1))
+	        continue;
+#endif
             if (!(opcode >= pa->sym && opcode < pa->sym + NBWLX))
                 continue;
@@ -658,5 +785,15 @@
         if (pa->nb_ops != nb_ops)
             continue;
+#ifdef TCC_TARGET_X86_64
+	/* Special case for moves.  Selecting the IM64->REG64 form
+	   should only be done if we really have an >32bit imm64, and that
+	   is hardcoded.  Ignore it here.  */
+	if (pa->opcode == 0xb0 && ops[0].type != OP_IM64
+	    && (ops[1].type & OP_REG) == OP_REG64
+	    && !(pa->instr_type & OPC_0F))
+	    continue;
+#endif
         /* now decode and check each operand */
+	alltypes = 0;
         for(i = 0; i < nb_ops; i++) {
             int op1, op2;
@@ -665,5 +802,5 @@
             switch(op2) {
             case OPT_IM:
-                v = OP_IM8 | OP_IM16 | OP_IM32 | OP_IM64;
+                v = OP_IM8 | OP_IM16 | OP_IM32;
                 break;
             case OPT_REG:
@@ -674,11 +811,13 @@
                 break;
             case OPT_IMW:
-                v = OP_IM16 | OP_IM32 | OP_IM64;
-                break;
-#ifdef TCC_TARGET_X86_64
-            case OPT_IMNO64:
                 v = OP_IM16 | OP_IM32;
                 break;
-#endif
+	    case OPT_MMXSSE:
+		v = OP_MMX | OP_SSE;
+		break;
+	    case OPT_DISP:
+	    case OPT_DISP8:
+		v = OP_ADDR;
+		break;
             default:
                 v = 1 << op2;
@@ -687,7 +826,8 @@
             if (op1 & OPT_EA)
                 v |= OP_EA;
-            op_type[i] = v;
+	    op_type[i] = v;
             if ((ops[i].type & v) == 0)
                 goto next;
+	    alltypes |= ops[i].type;
         }
         /* all is matching ! */
@@ -699,36 +839,48 @@
             int b;
             b = op0_codes[opcode - TOK_ASM_first];
-#ifdef I386_ASM_16
-            if (opcode == TOK_ASM_o32) {
-                if (s1->seg_size == 32)
-                    tcc_error("incorrect prefix");
-                else
-                    o32 = data32 = 1;
-            } else if (opcode == TOK_ASM_a32) {
-                if (s1->seg_size == 32)
-                    tcc_error("incorrect prefix");
-                else
-                    a32 = addr32 = 1;
-            }
-#endif
             if (b & 0xff00) 
                 g(b >> 8);
             g(b);
             return;
+        } else if (opcode <= TOK_ASM_alllast) {
+            tcc_error("bad operand with opcode '%s'",
+                  get_tok_str(opcode, NULL));
         } else {
-            tcc_error("unknown opcode '%s'",
-                  get_tok_str(opcode, NULL));
+	    /* Special case for cmovcc, we accept size suffixes but ignore
+	       them, but we don't want them to blow up our tables.  */
+	    TokenSym *ts = table_ident[opcode - TOK_IDENT];
+	    if (ts->len >= 6
+		&& strchr("wlq", ts->str[ts->len-1])
+		&& !memcmp(ts->str, "cmov", 4)) {
+		opcode = tok_alloc(ts->str, ts->len-1)->tok;
+		goto again;
+	    }
+            tcc_error("unknown opcode '%s'", ts->str);
         }
     }
     /* if the size is unknown, then evaluate it (OPC_B or OPC_WL case) */
-    if (s == NBWLX-1) {
-        for(i = 0; s == NBWLX-1 && i < nb_ops; i++) {
+    autosize = NBWLX-1;
+#ifdef TCC_TARGET_X86_64
+    /* XXX the autosize should rather be zero, to not have to adjust this
+       all the time.  */
+    if ((pa->instr_type & OPC_BWLQ) == OPC_B)
+        autosize = NBWLX-2;
+#endif
+    if (s == autosize) {
+	/* Check for register operands providing hints about the size.
+	   Start from the end, i.e. destination operands.  This matters
+	   only for opcodes accepting different sized registers, lar and lsl
+	   are such opcodes.  */
+        for(i = nb_ops - 1; s == autosize && i >= 0; i--) {
             if ((ops[i].type & OP_REG) && !(op_type[i] & (OP_CL | OP_DX)))
                 s = reg_to_size[ops[i].type & OP_REG];
         }
-        if (s == NBWLX-1) {
+        if (s == autosize) {
             if ((opcode == TOK_ASM_push || opcode == TOK_ASM_pop) &&
-                (ops[0].type & (OP_SEG | OP_IM8S | OP_IM32 | OP_IM64)))
+                (ops[0].type & (OP_SEG | OP_IM8S | OP_IM32)))
                 s = 2;
+	    else if ((opcode == TOK_ASM_push || opcode == TOK_ASM_pop) &&
+		     (ops[0].type & OP_EA))
+	        s = NBWLX - 2;
             else
                 tcc_error("cannot infer opcode suffix");
@@ -736,50 +888,57 @@
     }
 
-#ifdef I386_ASM_16
+#ifdef TCC_TARGET_X86_64
+    /* Generate addr32 prefix if needed */
     for(i = 0; i < nb_ops; i++) {
-        if (ops[i].type & OP_REG32) {
-            if (s1->seg_size == 16)
-                o32 = 1;
-        } else if (!(ops[i].type & OP_REG32)) {
-            if (s1->seg_size == 32)
-                o32 = 1;
-        }
-    }
-
-
-    if (s == 1 || (pa->instr_type & OPC_D16)) {
-        if (s1->seg_size == 32)
-            o32 = 1;
-    } else if (s == 2) {
-        if (s1->seg_size == 16) {
-            if (!(pa->instr_type & OPC_D16))
-            o32 = 1;
-        }
-    }
-
-    /* generate a16/a32 prefix if needed */
-    if ((a32 == 1) && (addr32 == 0))
-        g(0x67);
-    /* generate o16/o32 prefix if needed */
-    if ((o32 == 1) && (data32 == 0))
+        if (ops[i].type & OP_EA32) {
+	    g(0x67);
+	    break;
+        }
+    }
+#endif
+    /* generate data16 prefix if needed */
+    p66 = 0;
+    if (s == 1)
+        p66 = 1;
+    else {
+	/* accepting mmx+sse in all operands --> needs 0x66 to
+	   switch to sse mode.  Accepting only sse in an operand --> is
+	   already SSE insn and needs 0x66/f2/f3 handling.  */
+        for (i = 0; i < nb_ops; i++)
+            if ((op_type[i] & (OP_MMX | OP_SSE)) == (OP_MMX | OP_SSE)
+	        && ops[i].type & OP_SSE)
+	        p66 = 1;
+    }
+    if (p66)
         g(0x66);
-
-    addr32 = data32 = 0;
-#else
-    /* generate data16 prefix if needed */
-    if (s == 1 || (pa->instr_type & OPC_D16))
-        g(0x66);
-#ifdef TCC_TARGET_X86_64
-    else if (s == 3) {
+#ifdef TCC_TARGET_X86_64
+    rex64 = 0;
+    if (pa->instr_type & OPC_48)
+        rex64 = 1;
+    else if (s == 3 || (alltypes & OP_REG64)) {
         /* generate REX prefix */
-        if ((opcode != TOK_ASM_push && opcode != TOK_ASM_pop)
-            || !(ops[0].type & OP_REG64))
-            g(0x48);
-    }
-#endif
+	int default64 = 0;
+	for(i = 0; i < nb_ops; i++) {
+	    if (op_type[i] == OP_REG64 && pa->opcode != 0xb8) {
+		/* If only 64bit regs are accepted in one operand
+		   this is a default64 instruction without need for
+		   REX prefixes, except for movabs(0xb8).  */
+		default64 = 1;
+		break;
+	    }
+	}
+	/* XXX find better encoding for the default64 instructions.  */
+        if (((opcode != TOK_ASM_push && opcode != TOK_ASM_pop
+	      && opcode != TOK_ASM_pushw && opcode != TOK_ASM_pushl
+	      && opcode != TOK_ASM_pushq && opcode != TOK_ASM_popw
+	      && opcode != TOK_ASM_popl && opcode != TOK_ASM_popq
+	      && opcode != TOK_ASM_call && opcode != TOK_ASM_jmp))
+	    && !default64)
+            rex64 = 1;
+    }
 #endif
 
     /* now generates the operation */
-    if (pa->instr_type & OPC_FWAIT)
+    if (OPCT_IS(pa->instr_type, OPC_FWAIT))
         g(0x9b);
     if (seg_prefix)
@@ -787,4 +946,6 @@
 
     v = pa->opcode;
+    if (pa->instr_type & OPC_0F)
+        v = ((v & ~0xff) << 8) | 0x0f00 | (v & 0xff);
     if ((v == 0x69 || v == 0x6b) && nb_ops == 2) {
         /* kludge for imul $im, %reg */
@@ -806,9 +967,56 @@
         /* arith case */
         v += ((opcode - TOK_ASM_addb) / NBWLX) << 3;
-    } else if ((pa->instr_type & (OPC_FARITH | OPC_MODRM)) == OPC_FARITH) {
+    } else if ((pa->instr_type & (OPCT_MASK | OPC_MODRM)) == OPC_FARITH) {
         /* fpu arith case */
         v += ((opcode - pa->sym) / 6) << 3;
     }
+
+    /* search which operand will be used for modrm */
+    modrm_index = -1;
+    modreg_index = -1;
+    if (pa->instr_type & OPC_MODRM) {
+	if (!nb_ops) {
+	    /* A modrm opcode without operands is a special case (e.g. mfence).
+	       It has a group and acts as if there's an register operand 0
+	       (ax).  */
+	    i = 0;
+	    ops[i].type = OP_REG;
+	    ops[i].reg = 0;
+	    goto modrm_found;
+	}
+        /* first look for an ea operand */
+        for(i = 0;i < nb_ops; i++) {
+            if (op_type[i] & OP_EA)
+                goto modrm_found;
+        }
+        /* then if not found, a register or indirection (shift instructions) */
+        for(i = 0;i < nb_ops; i++) {
+            if (op_type[i] & (OP_REG | OP_MMX | OP_SSE | OP_INDIR))
+                goto modrm_found;
+        }
+#ifdef ASM_DEBUG
+        tcc_error("bad op table");
+#endif
+    modrm_found:
+        modrm_index = i;
+        /* if a register is used in another operand then it is
+           used instead of group */
+        for(i = 0;i < nb_ops; i++) {
+            int t = op_type[i];
+            if (i != modrm_index &&
+                (t & (OP_REG | OP_MMX | OP_SSE | OP_CR | OP_TR | OP_DB | OP_SEG))) {
+                modreg_index = i;
+                break;
+            }
+        }
+    }
+#ifdef TCC_TARGET_X86_64
+    asm_rex (rex64, ops, nb_ops, op_type, modreg_index, modrm_index);
+#endif
+
     if (pa->instr_type & OPC_REG) {
+        /* mov $im, %reg case */
+        if (v == 0xb0 && s >= 1)
+            v += 7;
         for(i = 0; i < nb_ops; i++) {
             if (op_type[i] & (OP_REG | OP_ST)) {
@@ -817,99 +1025,70 @@
             }
         }
-        /* mov $im, %reg case */
-        if (pa->opcode == 0xb0 && s >= 1)
-            v += 7;
     }
     if (pa->instr_type & OPC_B)
         v += s >= 1;
-    if (pa->instr_type & OPC_TEST)
-        v += test_bits[opcode - pa->sym];
-    if (pa->instr_type & OPC_SHORTJMP) {
-        Sym *sym;
+    if (nb_ops == 1 && pa->op_type[0] == OPT_DISP8) {
+	ElfSym *esym;
         int jmp_disp;
 
         /* see if we can really generate the jump with a byte offset */
-        sym = ops[0].e.sym;
-        if (!sym)
+	esym = elfsym(ops[0].e.sym);
+        if (!esym || esym->st_shndx != cur_text_section->sh_num)
             goto no_short_jump;
-        if (sym->r != cur_text_section->sh_num)
-            goto no_short_jump;
-        jmp_disp = ops[0].e.v + sym->jnext - ind - 2;
+        jmp_disp = ops[0].e.v + esym->st_value - ind - 2 - (v >= 0xff);
         if (jmp_disp == (int8_t)jmp_disp) {
             /* OK to generate jump */
-            is_short_jmp = 1;
+	    ops[0].e.sym = 0;
             ops[0].e.v = jmp_disp;
+	    op_type[0] = OP_IM8S;
         } else {
         no_short_jump:
-            if (pa->instr_type & OPC_JMP) {
-                /* long jump will be allowed. need to modify the
-                   opcode slightly */
-                if (v == 0xeb)
-                    v = 0xe9;
-                else
-                    v += 0x0f10;
-            } else {
-                tcc_error("invalid displacement");
-            }
-        }
-    }
-    op1 = v >> 8;
+	    /* long jump will be allowed. need to modify the
+	       opcode slightly */
+	    if (v == 0xeb) /* jmp */
+	        v = 0xe9;
+	    else if (v == 0x70) /* jcc */
+	        v += 0x0f10;
+	    else
+	        tcc_error("invalid displacement");
+        }
+    }
+    if (OPCT_IS(pa->instr_type, OPC_TEST))
+        v += test_bits[opcode - pa->sym];
+    op1 = v >> 16;
+    if (op1)
+        g(op1);
+    op1 = (v >> 8) & 0xff;
     if (op1)
         g(op1);
     g(v);
 
-    /* search which operand will used for modrm */
-    modrm_index = 0;
-    if (pa->instr_type & OPC_SHIFT) {
+    if (OPCT_IS(pa->instr_type, OPC_SHIFT)) {
         reg = (opcode - pa->sym) / NBWLX;
         if (reg == 6)
             reg = 7;
-    } else if (pa->instr_type & OPC_ARITH) {
+    } else if (OPCT_IS(pa->instr_type, OPC_ARITH)) {
         reg = (opcode - pa->sym) / NBWLX;
-    } else if (pa->instr_type & OPC_FARITH) {
+    } else if (OPCT_IS(pa->instr_type, OPC_FARITH)) {
         reg = (opcode - pa->sym) / 6;
     } else {
         reg = (pa->instr_type >> OPC_GROUP_SHIFT) & 7;
     }
+
+    pc = 0;
     if (pa->instr_type & OPC_MODRM) {
-        /* first look for an ea operand */
-        for(i = 0;i < nb_ops; i++) {
-            if (op_type[i] & OP_EA)
-                goto modrm_found;
-        }
-        /* then if not found, a register or indirection (shift instructions) */
-        for(i = 0;i < nb_ops; i++) {
-            if (op_type[i] & (OP_REG | OP_MMX | OP_SSE | OP_INDIR))
-                goto modrm_found;
-        }
-#ifdef ASM_DEBUG
-        tcc_error("bad op table");
-#endif
-    modrm_found:
-        modrm_index = i;
         /* if a register is used in another operand then it is
            used instead of group */
-        for(i = 0;i < nb_ops; i++) {
-            v = op_type[i];
-            if (i != modrm_index &&
-                (v & (OP_REG | OP_MMX | OP_SSE | OP_CR | OP_TR | OP_DB | OP_SEG))) {
-                reg = ops[i].reg;
-                break;
-            }
-        }
-
-        asm_modrm(reg, &ops[modrm_index]);
+	if (modreg_index >= 0)
+	    reg = ops[modreg_index].reg;
+        pc = asm_modrm(reg, &ops[modrm_index]);
     }
 
     /* emit constants */
 #ifndef TCC_TARGET_X86_64
-    if (pa->opcode == 0x9a || pa->opcode == 0xea) {
+    if (!(pa->instr_type & OPC_0F)
+	&& (pa->opcode == 0x9a || pa->opcode == 0xea)) {
         /* ljmp or lcall kludge */
-#ifdef I386_ASM_16
-        if (s1->seg_size == 16 && o32 == 0)
-            gen_expr16(&ops[1].e);
-        else
-#endif
-            gen_expr32(&ops[1].e);
+	gen_expr32(&ops[1].e);
         if (ops[0].e.sym)
             tcc_error("cannot relocate");
@@ -933,62 +1112,27 @@
                     v = OP_IM64;
             }
+
+            if ((v & (OP_IM8 | OP_IM8S | OP_IM16)) && ops[i].e.sym)
+                tcc_error("cannot relocate");
+
             if (v & (OP_IM8 | OP_IM8S)) {
-                if (ops[i].e.sym)
-                    goto error_relocate;
                 g(ops[i].e.v);
             } else if (v & OP_IM16) {
-#ifdef I386_ASM_16
-                if (s1->seg_size == 16)
-                    gen_expr16(&ops[i].e);
-                else
-#endif
-                if (ops[i].e.sym)
-                error_relocate:
-                    tcc_error("cannot relocate");
-                else
-                    gen_le16(ops[i].e.v);
+                gen_le16(ops[i].e.v);
+#ifdef TCC_TARGET_X86_64
+            } else if (v & OP_IM64) {
+                gen_expr64(&ops[i].e);
+#endif
+	    } else if (pa->op_type[i] == OPT_DISP || pa->op_type[i] == OPT_DISP8) {
+                gen_disp32(&ops[i].e);
             } else {
-                if (pa->instr_type & (OPC_JMP | OPC_SHORTJMP)) {
-                    if (is_short_jmp)
-                        g(ops[i].e.v);
-#ifdef I386_ASM_16
-                    else if (s1->seg_size == 16)
-                        gen_disp16(&ops[i].e);
-#endif
-                    else
-                        gen_disp32(&ops[i].e);
-                } else {
-#ifdef I386_ASM_16
-                    if (s1->seg_size == 16 && !((o32 == 1) && (v & OP_IM32)))
-                        gen_expr16(&ops[i].e);
-                    else
-#endif
-#ifdef TCC_TARGET_X86_64
-                    if (v & OP_IM64)
-                        gen_expr64(&ops[i].e);
-                    else
-#endif
-                        gen_expr32(&ops[i].e);
-                }
+                gen_expr32(&ops[i].e);
             }
-#ifdef I386_ASM_16
-        } else if (v & (OP_REG16 | OP_REG32)) {
-            if (pa->instr_type & (OPC_JMP | OPC_SHORTJMP)) {
-                /* jmp $r */
-                g(0xE0 + ops[i].reg);
-            }
-#endif
-#ifdef TCC_TARGET_X86_64
-        } else if (v & (OP_REG32 | OP_REG64)) {
-            if (pa->instr_type & (OPC_JMP | OPC_SHORTJMP)) {
-                /* jmp $r */
-                g(0xE0 + ops[i].reg);
-            }
-#endif
-        }
-    }
-#ifdef I386_ASM_16
-    a32 = o32 = 0;
-#endif
+        }
+    }
+
+    /* after immediate operands, adjust pc-relative address */
+    if (pc)
+        add32le(cur_text_section->data + pc - 4, pc - ind);
 }
 
@@ -1022,4 +1166,6 @@
             break;
         case 'r':
+	case 'R':
+	case 'p':
             pr = 3;
             break;
@@ -1027,4 +1173,5 @@
         case 'M':
         case 'I':
+	case 'e':
         case 'i':
         case 'm':
@@ -1047,4 +1194,26 @@
         p++;
     return p;
+}
+
+/* If T (a token) is of the form "%reg" returns the register
+   number and type, otherwise return -1.  */
+ST_FUNC int asm_parse_regvar (int t)
+{
+    const char *s;
+    Operand op;
+    if (t < TOK_IDENT)
+        return -1;
+    s = table_ident[t - TOK_IDENT]->str;
+    if (s[0] != '%')
+        return -1;
+    t = tok_alloc(s+1, strlen(s)-1)->tok;
+    unget_tok(t);
+    unget_tok('%');
+    parse_operand(tcc_state, &op);
+    /* Accept only integer regs for now.  */
+    if (op.type & OP_REG)
+        return op.reg;
+    else
+        return -1;
 }
 
@@ -1091,4 +1260,9 @@
             operands[k].input_index = i;
             op->priority = 5;
+	} else if ((op->vt->r & VT_VALMASK) == VT_LOCAL
+		   && op->vt->sym
+		   && (reg = op->vt->sym->r & VT_VALMASK) < VT_CONST) {
+	    op->priority = 1;
+	    op->reg = reg;
         } else {
             op->priority = constraint_priority(str);
@@ -1138,4 +1312,10 @@
             reg_mask = REG_IN_MASK;
         }
+	if (op->reg >= 0) {
+	    if (is_reg_allocated(op->reg))
+	        tcc_error("asm regvar requests register that's taken already");
+	    reg = op->reg;
+	    goto reg_found;
+	}
     try_next:
         c = *str++;
@@ -1190,4 +1370,6 @@
             goto try_next;
         case 'r':
+	case 'R':
+	case 'p': /* A general address, for x86(64) any register is acceptable*/
             /* any general register */
             for(reg = 0; reg < 8; reg++) {
@@ -1202,4 +1384,5 @@
             regs_allocated[reg] |= reg_mask;
             break;
+	case 'e':
         case 'i':
             if (!((op->vt->r & (VT_VALMASK | VT_LVAL)) == VT_CONST))
@@ -1294,22 +1477,39 @@
     r = sv->r;
     if ((r & VT_VALMASK) == VT_CONST) {
-        if (!(r & VT_LVAL) && modifier != 'c' && modifier != 'n')
+        if (!(r & VT_LVAL) && modifier != 'c' && modifier != 'n' &&
+	    modifier != 'P')
             cstr_ccat(add_str, '$');
         if (r & VT_SYM) {
-            cstr_cat(add_str, get_tok_str(sv->sym->v, NULL));
-            if (sv->c.i != 0) {
-                cstr_ccat(add_str, '+');
-            } else {
-                return;
-            }
+	    const char *name = get_tok_str(sv->sym->v, NULL);
+	    if (sv->sym->v >= SYM_FIRST_ANOM) {
+		/* In case of anonymous symbols ("L.42", used
+		   for static data labels) we can't find them
+		   in the C symbol table when later looking up
+		   this name.  So enter them now into the asm label
+		   list when we still know the symbol.  */
+		get_asm_sym(tok_alloc(name, strlen(name))->tok, sv->sym);
+	    }
+            cstr_cat(add_str, name, -1);
+            if ((uint32_t)sv->c.i == 0)
+                goto no_offset;
+	    cstr_ccat(add_str, '+');
         }
         val = sv->c.i;
         if (modifier == 'n')
             val = -val;
-        snprintf(buf, sizeof(buf), "%d", sv->c.i);
-        cstr_cat(add_str, buf);
+        snprintf(buf, sizeof(buf), "%d", (int)sv->c.i);
+        cstr_cat(add_str, buf, -1);
+    no_offset:;
+#ifdef TCC_TARGET_X86_64
+        if (r & VT_LVAL)
+            cstr_cat(add_str, "(%rip)", -1);
+#endif
     } else if ((r & VT_VALMASK) == VT_LOCAL) {
-        snprintf(buf, sizeof(buf), "%d(%%ebp)", sv->c.i);
-        cstr_cat(add_str, buf);
+#ifdef TCC_TARGET_X86_64
+        snprintf(buf, sizeof(buf), "%d(%%rbp)", (int)sv->c.i);
+#else
+        snprintf(buf, sizeof(buf), "%d(%%ebp)", (int)sv->c.i);
+#endif
+        cstr_cat(add_str, buf, -1);
     } else if (r & VT_LVAL) {
         reg = r & VT_VALMASK;
@@ -1317,6 +1517,11 @@
             tcc_error("internal compiler error");
         snprintf(buf, sizeof(buf), "(%%%s)",
-                 get_tok_str(TOK_ASM_eax + reg, NULL));
-        cstr_cat(add_str, buf);
+#ifdef TCC_TARGET_X86_64
+                 get_tok_str(TOK_ASM_rax + reg, NULL)
+#else
+                 get_tok_str(TOK_ASM_eax + reg, NULL)
+#endif
+		 );
+        cstr_cat(add_str, buf, -1);
     } else {
         /* register case */
@@ -1326,10 +1531,12 @@
 
         /* choose register operand size */
-        if ((sv->type.t & VT_BTYPE) == VT_BYTE)
+        if ((sv->type.t & VT_BTYPE) == VT_BYTE ||
+	    (sv->type.t & VT_BTYPE) == VT_BOOL)
             size = 1;
         else if ((sv->type.t & VT_BTYPE) == VT_SHORT)
             size = 2;
 #ifdef TCC_TARGET_X86_64
-        else if ((sv->type.t & VT_BTYPE) == VT_LLONG)
+        else if ((sv->type.t & VT_BTYPE) == VT_LLONG ||
+		 (sv->type.t & VT_BTYPE) == VT_PTR)
             size = 8;
 #endif
@@ -1349,4 +1556,6 @@
         } else if (modifier == 'w') {
             size = 2;
+        } else if (modifier == 'k') {
+            size = 4;
 #ifdef TCC_TARGET_X86_64
         } else if (modifier == 'q') {
@@ -1375,9 +1584,9 @@
         }
         snprintf(buf, sizeof(buf), "%%%s", get_tok_str(reg, NULL));
-        cstr_cat(add_str, buf);
+        cstr_cat(add_str, buf, -1);
     }
 }
 
-/* generate prolog and epilog code for asm statment */
+/* generate prolog and epilog code for asm statement */
 ST_FUNC void asm_gen_code(ASMOperand *operands, int nb_operands,
                          int nb_outputs, int is_output,
@@ -1388,5 +1597,16 @@
     ASMOperand *op;
     int i, reg;
-    static uint8_t reg_saved[NB_SAVED_REGS] = { 3, 6, 7 };
+
+    /* Strictly speaking %Xbp and %Xsp should be included in the
+       call-preserved registers, but currently it doesn't matter.  */
+#ifdef TCC_TARGET_X86_64
+#ifdef TCC_TARGET_PE
+    static uint8_t reg_saved[] = { 3, 6, 7, 12, 13, 14, 15 };
+#else
+    static uint8_t reg_saved[] = { 3, 12, 13, 14, 15 };
+#endif
+#else
+    static uint8_t reg_saved[] = { 3, 6, 7 };
+#endif
 
     /* mark all used registers */
@@ -1399,11 +1619,9 @@
     if (!is_output) {
         /* generate reg save code */
-        for(i = 0; i < NB_SAVED_REGS; i++) {
+        for(i = 0; i < sizeof(reg_saved)/sizeof(reg_saved[0]); i++) {
             reg = reg_saved[i];
             if (regs_allocated[reg]) {
-#ifdef I386_ASM_16
-                if (tcc_state->seg_size == 16)
-                    g(0x66);
-#endif
+		if (reg >= 8)
+		  g(0x41), reg-=8;
                 g(0x50 + reg);
             }
@@ -1420,5 +1638,6 @@
                     SValue sv;
                     sv = *op->vt;
-                    sv.r = (sv.r & ~VT_VALMASK) | VT_LOCAL;
+                    sv.r = (sv.r & ~VT_VALMASK) | VT_LOCAL | VT_LVAL;
+                    sv.type.t = VT_PTR;
                     load(op->reg, &sv);
                 } else if (i >= nb_outputs || op->is_rw) {
@@ -1428,5 +1647,5 @@
                         SValue sv;
                         sv = *op->vt;
-                        sv.c.ul += 4;
+                        sv.c.i += 4;
                         load(TREG_XDX, &sv);
                     }
@@ -1444,6 +1663,8 @@
                         sv = *op->vt;
                         sv.r = (sv.r & ~VT_VALMASK) | VT_LOCAL;
+			sv.type.t = VT_PTR;
                         load(out_reg, &sv);
 
+			sv = *op->vt;
                         sv.r = (sv.r & ~VT_VALMASK) | out_reg;
                         store(op->reg, &sv);
@@ -1454,5 +1675,5 @@
                         SValue sv;
                         sv = *op->vt;
-                        sv.c.ul += 4;
+                        sv.c.i += 4;
                         store(TREG_XDX, &sv);
                     }
@@ -1461,11 +1682,9 @@
         }
         /* generate reg restore code */
-        for(i = NB_SAVED_REGS - 1; i >= 0; i--) {
+        for(i = sizeof(reg_saved)/sizeof(reg_saved[0]) - 1; i >= 0; i--) {
             reg = reg_saved[i];
             if (regs_allocated[reg]) {
-#ifdef I386_ASM_16
-                if (tcc_state->seg_size == 16)
-                    g(0x66);
-#endif
+		if (reg >= 8)
+		  g(0x41), reg-=8;
                 g(0x58 + reg);
             }
@@ -1478,7 +1697,11 @@
     int reg;
     TokenSym *ts;
+#ifdef TCC_TARGET_X86_64
+    unsigned int type;
+#endif
 
     if (!strcmp(str, "memory") ||
-        !strcmp(str, "cc"))
+        !strcmp(str, "cc") ||
+	!strcmp(str, "flags"))
         return;
     ts = tok_alloc(str, strlen(str));
@@ -1491,4 +1714,6 @@
     } else if (reg >= TOK_ASM_rax && reg <= TOK_ASM_rdi) {
         reg -= TOK_ASM_rax;
+    } else if ((reg = asm_parse_numeric_reg(reg, &type)) >= 0) {
+	;
 #endif
     } else {
