* config/tc-a29k.h: Fix comment typos.
[external/binutils.git] / gas / config / tc-m68hc11.c
1 /* tc-m68hc11.c -- Assembler code for the Motorola 68HC11 & 68HC12.
2    Copyright 1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
3    Written by Stephane Carrez (stcarrez@nerim.fr)
4
5    This file is part of GAS, the GNU Assembler.
6
7    GAS is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2, or (at your option)
10    any later version.
11
12    GAS is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GAS; see the file COPYING.  If not, write to
19    the Free Software Foundation, 59 Temple Place - Suite 330,
20    Boston, MA 02111-1307, USA.  */
21
22 #include "as.h"
23 #include "safe-ctype.h"
24 #include "subsegs.h"
25 #include "opcode/m68hc11.h"
26 #include "dwarf2dbg.h"
27 #include "elf/m68hc11.h"
28
29 const char comment_chars[] = ";!";
30 const char line_comment_chars[] = "#*";
31 const char line_separator_chars[] = "";
32
33 const char EXP_CHARS[] = "eE";
34 const char FLT_CHARS[] = "dD";
35
36 #define STATE_CONDITIONAL_BRANCH        (1)
37 #define STATE_PC_RELATIVE               (2)
38 #define STATE_INDEXED_OFFSET            (3)
39 #define STATE_INDEXED_PCREL             (4)
40 #define STATE_XBCC_BRANCH               (5)
41 #define STATE_CONDITIONAL_BRANCH_6812   (6)
42
43 #define STATE_BYTE                      (0)
44 #define STATE_BITS5                     (0)
45 #define STATE_WORD                      (1)
46 #define STATE_BITS9                     (1)
47 #define STATE_LONG                      (2)
48 #define STATE_BITS16                    (2)
49 #define STATE_UNDF                      (3)     /* Symbol undefined in pass1 */
50
51 /* This macro has no side-effects.  */
52 #define ENCODE_RELAX(what,length) (((what) << 2) + (length))
53 #define RELAX_STATE(s) ((s) >> 2)
54 #define RELAX_LENGTH(s) ((s) & 3)
55
56 #define IS_OPCODE(C1,C2)        (((C1) & 0x0FF) == ((C2) & 0x0FF))
57
58 /* This table describes how you change sizes for the various types of variable
59    size expressions.  This version only supports two kinds.  */
60
61 /* The fields are:
62    How far Forward this mode will reach.
63    How far Backward this mode will reach.
64    How many bytes this mode will add to the size of the frag.
65    Which mode to go to if the offset won't fit in this one.  */
66
67 relax_typeS md_relax_table[] = {
68   {1, 1, 0, 0},                 /* First entries aren't used.  */
69   {1, 1, 0, 0},                 /* For no good reason except.  */
70   {1, 1, 0, 0},                 /* that the VAX doesn't either.  */
71   {1, 1, 0, 0},
72
73   /* Relax for bcc <L>.
74      These insns are translated into b!cc +3 jmp L.  */
75   {(127), (-128), 0, ENCODE_RELAX (STATE_CONDITIONAL_BRANCH, STATE_WORD)},
76   {0, 0, 3, 0},
77   {1, 1, 0, 0},
78   {1, 1, 0, 0},
79
80   /* Relax for bsr <L> and bra <L>.
81      These insns are translated into jsr and jmp.  */
82   {(127), (-128), 0, ENCODE_RELAX (STATE_PC_RELATIVE, STATE_WORD)},
83   {0, 0, 1, 0},
84   {1, 1, 0, 0},
85   {1, 1, 0, 0},
86
87   /* Relax for indexed offset: 5-bits, 9-bits, 16-bits.  */
88   {(15), (-16), 0, ENCODE_RELAX (STATE_INDEXED_OFFSET, STATE_BITS9)},
89   {(255), (-256), 1, ENCODE_RELAX (STATE_INDEXED_OFFSET, STATE_BITS16)},
90   {0, 0, 2, 0},
91   {1, 1, 0, 0},
92
93   /* Relax for PC relative offset: 5-bits, 9-bits, 16-bits.
94      For the 9-bit case, there will be a -1 correction to take into
95      account the new byte that's why the range is -255..256.  */
96   {(15), (-16), 0, ENCODE_RELAX (STATE_INDEXED_PCREL, STATE_BITS9)},
97   {(256), (-255), 1, ENCODE_RELAX (STATE_INDEXED_PCREL, STATE_BITS16)},
98   {0, 0, 2, 0},
99   {1, 1, 0, 0},
100
101   /* Relax for dbeq/ibeq/tbeq r,<L>:
102      These insns are translated into db!cc +3 jmp L.  */
103   {(255), (-256), 0, ENCODE_RELAX (STATE_XBCC_BRANCH, STATE_WORD)},
104   {0, 0, 3, 0},
105   {1, 1, 0, 0},
106   {1, 1, 0, 0},
107
108   /* Relax for bcc <L> on 68HC12.
109      These insns are translated into lbcc <L>.  */
110   {(127), (-128), 0, ENCODE_RELAX (STATE_CONDITIONAL_BRANCH_6812, STATE_WORD)},
111   {0, 0, 2, 0},
112   {1, 1, 0, 0},
113   {1, 1, 0, 0},
114
115 };
116
117 /* 68HC11 and 68HC12 registers.  They are numbered according to the 68HC12.  */
118 typedef enum register_id {
119   REG_NONE = -1,
120   REG_A = 0,
121   REG_B = 1,
122   REG_CCR = 2,
123   REG_D = 4,
124   REG_X = 5,
125   REG_Y = 6,
126   REG_SP = 7,
127   REG_PC = 8
128 } register_id;
129
130 typedef struct operand {
131   expressionS exp;
132   register_id reg1;
133   register_id reg2;
134   int mode;
135 } operand;
136
137 struct m68hc11_opcode_def {
138   long format;
139   int min_operands;
140   int max_operands;
141   int nb_modes;
142   int used;
143   struct m68hc11_opcode *opcode;
144 };
145
146 static struct m68hc11_opcode_def *m68hc11_opcode_defs = 0;
147 static int m68hc11_nb_opcode_defs = 0;
148
149 typedef struct alias {
150   const char *name;
151   const char *alias;
152 } alias;
153
154 static alias alias_opcodes[] = {
155   {"cpd", "cmpd"},
156   {"cpx", "cmpx"},
157   {"cpy", "cmpy"},
158   {0, 0}
159 };
160
161 /* Local functions.  */
162 static register_id reg_name_search (char *);
163 static register_id register_name (void);
164 static int cmp_opcode (struct m68hc11_opcode *, struct m68hc11_opcode *);
165 static char *print_opcode_format (struct m68hc11_opcode *, int);
166 static char *skip_whites (char *);
167 static int check_range (long, int);
168 static void print_opcode_list (void);
169 static void get_default_target (void);
170 static void print_insn_format (char *);
171 static int get_operand (operand *, int, long);
172 static void fixup8 (expressionS *, int, int);
173 static void fixup16 (expressionS *, int, int);
174 static void fixup24 (expressionS *, int, int);
175 static unsigned char convert_branch (unsigned char);
176 static char *m68hc11_new_insn (int);
177 static void build_dbranch_insn (struct m68hc11_opcode *,
178                                 operand *, int, int);
179 static int build_indexed_byte (operand *, int, int);
180 static int build_reg_mode (operand *, int);
181
182 static struct m68hc11_opcode *find (struct m68hc11_opcode_def *,
183                                     operand *, int);
184 static struct m68hc11_opcode *find_opcode (struct m68hc11_opcode_def *,
185                                            operand *, int *);
186 static void build_jump_insn (struct m68hc11_opcode *, operand *, int, int);
187 static void build_insn (struct m68hc11_opcode *, operand *, int);
188 static int relaxable_symbol (symbolS *);
189
190 /* Pseudo op to indicate a relax group.  */
191 static void s_m68hc11_relax (int);
192
193 /* Pseudo op to control the ELF flags.  */
194 static void s_m68hc11_mode (int);
195
196 /* Mark the symbols with STO_M68HC12_FAR to indicate the functions
197    are using 'rtc' for returning.  It is necessary to use 'call'
198    to invoke them.  This is also used by the debugger to correctly
199    find the stack frame.  */
200 static void s_m68hc11_mark_symbol (int);
201
202 /* Controls whether relative branches can be turned into long branches.
203    When the relative offset is too large, the insn are changed:
204     bra -> jmp
205     bsr -> jsr
206     bcc -> b!cc +3
207            jmp L
208     dbcc -> db!cc +3
209             jmp L
210
211   Setting the flag forbidds this.  */
212 static short flag_fixed_branchs = 0;
213
214 /* Force to use long jumps (absolute) instead of relative branches.  */
215 static short flag_force_long_jumps = 0;
216
217 /* Change the direct addressing mode into an absolute addressing mode
218    when the insn does not support direct addressing.
219    For example, "clr *ZD0" is normally not possible and is changed
220    into "clr ZDO".  */
221 static short flag_strict_direct_addressing = 1;
222
223 /* When an opcode has invalid operand, print out the syntax of the opcode
224    to stderr.  */
225 static short flag_print_insn_syntax = 0;
226
227 /* Dumps the list of instructions with syntax and then exit:
228    1 -> Only dumps the list (sorted by name)
229    2 -> Generate an example (or test) that can be compiled.  */
230 static short flag_print_opcodes = 0;
231
232 /* Opcode hash table.  */
233 static struct hash_control *m68hc11_hash;
234
235 /* Current cpu (either cpu6811 or cpu6812).  This is determined automagically
236    by 'get_default_target' by looking at default BFD vector.  This is overridden
237    with the -m<cpu> option.  */
238 static int current_architecture = 0;
239
240 /* Default cpu determined by 'get_default_target'.  */
241 static const char *default_cpu;
242
243 /* Number of opcodes in the sorted table (filtered by current cpu).  */
244 static int num_opcodes;
245
246 /* The opcodes sorted by name and filtered by current cpu.  */
247 static struct m68hc11_opcode *m68hc11_sorted_opcodes;
248
249 /* ELF flags to set in the output file header.  */
250 static int elf_flags = E_M68HC11_F64;
251
252 /* These are the machine dependent pseudo-ops.  These are included so
253    the assembler can work on the output from the SUN C compiler, which
254    generates these.  */
255
256 /* This table describes all the machine specific pseudo-ops the assembler
257    has to support.  The fields are:
258    pseudo-op name without dot
259    function to call to execute this pseudo-op
260    Integer arg to pass to the function.  */
261 const pseudo_typeS md_pseudo_table[] = {
262   /* The following pseudo-ops are supported for MRI compatibility.  */
263   {"fcb", cons, 1},
264   {"fdb", cons, 2},
265   {"fcc", stringer, 1},
266   {"rmb", s_space, 0},
267
268   /* Motorola ALIS.  */
269   {"xrefb", s_ignore, 0}, /* Same as xref  */
270
271   /* Gcc driven relaxation.  */
272   {"relax", s_m68hc11_relax, 0},
273
274   /* .mode instruction (ala SH).  */
275   {"mode", s_m68hc11_mode, 0},
276
277   /* .far instruction.  */
278   {"far", s_m68hc11_mark_symbol, STO_M68HC12_FAR},
279
280   /* .interrupt instruction.  */
281   {"interrupt", s_m68hc11_mark_symbol, STO_M68HC12_INTERRUPT},
282
283   {0, 0, 0}
284 };
285 \f
286 /* Options and initialization.  */
287
288 const char *md_shortopts = "Sm:";
289
290 struct option md_longopts[] = {
291 #define OPTION_FORCE_LONG_BRANCH (OPTION_MD_BASE)
292   {"force-long-branchs", no_argument, NULL, OPTION_FORCE_LONG_BRANCH},
293
294 #define OPTION_SHORT_BRANCHS     (OPTION_MD_BASE + 1)
295   {"short-branchs", no_argument, NULL, OPTION_SHORT_BRANCHS},
296
297 #define OPTION_STRICT_DIRECT_MODE  (OPTION_MD_BASE + 2)
298   {"strict-direct-mode", no_argument, NULL, OPTION_STRICT_DIRECT_MODE},
299
300 #define OPTION_PRINT_INSN_SYNTAX  (OPTION_MD_BASE + 3)
301   {"print-insn-syntax", no_argument, NULL, OPTION_PRINT_INSN_SYNTAX},
302
303 #define OPTION_PRINT_OPCODES  (OPTION_MD_BASE + 4)
304   {"print-opcodes", no_argument, NULL, OPTION_PRINT_OPCODES},
305
306 #define OPTION_GENERATE_EXAMPLE  (OPTION_MD_BASE + 5)
307   {"generate-example", no_argument, NULL, OPTION_GENERATE_EXAMPLE},
308
309 #define OPTION_MSHORT  (OPTION_MD_BASE + 6)
310   {"mshort", no_argument, NULL, OPTION_MSHORT},
311
312 #define OPTION_MLONG  (OPTION_MD_BASE + 7)
313   {"mlong", no_argument, NULL, OPTION_MLONG},
314
315 #define OPTION_MSHORT_DOUBLE  (OPTION_MD_BASE + 8)
316   {"mshort-double", no_argument, NULL, OPTION_MSHORT_DOUBLE},
317
318 #define OPTION_MLONG_DOUBLE  (OPTION_MD_BASE + 9)
319   {"mlong-double", no_argument, NULL, OPTION_MLONG_DOUBLE},
320
321   {NULL, no_argument, NULL, 0}
322 };
323 size_t md_longopts_size = sizeof (md_longopts);
324
325 /* Get the target cpu for the assembler.  This is based on the configure
326    options and on the -m68hc11/-m68hc12 option.  If no option is specified,
327    we must get the default.  */
328 const char *
329 m68hc11_arch_format (void)
330 {
331   get_default_target ();
332   if (current_architecture & cpu6811)
333     return "elf32-m68hc11";
334   else
335     return "elf32-m68hc12";
336 }
337
338 enum bfd_architecture
339 m68hc11_arch (void)
340 {
341   get_default_target ();
342   if (current_architecture & cpu6811)
343     return bfd_arch_m68hc11;
344   else
345     return bfd_arch_m68hc12;
346 }
347
348 int
349 m68hc11_mach (void)
350 {
351   return 0;
352 }
353
354 /* Listing header selected according to cpu.  */
355 const char *
356 m68hc11_listing_header (void)
357 {
358   if (current_architecture & cpu6811)
359     return "M68HC11 GAS ";
360   else
361     return "M68HC12 GAS ";
362 }
363
364 void
365 md_show_usage (FILE *stream)
366 {
367   get_default_target ();
368   fprintf (stream, _("\
369 Motorola 68HC11/68HC12/68HCS12 options:\n\
370   -m68hc11 | -m68hc12 |\n\
371   -m68hcs12               specify the processor [default %s]\n\
372   -mshort                 use 16-bit int ABI (default)\n\
373   -mlong                  use 32-bit int ABI\n\
374   -mshort-double          use 32-bit double ABI\n\
375   -mlong-double           use 64-bit double ABI (default)\n\
376   --force-long-branchs    always turn relative branchs into absolute ones\n\
377   -S,--short-branchs      do not turn relative branchs into absolute ones\n\
378                           when the offset is out of range\n\
379   --strict-direct-mode    do not turn the direct mode into extended mode\n\
380                           when the instruction does not support direct mode\n\
381   --print-insn-syntax     print the syntax of instruction in case of error\n\
382   --print-opcodes         print the list of instructions with syntax\n\
383   --generate-example      generate an example of each instruction\n\
384                           (used for testing)\n"), default_cpu);
385
386 }
387
388 /* Try to identify the default target based on the BFD library.  */
389 static void
390 get_default_target (void)
391 {
392   const bfd_target *target;
393   bfd abfd;
394
395   if (current_architecture != 0)
396     return;
397
398   default_cpu = "unknown";
399   target = bfd_find_target (0, &abfd);
400   if (target && target->name)
401     {
402       if (strcmp (target->name, "elf32-m68hc12") == 0)
403         {
404           current_architecture = cpu6812;
405           default_cpu = "m68hc12";
406         }
407       else if (strcmp (target->name, "elf32-m68hc11") == 0)
408         {
409           current_architecture = cpu6811;
410           default_cpu = "m68hc11";
411         }
412       else
413         {
414           as_bad (_("Default target `%s' is not supported."), target->name);
415         }
416     }
417 }
418
419 void
420 m68hc11_print_statistics (FILE *file)
421 {
422   int i;
423   struct m68hc11_opcode_def *opc;
424
425   hash_print_statistics (file, "opcode table", m68hc11_hash);
426
427   opc = m68hc11_opcode_defs;
428   if (opc == 0 || m68hc11_nb_opcode_defs == 0)
429     return;
430
431   /* Dump the opcode statistics table.  */
432   fprintf (file, _("Name   # Modes  Min ops  Max ops  Modes mask  # Used\n"));
433   for (i = 0; i < m68hc11_nb_opcode_defs; i++, opc++)
434     {
435       fprintf (file, "%-7.7s  %5d  %7d  %7d  0x%08lx  %7d\n",
436                opc->opcode->name,
437                opc->nb_modes,
438                opc->min_operands, opc->max_operands, opc->format, opc->used);
439     }
440 }
441
442 int
443 md_parse_option (int c, char *arg)
444 {
445   get_default_target ();
446   switch (c)
447     {
448       /* -S means keep external to 2 bit offset rather than 16 bit one.  */
449     case OPTION_SHORT_BRANCHS:
450     case 'S':
451       flag_fixed_branchs = 1;
452       break;
453
454     case OPTION_FORCE_LONG_BRANCH:
455       flag_force_long_jumps = 1;
456       break;
457
458     case OPTION_PRINT_INSN_SYNTAX:
459       flag_print_insn_syntax = 1;
460       break;
461
462     case OPTION_PRINT_OPCODES:
463       flag_print_opcodes = 1;
464       break;
465
466     case OPTION_STRICT_DIRECT_MODE:
467       flag_strict_direct_addressing = 0;
468       break;
469
470     case OPTION_GENERATE_EXAMPLE:
471       flag_print_opcodes = 2;
472       break;
473
474     case OPTION_MSHORT:
475       elf_flags &= ~E_M68HC11_I32;
476       break;
477
478     case OPTION_MLONG:
479       elf_flags |= E_M68HC11_I32;
480       break;
481
482     case OPTION_MSHORT_DOUBLE:
483       elf_flags &= ~E_M68HC11_F64;
484       break;
485
486     case OPTION_MLONG_DOUBLE:
487       elf_flags |= E_M68HC11_F64;
488       break;
489
490     case 'm':
491       if (strcasecmp (arg, "68hc11") == 0)
492         current_architecture = cpu6811;
493       else if (strcasecmp (arg, "68hc12") == 0)
494         current_architecture = cpu6812;
495       else if (strcasecmp (arg, "68hcs12") == 0)
496         current_architecture = cpu6812 | cpu6812s;
497       else
498         as_bad (_("Option `%s' is not recognized."), arg);
499       break;
500
501     default:
502       return 0;
503     }
504
505   return 1;
506 }
507 \f
508 symbolS *
509 md_undefined_symbol (char *name ATTRIBUTE_UNUSED)
510 {
511   return 0;
512 }
513
514 /* Equal to MAX_PRECISION in atof-ieee.c.  */
515 #define MAX_LITTLENUMS 6
516
517 /* Turn a string in input_line_pointer into a floating point constant
518    of type TYPE, and store the appropriate bytes in *LITP.  The number
519    of LITTLENUMS emitted is stored in *SIZEP.  An error message is
520    returned, or NULL on OK.  */
521 char *
522 md_atof (int type, char *litP, int *sizeP)
523 {
524   int prec;
525   LITTLENUM_TYPE words[MAX_LITTLENUMS];
526   LITTLENUM_TYPE *wordP;
527   char *t;
528
529   switch (type)
530     {
531     case 'f':
532     case 'F':
533     case 's':
534     case 'S':
535       prec = 2;
536       break;
537
538     case 'd':
539     case 'D':
540     case 'r':
541     case 'R':
542       prec = 4;
543       break;
544
545     case 'x':
546     case 'X':
547       prec = 6;
548       break;
549
550     case 'p':
551     case 'P':
552       prec = 6;
553       break;
554
555     default:
556       *sizeP = 0;
557       return _("Bad call to MD_ATOF()");
558     }
559   t = atof_ieee (input_line_pointer, type, words);
560   if (t)
561     input_line_pointer = t;
562
563   *sizeP = prec * sizeof (LITTLENUM_TYPE);
564   for (wordP = words; prec--;)
565     {
566       md_number_to_chars (litP, (long) (*wordP++), sizeof (LITTLENUM_TYPE));
567       litP += sizeof (LITTLENUM_TYPE);
568     }
569   return 0;
570 }
571
572 valueT
573 md_section_align (asection *seg, valueT addr)
574 {
575   int align = bfd_get_section_alignment (stdoutput, seg);
576   return ((addr + (1 << align) - 1) & (-1 << align));
577 }
578
579 static int
580 cmp_opcode (struct m68hc11_opcode *op1, struct m68hc11_opcode *op2)
581 {
582   return strcmp (op1->name, op2->name);
583 }
584
585 #define IS_CALL_SYMBOL(MODE) \
586 (((MODE) & (M6812_OP_PAGE|M6811_OP_IND16)) \
587   == ((M6812_OP_PAGE|M6811_OP_IND16)))
588
589 /* Initialize the assembler.  Create the opcode hash table
590    (sorted on the names) with the M6811 opcode table
591    (from opcode library).  */
592 void
593 md_begin (void)
594 {
595   char *prev_name = "";
596   struct m68hc11_opcode *opcodes;
597   struct m68hc11_opcode_def *opc = 0;
598   int i, j;
599
600   get_default_target ();
601
602   m68hc11_hash = hash_new ();
603
604   /* Get a writable copy of the opcode table and sort it on the names.  */
605   opcodes = (struct m68hc11_opcode *) xmalloc (m68hc11_num_opcodes *
606                                                sizeof (struct
607                                                        m68hc11_opcode));
608   m68hc11_sorted_opcodes = opcodes;
609   num_opcodes = 0;
610   for (i = 0; i < m68hc11_num_opcodes; i++)
611     {
612       if (m68hc11_opcodes[i].arch & current_architecture)
613         {
614           opcodes[num_opcodes] = m68hc11_opcodes[i];
615           if (opcodes[num_opcodes].name[0] == 'b'
616               && opcodes[num_opcodes].format & M6811_OP_JUMP_REL
617               && !(opcodes[num_opcodes].format & M6811_OP_BITMASK))
618             {
619               num_opcodes++;
620               opcodes[num_opcodes] = m68hc11_opcodes[i];
621             }
622           num_opcodes++;
623           for (j = 0; alias_opcodes[j].name != 0; j++)
624             if (strcmp (m68hc11_opcodes[i].name, alias_opcodes[j].name) == 0)
625               {
626                 opcodes[num_opcodes] = m68hc11_opcodes[i];
627                 opcodes[num_opcodes].name = alias_opcodes[j].alias;
628                 num_opcodes++;
629                 break;
630               }
631         }
632     }
633   qsort (opcodes, num_opcodes, sizeof (struct m68hc11_opcode),
634          (int (*) (const void*, const void*)) cmp_opcode);
635
636   opc = (struct m68hc11_opcode_def *)
637     xmalloc (num_opcodes * sizeof (struct m68hc11_opcode_def));
638   m68hc11_opcode_defs = opc--;
639
640   /* Insert unique names into hash table.  The M6811 instruction set
641      has several identical opcode names that have different opcodes based
642      on the operands.  This hash table then provides a quick index to
643      the first opcode with a particular name in the opcode table.  */
644   for (i = 0; i < num_opcodes; i++, opcodes++)
645     {
646       int expect;
647
648       if (strcmp (prev_name, opcodes->name))
649         {
650           prev_name = (char *) opcodes->name;
651
652           opc++;
653           opc->format = 0;
654           opc->min_operands = 100;
655           opc->max_operands = 0;
656           opc->nb_modes = 0;
657           opc->opcode = opcodes;
658           opc->used = 0;
659           hash_insert (m68hc11_hash, opcodes->name, opc);
660         }
661       opc->nb_modes++;
662       opc->format |= opcodes->format;
663
664       /* See how many operands this opcode needs.  */
665       expect = 0;
666       if (opcodes->format & M6811_OP_MASK)
667         expect++;
668       if (opcodes->format & M6811_OP_BITMASK)
669         expect++;
670       if (opcodes->format & (M6811_OP_JUMP_REL | M6812_OP_JUMP_REL16))
671         expect++;
672       if (opcodes->format & (M6812_OP_IND16_P2 | M6812_OP_IDX_P2))
673         expect++;
674       /* Special case for call instruction.  */
675       if ((opcodes->format & M6812_OP_PAGE)
676           && !(opcodes->format & M6811_OP_IND16))
677         expect++;
678
679       if (expect < opc->min_operands)
680         opc->min_operands = expect;
681       if (IS_CALL_SYMBOL (opcodes->format))
682          expect++;
683       if (expect > opc->max_operands)
684         opc->max_operands = expect;
685     }
686   opc++;
687   m68hc11_nb_opcode_defs = opc - m68hc11_opcode_defs;
688
689   if (flag_print_opcodes)
690     {
691       print_opcode_list ();
692       exit (EXIT_SUCCESS);
693     }
694 }
695
696 void
697 m68hc11_init_after_args (void)
698 {
699 }
700 \f
701 /* Builtin help.  */
702
703 /* Return a string that represents the operand format for the instruction.
704    When example is true, this generates an example of operand.  This is used
705    to give an example and also to generate a test.  */
706 static char *
707 print_opcode_format (struct m68hc11_opcode *opcode, int example)
708 {
709   static char buf[128];
710   int format = opcode->format;
711   char *p;
712
713   p = buf;
714   buf[0] = 0;
715   if (format & M6811_OP_IMM8)
716     {
717       if (example)
718         sprintf (p, "#%d", rand () & 0x0FF);
719       else
720         strcpy (p, _("#<imm8>"));
721       p = &p[strlen (p)];
722     }
723
724   if (format & M6811_OP_IMM16)
725     {
726       if (example)
727         sprintf (p, "#%d", rand () & 0x0FFFF);
728       else
729         strcpy (p, _("#<imm16>"));
730       p = &p[strlen (p)];
731     }
732
733   if (format & M6811_OP_IX)
734     {
735       if (example)
736         sprintf (p, "%d,X", rand () & 0x0FF);
737       else
738         strcpy (p, _("<imm8>,X"));
739       p = &p[strlen (p)];
740     }
741
742   if (format & M6811_OP_IY)
743     {
744       if (example)
745         sprintf (p, "%d,X", rand () & 0x0FF);
746       else
747         strcpy (p, _("<imm8>,X"));
748       p = &p[strlen (p)];
749     }
750
751   if (format & M6812_OP_IDX)
752     {
753       if (example)
754         sprintf (p, "%d,X", rand () & 0x0FF);
755       else
756         strcpy (p, "n,r");
757       p = &p[strlen (p)];
758     }
759
760   if (format & M6812_OP_PAGE)
761     {
762       if (example)
763         sprintf (p, ", %d", rand () & 0x0FF);
764       else
765         strcpy (p, ", <page>");
766       p = &p[strlen (p)];
767     }
768
769   if (format & M6811_OP_DIRECT)
770     {
771       if (example)
772         sprintf (p, "*Z%d", rand () & 0x0FF);
773       else
774         strcpy (p, _("*<abs8>"));
775       p = &p[strlen (p)];
776     }
777
778   if (format & M6811_OP_BITMASK)
779     {
780       if (buf[0])
781         *p++ = ' ';
782
783       if (example)
784         sprintf (p, "#$%02x", rand () & 0x0FF);
785       else
786         strcpy (p, _("#<mask>"));
787
788       p = &p[strlen (p)];
789       if (format & M6811_OP_JUMP_REL)
790         *p++ = ' ';
791     }
792
793   if (format & M6811_OP_IND16)
794     {
795       if (example)
796         sprintf (p, _("symbol%d"), rand () & 0x0FF);
797       else
798         strcpy (p, _("<abs>"));
799
800       p = &p[strlen (p)];
801     }
802
803   if (format & (M6811_OP_JUMP_REL | M6812_OP_JUMP_REL16))
804     {
805       if (example)
806         {
807           if (format & M6811_OP_BITMASK)
808             {
809               sprintf (p, ".+%d", rand () & 0x7F);
810             }
811           else
812             {
813               sprintf (p, "L%d", rand () & 0x0FF);
814             }
815         }
816       else
817         strcpy (p, _("<label>"));
818     }
819
820   return buf;
821 }
822
823 /* Prints the list of instructions with the possible operands.  */
824 static void
825 print_opcode_list (void)
826 {
827   int i;
828   char *prev_name = "";
829   struct m68hc11_opcode *opcodes;
830   int example = flag_print_opcodes == 2;
831
832   if (example)
833     printf (_("# Example of `%s' instructions\n\t.sect .text\n_start:\n"),
834             default_cpu);
835
836   opcodes = m68hc11_sorted_opcodes;
837
838   /* Walk the list sorted on names (by md_begin).  We only report
839      one instruction per line, and we collect the different operand
840      formats.  */
841   for (i = 0; i < num_opcodes; i++, opcodes++)
842     {
843       char *fmt = print_opcode_format (opcodes, example);
844
845       if (example)
846         {
847           printf ("L%d:\t", i);
848           printf ("%s %s\n", opcodes->name, fmt);
849         }
850       else
851         {
852           if (strcmp (prev_name, opcodes->name))
853             {
854               if (i > 0)
855                 printf ("\n");
856
857               printf ("%-5.5s ", opcodes->name);
858               prev_name = (char *) opcodes->name;
859             }
860           if (fmt[0])
861             printf ("  [%s]", fmt);
862         }
863     }
864   printf ("\n");
865 }
866
867 /* Print the instruction format.  This operation is called when some
868    instruction is not correct.  Instruction format is printed as an
869    error message.  */
870 static void
871 print_insn_format (char *name)
872 {
873   struct m68hc11_opcode_def *opc;
874   struct m68hc11_opcode *opcode;
875   char buf[128];
876
877   opc = (struct m68hc11_opcode_def *) hash_find (m68hc11_hash, name);
878   if (opc == NULL)
879     {
880       as_bad (_("Instruction `%s' is not recognized."), name);
881       return;
882     }
883   opcode = opc->opcode;
884
885   as_bad (_("Instruction formats for `%s':"), name);
886   do
887     {
888       char *fmt;
889
890       fmt = print_opcode_format (opcode, 0);
891       sprintf (buf, "\t%-5.5s %s", opcode->name, fmt);
892
893       as_bad ("%s", buf);
894       opcode++;
895     }
896   while (strcmp (opcode->name, name) == 0);
897 }
898 \f
899 /* Analysis of 68HC11 and 68HC12 operands.  */
900
901 /* reg_name_search() finds the register number given its name.
902    Returns the register number or REG_NONE on failure.  */
903 static register_id
904 reg_name_search (char *name)
905 {
906   if (strcasecmp (name, "x") == 0 || strcasecmp (name, "ix") == 0)
907     return REG_X;
908   if (strcasecmp (name, "y") == 0 || strcasecmp (name, "iy") == 0)
909     return REG_Y;
910   if (strcasecmp (name, "a") == 0)
911     return REG_A;
912   if (strcasecmp (name, "b") == 0)
913     return REG_B;
914   if (strcasecmp (name, "d") == 0)
915     return REG_D;
916   if (strcasecmp (name, "sp") == 0)
917     return REG_SP;
918   if (strcasecmp (name, "pc") == 0)
919     return REG_PC;
920   if (strcasecmp (name, "ccr") == 0)
921     return REG_CCR;
922
923   return REG_NONE;
924 }
925
926 static char *
927 skip_whites (char *p)
928 {
929   while (*p == ' ' || *p == '\t')
930     p++;
931
932   return p;
933 }
934
935 /* Check the string at input_line_pointer
936    to see if it is a valid register name.  */
937 static register_id
938 register_name (void)
939 {
940   register_id reg_number;
941   char c, *p = input_line_pointer;
942
943   if (!is_name_beginner (*p++))
944     return REG_NONE;
945
946   while (is_part_of_name (*p++))
947     continue;
948
949   c = *--p;
950   if (c)
951     *p++ = 0;
952
953   /* Look to see if it's in the register table.  */
954   reg_number = reg_name_search (input_line_pointer);
955   if (reg_number != REG_NONE)
956     {
957       if (c)
958         *--p = c;
959
960       input_line_pointer = p;
961       return reg_number;
962     }
963   if (c)
964     *--p = c;
965
966   return reg_number;
967 }
968 #define M6811_OP_CALL_ADDR    0x00800000
969 #define M6811_OP_PAGE_ADDR    0x04000000
970
971 /* Parse a string of operands and return an array of expressions.
972
973    Operand      mode[0]         mode[1]       exp[0]       exp[1]
974    #n           M6811_OP_IMM16  -             O_*
975    *<exp>       M6811_OP_DIRECT -             O_*
976    .{+-}<exp>   M6811_OP_JUMP_REL -           O_*
977    <exp>        M6811_OP_IND16  -             O_*
978    ,r N,r       M6812_OP_IDX    M6812_OP_REG  O_constant   O_register
979    n,-r         M6812_PRE_DEC   M6812_OP_REG  O_constant   O_register
980    n,+r         M6812_PRE_INC   " "
981    n,r-         M6812_POST_DEC  " "
982    n,r+         M6812_POST_INC  " "
983    A,r B,r D,r  M6811_OP_REG    M6812_OP_REG  O_register   O_register
984    [D,r]        M6811_OP_D_IDX  M6812_OP_REG  O_register   O_register
985    [n,r]        M6811_OP_D_IDX_2 M6812_OP_REG  O_constant   O_register  */
986 static int
987 get_operand (operand *oper, int which, long opmode)
988 {
989   char *p = input_line_pointer;
990   int mode;
991   register_id reg;
992
993   oper->exp.X_op = O_absent;
994   oper->reg1 = REG_NONE;
995   oper->reg2 = REG_NONE;
996   mode = M6811_OP_NONE;
997
998   p = skip_whites (p);
999
1000   if (*p == 0 || *p == '\n' || *p == '\r')
1001     {
1002       input_line_pointer = p;
1003       return 0;
1004     }
1005
1006   if (*p == '*' && (opmode & (M6811_OP_DIRECT | M6811_OP_IND16)))
1007     {
1008       mode = M6811_OP_DIRECT;
1009       p++;
1010     }
1011   else if (*p == '#')
1012     {
1013       if (!(opmode & (M6811_OP_IMM8 | M6811_OP_IMM16 | M6811_OP_BITMASK)))
1014         {
1015           as_bad (_("Immediate operand is not allowed for operand %d."),
1016                   which);
1017           return -1;
1018         }
1019
1020       mode = M6811_OP_IMM16;
1021       p++;
1022       if (strncmp (p, "%hi", 3) == 0)
1023         {
1024           p += 3;
1025           mode |= M6811_OP_HIGH_ADDR;
1026         }
1027       else if (strncmp (p, "%lo", 3) == 0)
1028         {
1029           p += 3;
1030           mode |= M6811_OP_LOW_ADDR;
1031         }
1032       /* %page modifier is used to obtain only the page number
1033          of the address of a function.  */
1034       else if (strncmp (p, "%page", 5) == 0)
1035         {
1036           p += 5;
1037           mode |= M6811_OP_PAGE_ADDR;
1038         }
1039
1040       /* %addr modifier is used to obtain the physical address part
1041          of the function (16-bit).  For 68HC12 the function will be
1042          mapped in the 16K window at 0x8000 and the value will be
1043          within that window (although the function address may not fit
1044          in 16-bit).  See bfd/elf32-m68hc12.c for the translation.  */
1045       else if (strncmp (p, "%addr", 5) == 0)
1046         {
1047           p += 5;
1048           mode |= M6811_OP_CALL_ADDR;
1049         }
1050     }
1051   else if (*p == '.' && (p[1] == '+' || p[1] == '-'))
1052     {
1053       p++;
1054       mode = M6811_OP_JUMP_REL;
1055     }
1056   else if (*p == '[')
1057     {
1058       if (current_architecture & cpu6811)
1059         as_bad (_("Indirect indexed addressing is not valid for 68HC11."));
1060
1061       p++;
1062       mode = M6812_OP_D_IDX;
1063       p = skip_whites (p);
1064     }
1065   else if (*p == ',')           /* Special handling of ,x and ,y.  */
1066     {
1067       p++;
1068       input_line_pointer = p;
1069
1070       reg = register_name ();
1071       if (reg != REG_NONE)
1072         {
1073           oper->reg1 = reg;
1074           oper->exp.X_op = O_constant;
1075           oper->exp.X_add_number = 0;
1076           oper->mode = M6812_OP_IDX;
1077           return 1;
1078         }
1079       as_bad (_("Spurious `,' or bad indirect register addressing mode."));
1080       return -1;
1081     }
1082   /* Handle 68HC12 page specification in 'call foo,%page(bar)'.  */
1083   else if ((opmode & M6812_OP_PAGE) && strncmp (p, "%page", 5) == 0)
1084     {
1085       p += 5;
1086       mode = M6811_OP_PAGE_ADDR | M6812_OP_PAGE | M6811_OP_IND16;
1087     }
1088   input_line_pointer = p;
1089
1090   if (mode == M6811_OP_NONE || mode == M6812_OP_D_IDX)
1091     reg = register_name ();
1092   else
1093     reg = REG_NONE;
1094
1095   if (reg != REG_NONE)
1096     {
1097       p = skip_whites (input_line_pointer);
1098       if (*p == ']' && mode == M6812_OP_D_IDX)
1099         {
1100           as_bad
1101             (_("Missing second register or offset for indexed-indirect mode."));
1102           return -1;
1103         }
1104
1105       oper->reg1 = reg;
1106       oper->mode = mode | M6812_OP_REG;
1107       if (*p != ',')
1108         {
1109           if (mode == M6812_OP_D_IDX)
1110             {
1111               as_bad (_("Missing second register for indexed-indirect mode."));
1112               return -1;
1113             }
1114           return 1;
1115         }
1116
1117       p++;
1118       input_line_pointer = p;
1119       reg = register_name ();
1120       if (reg != REG_NONE)
1121         {
1122           p = skip_whites (input_line_pointer);
1123           if (mode == M6812_OP_D_IDX)
1124             {
1125               if (*p != ']')
1126                 {
1127                   as_bad (_("Missing `]' to close indexed-indirect mode."));
1128                   return -1;
1129                 }
1130               p++;
1131               oper->mode = M6812_OP_D_IDX;
1132             }
1133           input_line_pointer = p;
1134
1135           oper->reg2 = reg;
1136           return 1;
1137         }
1138       return 1;
1139     }
1140
1141   /* In MRI mode, isolate the operand because we can't distinguish
1142      operands from comments.  */
1143   if (flag_mri)
1144     {
1145       char c = 0;
1146
1147       p = skip_whites (p);
1148       while (*p && *p != ' ' && *p != '\t')
1149         p++;
1150
1151       if (*p)
1152         {
1153           c = *p;
1154           *p = 0;
1155         }
1156
1157       /* Parse as an expression.  */
1158       expression (&oper->exp);
1159
1160       if (c)
1161         {
1162           *p = c;
1163         }
1164     }
1165   else
1166     {
1167       expression (&oper->exp);
1168     }
1169
1170   if (oper->exp.X_op == O_illegal)
1171     {
1172       as_bad (_("Illegal operand."));
1173       return -1;
1174     }
1175   else if (oper->exp.X_op == O_absent)
1176     {
1177       as_bad (_("Missing operand."));
1178       return -1;
1179     }
1180
1181   p = input_line_pointer;
1182
1183   if (mode == M6811_OP_NONE || mode == M6811_OP_DIRECT
1184       || mode == M6812_OP_D_IDX)
1185     {
1186       p = skip_whites (input_line_pointer);
1187
1188       if (*p == ',')
1189         {
1190           int possible_mode = M6811_OP_NONE;
1191           char *old_input_line;
1192
1193           old_input_line = p;
1194           p++;
1195
1196           /* 68HC12 pre increment or decrement.  */
1197           if (mode == M6811_OP_NONE)
1198             {
1199               if (*p == '-')
1200                 {
1201                   possible_mode = M6812_PRE_DEC;
1202                   p++;
1203                 }
1204               else if (*p == '+')
1205                 {
1206                   possible_mode = M6812_PRE_INC;
1207                   p++;
1208                 }
1209               p = skip_whites (p);
1210             }
1211           input_line_pointer = p;
1212           reg = register_name ();
1213
1214           /* Backtrack if we have a valid constant expression and
1215              it does not correspond to the offset of the 68HC12 indexed
1216              addressing mode (as in N,x).  */
1217           if (reg == REG_NONE && mode == M6811_OP_NONE
1218               && possible_mode != M6811_OP_NONE)
1219             {
1220               oper->mode = M6811_OP_IND16 | M6811_OP_JUMP_REL;
1221               input_line_pointer = skip_whites (old_input_line);
1222               return 1;
1223             }
1224
1225           if (possible_mode != M6811_OP_NONE)
1226             mode = possible_mode;
1227
1228           if ((current_architecture & cpu6811)
1229               && possible_mode != M6811_OP_NONE)
1230             as_bad (_("Pre-increment mode is not valid for 68HC11"));
1231           /* Backtrack.  */
1232           if (which == 0 && opmode & M6812_OP_IDX_P2
1233               && reg != REG_X && reg != REG_Y
1234               && reg != REG_PC && reg != REG_SP)
1235             {
1236               reg = REG_NONE;
1237               input_line_pointer = p;
1238             }
1239
1240           if (reg == REG_NONE && mode != M6811_OP_DIRECT
1241               && !(mode == M6811_OP_NONE && opmode & M6811_OP_IND16))
1242             {
1243               as_bad (_("Wrong register in register indirect mode."));
1244               return -1;
1245             }
1246           if (mode == M6812_OP_D_IDX)
1247             {
1248               p = skip_whites (input_line_pointer);
1249               if (*p++ != ']')
1250                 {
1251                   as_bad (_("Missing `]' to close register indirect operand."));
1252                   return -1;
1253                 }
1254               input_line_pointer = p;
1255               oper->reg1 = reg;
1256               oper->mode = M6812_OP_D_IDX_2;
1257               return 1;
1258             }
1259           if (reg != REG_NONE)
1260             {
1261               oper->reg1 = reg;
1262               if (mode == M6811_OP_NONE)
1263                 {
1264                   p = input_line_pointer;
1265                   if (*p == '-')
1266                     {
1267                       mode = M6812_POST_DEC;
1268                       p++;
1269                       if (current_architecture & cpu6811)
1270                         as_bad
1271                           (_("Post-decrement mode is not valid for 68HC11."));
1272                     }
1273                   else if (*p == '+')
1274                     {
1275                       mode = M6812_POST_INC;
1276                       p++;
1277                       if (current_architecture & cpu6811)
1278                         as_bad
1279                           (_("Post-increment mode is not valid for 68HC11."));
1280                     }
1281                   else
1282                     mode = M6812_OP_IDX;
1283
1284                   input_line_pointer = p;
1285                 }
1286               else
1287                 mode |= M6812_OP_IDX;
1288
1289               oper->mode = mode;
1290               return 1;
1291             }
1292           input_line_pointer = old_input_line;
1293         }
1294
1295       if (mode == M6812_OP_D_IDX_2)
1296         {
1297           as_bad (_("Invalid indexed indirect mode."));
1298           return -1;
1299         }
1300     }
1301
1302   /* If the mode is not known until now, this is either a label
1303      or an indirect address.  */
1304   if (mode == M6811_OP_NONE)
1305     mode = M6811_OP_IND16 | M6811_OP_JUMP_REL;
1306
1307   p = input_line_pointer;
1308   while (*p == ' ' || *p == '\t')
1309     p++;
1310   input_line_pointer = p;
1311   oper->mode = mode;
1312
1313   return 1;
1314 }
1315
1316 #define M6812_AUTO_INC_DEC (M6812_PRE_INC | M6812_PRE_DEC \
1317                             | M6812_POST_INC | M6812_POST_DEC)
1318
1319 /* Checks that the number 'num' fits for a given mode.  */
1320 static int
1321 check_range (long num, int mode)
1322 {
1323   /* Auto increment and decrement are ok for [-8..8] without 0.  */
1324   if (mode & M6812_AUTO_INC_DEC)
1325     return (num != 0 && num <= 8 && num >= -8);
1326
1327   /* The 68HC12 supports 5, 9 and 16-bit offsets.  */
1328   if (mode & (M6812_INDEXED_IND | M6812_INDEXED | M6812_OP_IDX))
1329     mode = M6811_OP_IND16;
1330
1331   if (mode & M6812_OP_JUMP_REL16)
1332     mode = M6811_OP_IND16;
1333
1334   mode &= ~M6811_OP_BRANCH;
1335   switch (mode)
1336     {
1337     case M6811_OP_IX:
1338     case M6811_OP_IY:
1339     case M6811_OP_DIRECT:
1340       return (num >= 0 && num <= 255) ? 1 : 0;
1341
1342     case M6811_OP_BITMASK:
1343     case M6811_OP_IMM8:
1344     case M6812_OP_PAGE:
1345       return (((num & 0xFFFFFF00) == 0) || ((num & 0xFFFFFF00) == 0xFFFFFF00))
1346         ? 1 : 0;
1347
1348     case M6811_OP_JUMP_REL:
1349       return (num >= -128 && num <= 127) ? 1 : 0;
1350
1351     case M6811_OP_IND16:
1352     case M6811_OP_IND16 | M6812_OP_PAGE:
1353     case M6811_OP_IMM16:
1354       return (((num & 0xFFFF0000) == 0) || ((num & 0xFFFF0000) == 0xFFFF0000))
1355         ? 1 : 0;
1356
1357     case M6812_OP_IBCC_MARKER:
1358     case M6812_OP_TBCC_MARKER:
1359     case M6812_OP_DBCC_MARKER:
1360       return (num >= -256 && num <= 255) ? 1 : 0;
1361
1362     case M6812_OP_TRAP_ID:
1363       return ((num >= 0x30 && num <= 0x39)
1364               || (num >= 0x40 && num <= 0x0ff)) ? 1 : 0;
1365
1366     default:
1367       return 0;
1368     }
1369 }
1370 \f
1371 /* Gas fixup generation.  */
1372
1373 /* Put a 1 byte expression described by 'oper'.  If this expression contains
1374    unresolved symbols, generate an 8-bit fixup.  */
1375 static void
1376 fixup8 (expressionS *oper, int mode, int opmode)
1377 {
1378   char *f;
1379
1380   f = frag_more (1);
1381
1382   if (oper->X_op == O_constant)
1383     {
1384       if (mode & M6812_OP_TRAP_ID
1385           && !check_range (oper->X_add_number, M6812_OP_TRAP_ID))
1386         {
1387           static char trap_id_warn_once = 0;
1388
1389           as_bad (_("Trap id `%ld' is out of range."), oper->X_add_number);
1390           if (trap_id_warn_once == 0)
1391             {
1392               trap_id_warn_once = 1;
1393               as_bad (_("Trap id must be within [0x30..0x39] or [0x40..0xff]."));
1394             }
1395         }
1396
1397       if (!(mode & M6812_OP_TRAP_ID)
1398           && !check_range (oper->X_add_number, mode))
1399         {
1400           as_bad (_("Operand out of 8-bit range: `%ld'."), oper->X_add_number);
1401         }
1402       number_to_chars_bigendian (f, oper->X_add_number & 0x0FF, 1);
1403     }
1404   else if (oper->X_op != O_register)
1405     {
1406       if (mode & M6812_OP_TRAP_ID)
1407         as_bad (_("The trap id must be a constant."));
1408
1409       if (mode == M6811_OP_JUMP_REL)
1410         {
1411           fixS *fixp;
1412
1413           fixp = fix_new_exp (frag_now, f - frag_now->fr_literal, 1,
1414                               oper, TRUE, BFD_RELOC_8_PCREL);
1415           fixp->fx_pcrel_adjust = 1;
1416         }
1417       else
1418         {
1419           fixS *fixp;
1420           int reloc;
1421
1422           /* Now create an 8-bit fixup.  If there was some %hi, %lo
1423              or %page modifier, generate the reloc accordingly.  */
1424           if (opmode & M6811_OP_HIGH_ADDR)
1425             reloc = BFD_RELOC_M68HC11_HI8;
1426           else if (opmode & M6811_OP_LOW_ADDR)
1427             reloc = BFD_RELOC_M68HC11_LO8;
1428           else if (opmode & M6811_OP_PAGE_ADDR)
1429             reloc = BFD_RELOC_M68HC11_PAGE;
1430           else
1431             reloc = BFD_RELOC_8;
1432
1433           fixp = fix_new_exp (frag_now, f - frag_now->fr_literal, 1,
1434                               oper, FALSE, reloc);
1435           if (reloc != BFD_RELOC_8)
1436             fixp->fx_no_overflow = 1;
1437         }
1438       number_to_chars_bigendian (f, 0, 1);
1439     }
1440   else
1441     {
1442       as_fatal (_("Operand `%x' not recognized in fixup8."), oper->X_op);
1443     }
1444 }
1445
1446 /* Put a 2 byte expression described by 'oper'.  If this expression contains
1447    unresolved symbols, generate a 16-bit fixup.  */
1448 static void
1449 fixup16 (expressionS *oper, int mode, int opmode ATTRIBUTE_UNUSED)
1450 {
1451   char *f;
1452
1453   f = frag_more (2);
1454
1455   if (oper->X_op == O_constant)
1456     {
1457       if (!check_range (oper->X_add_number, mode))
1458         {
1459           as_bad (_("Operand out of 16-bit range: `%ld'."),
1460                   oper->X_add_number);
1461         }
1462       number_to_chars_bigendian (f, oper->X_add_number & 0x0FFFF, 2);
1463     }
1464   else if (oper->X_op != O_register)
1465     {
1466       fixS *fixp;
1467       int reloc;
1468
1469       if ((opmode & M6811_OP_CALL_ADDR) && (mode & M6811_OP_IMM16))
1470         reloc = BFD_RELOC_M68HC11_LO16;
1471       else if (mode & M6812_OP_JUMP_REL16)
1472         reloc = BFD_RELOC_16_PCREL;
1473       else if (mode & M6812_OP_PAGE)
1474         reloc = BFD_RELOC_M68HC11_LO16;
1475       else
1476         reloc = BFD_RELOC_16;
1477
1478       /* Now create a 16-bit fixup.  */
1479       fixp = fix_new_exp (frag_now, f - frag_now->fr_literal, 2,
1480                           oper,
1481                           reloc == BFD_RELOC_16_PCREL,
1482                           reloc);
1483       number_to_chars_bigendian (f, 0, 2);
1484       if (reloc == BFD_RELOC_16_PCREL)
1485         fixp->fx_pcrel_adjust = 2;
1486       if (reloc == BFD_RELOC_M68HC11_LO16)
1487         fixp->fx_no_overflow = 1;
1488     }
1489   else
1490     {
1491       as_fatal (_("Operand `%x' not recognized in fixup16."), oper->X_op);
1492     }
1493 }
1494
1495 /* Put a 3 byte expression described by 'oper'.  If this expression contains
1496    unresolved symbols, generate a 24-bit fixup.  */
1497 static void
1498 fixup24 (expressionS *oper, int mode, int opmode ATTRIBUTE_UNUSED)
1499 {
1500   char *f;
1501
1502   f = frag_more (3);
1503
1504   if (oper->X_op == O_constant)
1505     {
1506       if (!check_range (oper->X_add_number, mode))
1507         {
1508           as_bad (_("Operand out of 16-bit range: `%ld'."),
1509                   oper->X_add_number);
1510         }
1511       number_to_chars_bigendian (f, oper->X_add_number & 0x0FFFFFF, 3);
1512     }
1513   else if (oper->X_op != O_register)
1514     {
1515       fixS *fixp;
1516
1517       /* Now create a 24-bit fixup.  */
1518       fixp = fix_new_exp (frag_now, f - frag_now->fr_literal, 2,
1519                           oper, FALSE, BFD_RELOC_M68HC11_24);
1520       number_to_chars_bigendian (f, 0, 3);
1521     }
1522   else
1523     {
1524       as_fatal (_("Operand `%x' not recognized in fixup16."), oper->X_op);
1525     }
1526 }
1527 \f
1528 /* 68HC11 and 68HC12 code generation.  */
1529
1530 /* Translate the short branch/bsr instruction into a long branch.  */
1531 static unsigned char
1532 convert_branch (unsigned char code)
1533 {
1534   if (IS_OPCODE (code, M6812_BSR))
1535     return M6812_JSR;
1536   else if (IS_OPCODE (code, M6811_BSR))
1537     return M6811_JSR;
1538   else if (IS_OPCODE (code, M6811_BRA))
1539     return (current_architecture & cpu6812) ? M6812_JMP : M6811_JMP;
1540   else
1541     as_fatal (_("Unexpected branch conversion with `%x'"), code);
1542
1543   /* Keep gcc happy.  */
1544   return M6811_JSR;
1545 }
1546
1547 /* Start a new insn that contains at least 'size' bytes.  Record the
1548    line information of that insn in the dwarf2 debug sections.  */
1549 static char *
1550 m68hc11_new_insn (int size)
1551 {
1552   char *f;
1553
1554   f = frag_more (size);
1555
1556   dwarf2_emit_insn (size);
1557
1558   return f;
1559 }
1560
1561 /* Builds a jump instruction (bra, bcc, bsr).  */
1562 static void
1563 build_jump_insn (struct m68hc11_opcode *opcode, operand operands[],
1564                  int nb_operands, int jmp_mode)
1565 {
1566   unsigned char code;
1567   char *f;
1568   unsigned long n;
1569   fragS *frag;
1570   int where;
1571
1572   /* The relative branch conversion is not supported for
1573      brclr and brset.  */
1574   assert ((opcode->format & M6811_OP_BITMASK) == 0);
1575   assert (nb_operands == 1);
1576   assert (operands[0].reg1 == REG_NONE && operands[0].reg2 == REG_NONE);
1577
1578   code = opcode->opcode;
1579
1580   n = operands[0].exp.X_add_number;
1581
1582   /* Turn into a long branch:
1583      - when force long branch option (and not for jbcc pseudos),
1584      - when jbcc and the constant is out of -128..127 range,
1585      - when branch optimization is allowed and branch out of range.  */
1586   if ((jmp_mode == 0 && flag_force_long_jumps)
1587       || (operands[0].exp.X_op == O_constant
1588           && (!check_range (n, opcode->format) &&
1589               (jmp_mode == 1 || flag_fixed_branchs == 0))))
1590     {
1591       frag = frag_now;
1592       where = frag_now_fix ();
1593
1594       fix_new (frag_now, frag_now_fix (), 1,
1595                &abs_symbol, 0, 1, BFD_RELOC_M68HC11_RL_JUMP);
1596
1597       if (code == M6811_BSR || code == M6811_BRA || code == M6812_BSR)
1598         {
1599           code = convert_branch (code);
1600
1601           f = m68hc11_new_insn (1);
1602           number_to_chars_bigendian (f, code, 1);
1603         }
1604       else if (current_architecture & cpu6812)
1605         {
1606           /* 68HC12: translate the bcc into a lbcc.  */
1607           f = m68hc11_new_insn (2);
1608           number_to_chars_bigendian (f, M6811_OPCODE_PAGE2, 1);
1609           number_to_chars_bigendian (f + 1, code, 1);
1610           fixup16 (&operands[0].exp, M6812_OP_JUMP_REL16,
1611                    M6812_OP_JUMP_REL16);
1612           return;
1613         }
1614       else
1615         {
1616           /* 68HC11: translate the bcc into b!cc +3; jmp <L>.  */
1617           f = m68hc11_new_insn (3);
1618           code ^= 1;
1619           number_to_chars_bigendian (f, code, 1);
1620           number_to_chars_bigendian (f + 1, 3, 1);
1621           number_to_chars_bigendian (f + 2, M6811_JMP, 1);
1622         }
1623       fixup16 (&operands[0].exp, M6811_OP_IND16, M6811_OP_IND16);
1624       return;
1625     }
1626
1627   /* Branch with a constant that must fit in 8-bits.  */
1628   if (operands[0].exp.X_op == O_constant)
1629     {
1630       if (!check_range (n, opcode->format))
1631         {
1632           as_bad (_("Operand out of range for a relative branch: `%ld'"),
1633                   n);
1634         }
1635       else if (opcode->format & M6812_OP_JUMP_REL16)
1636         {
1637           f = m68hc11_new_insn (4);
1638           number_to_chars_bigendian (f, M6811_OPCODE_PAGE2, 1);
1639           number_to_chars_bigendian (f + 1, code, 1);
1640           number_to_chars_bigendian (f + 2, n & 0x0ffff, 2);
1641         }
1642       else
1643         {
1644           f = m68hc11_new_insn (2);
1645           number_to_chars_bigendian (f, code, 1);
1646           number_to_chars_bigendian (f + 1, n & 0x0FF, 1);
1647         }
1648     }
1649   else if (opcode->format & M6812_OP_JUMP_REL16)
1650     {
1651       frag = frag_now;
1652       where = frag_now_fix ();
1653
1654       fix_new (frag_now, frag_now_fix (), 1,
1655                &abs_symbol, 0, 1, BFD_RELOC_M68HC11_RL_JUMP);
1656
1657       f = m68hc11_new_insn (2);
1658       number_to_chars_bigendian (f, M6811_OPCODE_PAGE2, 1);
1659       number_to_chars_bigendian (f + 1, code, 1);
1660       fixup16 (&operands[0].exp, M6812_OP_JUMP_REL16, M6812_OP_JUMP_REL16);
1661     }
1662   else
1663     {
1664       char *opcode;
1665
1666       frag = frag_now;
1667       where = frag_now_fix ();
1668       
1669       fix_new (frag_now, frag_now_fix (), 1,
1670                &abs_symbol, 0, 1, BFD_RELOC_M68HC11_RL_JUMP);
1671
1672       /* Branch offset must fit in 8-bits, don't do some relax.  */
1673       if (jmp_mode == 0 && flag_fixed_branchs)
1674         {
1675           opcode = m68hc11_new_insn (1);
1676           number_to_chars_bigendian (opcode, code, 1);
1677           fixup8 (&operands[0].exp, M6811_OP_JUMP_REL, M6811_OP_JUMP_REL);
1678         }
1679
1680       /* bra/bsr made be changed into jmp/jsr.  */
1681       else if (code == M6811_BSR || code == M6811_BRA || code == M6812_BSR)
1682         {
1683           /* Allocate worst case storage.  */
1684           opcode = m68hc11_new_insn (3);
1685           number_to_chars_bigendian (opcode, code, 1);
1686           number_to_chars_bigendian (opcode + 1, 0, 1);
1687           frag_variant (rs_machine_dependent, 1, 1,
1688                         ENCODE_RELAX (STATE_PC_RELATIVE, STATE_UNDF),
1689                         operands[0].exp.X_add_symbol, (offsetT) n,
1690                         opcode);
1691         }
1692       else if (current_architecture & cpu6812)
1693         {
1694           opcode = m68hc11_new_insn (2);
1695           number_to_chars_bigendian (opcode, code, 1);
1696           number_to_chars_bigendian (opcode + 1, 0, 1);
1697           frag_var (rs_machine_dependent, 2, 2,
1698                     ENCODE_RELAX (STATE_CONDITIONAL_BRANCH_6812, STATE_UNDF),
1699                     operands[0].exp.X_add_symbol, (offsetT) n, opcode);
1700         }
1701       else
1702         {
1703           opcode = m68hc11_new_insn (2);
1704           number_to_chars_bigendian (opcode, code, 1);
1705           number_to_chars_bigendian (opcode + 1, 0, 1);
1706           frag_var (rs_machine_dependent, 3, 3,
1707                     ENCODE_RELAX (STATE_CONDITIONAL_BRANCH, STATE_UNDF),
1708                     operands[0].exp.X_add_symbol, (offsetT) n, opcode);
1709         }
1710     }
1711 }
1712
1713 /* Builds a dbne/dbeq/tbne/tbeq instruction.  */
1714 static void
1715 build_dbranch_insn (struct m68hc11_opcode *opcode, operand operands[],
1716                     int nb_operands, int jmp_mode)
1717 {
1718   unsigned char code;
1719   char *f;
1720   unsigned long n;
1721
1722   /* The relative branch conversion is not supported for
1723      brclr and brset.  */
1724   assert ((opcode->format & M6811_OP_BITMASK) == 0);
1725   assert (nb_operands == 2);
1726   assert (operands[0].reg1 != REG_NONE);
1727
1728   code = opcode->opcode & 0x0FF;
1729
1730   f = m68hc11_new_insn (1);
1731   number_to_chars_bigendian (f, code, 1);
1732
1733   n = operands[1].exp.X_add_number;
1734   code = operands[0].reg1;
1735
1736   if (operands[0].reg1 == REG_NONE || operands[0].reg1 == REG_CCR
1737       || operands[0].reg1 == REG_PC)
1738     as_bad (_("Invalid register for dbcc/tbcc instruction."));
1739
1740   if (opcode->format & M6812_OP_IBCC_MARKER)
1741     code |= 0x80;
1742   else if (opcode->format & M6812_OP_TBCC_MARKER)
1743     code |= 0x40;
1744
1745   if (!(opcode->format & M6812_OP_EQ_MARKER))
1746     code |= 0x20;
1747
1748   /* Turn into a long branch:
1749      - when force long branch option (and not for jbcc pseudos),
1750      - when jdbcc and the constant is out of -256..255 range,
1751      - when branch optimization is allowed and branch out of range.  */
1752   if ((jmp_mode == 0 && flag_force_long_jumps)
1753       || (operands[1].exp.X_op == O_constant
1754           && (!check_range (n, M6812_OP_IBCC_MARKER) &&
1755               (jmp_mode == 1 || flag_fixed_branchs == 0))))
1756     {
1757       f = frag_more (2);
1758       code ^= 0x20;
1759       number_to_chars_bigendian (f, code, 1);
1760       number_to_chars_bigendian (f + 1, M6812_JMP, 1);
1761       fixup16 (&operands[0].exp, M6811_OP_IND16, M6811_OP_IND16);
1762       return;
1763     }
1764
1765   /* Branch with a constant that must fit in 9-bits.  */
1766   if (operands[1].exp.X_op == O_constant)
1767     {
1768       if (!check_range (n, M6812_OP_IBCC_MARKER))
1769         {
1770           as_bad (_("Operand out of range for a relative branch: `%ld'"),
1771                   n);
1772         }
1773       else
1774         {
1775           if ((long) n < 0)
1776             code |= 0x10;
1777
1778           f = frag_more (2);
1779           number_to_chars_bigendian (f, code, 1);
1780           number_to_chars_bigendian (f + 1, n & 0x0FF, 1);
1781         }
1782     }
1783   else
1784     {
1785       /* Branch offset must fit in 8-bits, don't do some relax.  */
1786       if (jmp_mode == 0 && flag_fixed_branchs)
1787         {
1788           fixup8 (&operands[0].exp, M6811_OP_JUMP_REL, M6811_OP_JUMP_REL);
1789         }
1790
1791       else
1792         {
1793           f = frag_more (2);
1794           number_to_chars_bigendian (f, code, 1);
1795           number_to_chars_bigendian (f + 1, 0, 1);
1796           frag_var (rs_machine_dependent, 3, 3,
1797                     ENCODE_RELAX (STATE_XBCC_BRANCH, STATE_UNDF),
1798                     operands[1].exp.X_add_symbol, (offsetT) n, f);
1799         }
1800     }
1801 }
1802
1803 #define OP_EXTENDED (M6811_OP_PAGE2 | M6811_OP_PAGE3 | M6811_OP_PAGE4)
1804
1805 /* Assemble the post index byte for 68HC12 extended addressing modes.  */
1806 static int
1807 build_indexed_byte (operand *op, int format ATTRIBUTE_UNUSED, int move_insn)
1808 {
1809   unsigned char byte = 0;
1810   char *f;
1811   int mode;
1812   long val;
1813
1814   val = op->exp.X_add_number;
1815   mode = op->mode;
1816   if (mode & M6812_AUTO_INC_DEC)
1817     {
1818       byte = 0x20;
1819       if (mode & (M6812_POST_INC | M6812_POST_DEC))
1820         byte |= 0x10;
1821
1822       if (op->exp.X_op == O_constant)
1823         {
1824           if (!check_range (val, mode))
1825             {
1826               as_bad (_("Increment/decrement value is out of range: `%ld'."),
1827                       val);
1828             }
1829           if (mode & (M6812_POST_INC | M6812_PRE_INC))
1830             byte |= (val - 1) & 0x07;
1831           else
1832             byte |= (8 - ((val) & 7)) | 0x8;
1833         }
1834       switch (op->reg1)
1835         {
1836         case REG_NONE:
1837           as_fatal (_("Expecting a register."));
1838
1839         case REG_X:
1840           byte |= 0;
1841           break;
1842
1843         case REG_Y:
1844           byte |= 0x40;
1845           break;
1846
1847         case REG_SP:
1848           byte |= 0x80;
1849           break;
1850
1851         default:
1852           as_bad (_("Invalid register for post/pre increment."));
1853           break;
1854         }
1855
1856       f = frag_more (1);
1857       number_to_chars_bigendian (f, byte, 1);
1858       return 1;
1859     }
1860
1861   if (mode & (M6812_OP_IDX | M6812_OP_D_IDX_2))
1862     {
1863       switch (op->reg1)
1864         {
1865         case REG_X:
1866           byte = 0;
1867           break;
1868
1869         case REG_Y:
1870           byte = 1;
1871           break;
1872
1873         case REG_SP:
1874           byte = 2;
1875           break;
1876
1877         case REG_PC:
1878           byte = 3;
1879           break;
1880
1881         default:
1882           as_bad (_("Invalid register."));
1883           break;
1884         }
1885       if (op->exp.X_op == O_constant)
1886         {
1887           if (!check_range (val, M6812_OP_IDX))
1888             {
1889               as_bad (_("Offset out of 16-bit range: %ld."), val);
1890             }
1891
1892           if (move_insn && !(val >= -16 && val <= 15))
1893             {
1894               as_bad (_("Offset out of 5-bit range for movw/movb insn: %ld."),
1895                       val);
1896               return -1;
1897             }
1898
1899           if (val >= -16 && val <= 15 && !(mode & M6812_OP_D_IDX_2))
1900             {
1901               byte = byte << 6;
1902               byte |= val & 0x1f;
1903               f = frag_more (1);
1904               number_to_chars_bigendian (f, byte, 1);
1905               return 1;
1906             }
1907           else if (val >= -256 && val <= 255 && !(mode & M6812_OP_D_IDX_2))
1908             {
1909               byte = byte << 3;
1910               byte |= 0xe0;
1911               if (val < 0)
1912                 byte |= 0x1;
1913               f = frag_more (2);
1914               number_to_chars_bigendian (f, byte, 1);
1915               number_to_chars_bigendian (f + 1, val & 0x0FF, 1);
1916               return 2;
1917             }
1918           else
1919             {
1920               byte = byte << 3;
1921               if (mode & M6812_OP_D_IDX_2)
1922                 byte |= 0xe3;
1923               else
1924                 byte |= 0xe2;
1925
1926               f = frag_more (3);
1927               number_to_chars_bigendian (f, byte, 1);
1928               number_to_chars_bigendian (f + 1, val & 0x0FFFF, 2);
1929               return 3;
1930             }
1931         }
1932       if (mode & M6812_OP_D_IDX_2)
1933         {
1934           byte = (byte << 3) | 0xe3;
1935           f = frag_more (1);
1936           number_to_chars_bigendian (f, byte, 1);
1937
1938           fixup16 (&op->exp, 0, 0);
1939         }
1940       else if (op->reg1 != REG_PC)
1941         {
1942           symbolS *sym;
1943           offsetT off;
1944
1945           f = frag_more (1);
1946           number_to_chars_bigendian (f, byte, 1);
1947           sym = op->exp.X_add_symbol;
1948           off = op->exp.X_add_number;
1949           if (op->exp.X_op != O_symbol)
1950             {
1951               sym = make_expr_symbol (&op->exp);
1952               off = 0;
1953             }
1954           frag_var (rs_machine_dependent, 2, 2,
1955                     ENCODE_RELAX (STATE_INDEXED_OFFSET, STATE_UNDF),
1956                     sym, off, f);
1957         }
1958       else
1959         {
1960           f = frag_more (1);
1961           number_to_chars_bigendian (f, byte, 1);
1962           frag_var (rs_machine_dependent, 2, 2,
1963                     ENCODE_RELAX (STATE_INDEXED_PCREL, STATE_UNDF),
1964                     op->exp.X_add_symbol,
1965                     op->exp.X_add_number, f);
1966         }
1967       return 3;
1968     }
1969
1970   if (mode & (M6812_OP_REG | M6812_OP_D_IDX))
1971     {
1972       if (mode & M6812_OP_D_IDX)
1973         {
1974           if (op->reg1 != REG_D)
1975             as_bad (_("Expecting register D for indexed indirect mode."));
1976           if (move_insn)
1977             as_bad (_("Indexed indirect mode is not allowed for movb/movw."));
1978
1979           byte = 0xE7;
1980         }
1981       else
1982         {
1983           switch (op->reg1)
1984             {
1985             case REG_A:
1986               byte = 0xE4;
1987               break;
1988
1989             case REG_B:
1990               byte = 0xE5;
1991               break;
1992
1993             default:
1994               as_bad (_("Invalid accumulator register."));
1995
1996             case REG_D:
1997               byte = 0xE6;
1998               break;
1999             }
2000         }
2001       switch (op->reg2)
2002         {
2003         case REG_X:
2004           break;
2005
2006         case REG_Y:
2007           byte |= (1 << 3);
2008           break;
2009
2010         case REG_SP:
2011           byte |= (2 << 3);
2012           break;
2013
2014         case REG_PC:
2015           byte |= (3 << 3);
2016           break;
2017
2018         default:
2019           as_bad (_("Invalid indexed register."));
2020           break;
2021         }
2022       f = frag_more (1);
2023       number_to_chars_bigendian (f, byte, 1);
2024       return 1;
2025     }
2026
2027   as_fatal (_("Addressing mode not implemented yet."));
2028   return 0;
2029 }
2030
2031 /* Assemble the 68HC12 register mode byte.  */
2032 static int
2033 build_reg_mode (operand *op, int format)
2034 {
2035   unsigned char byte;
2036   char *f;
2037
2038   if (format & M6812_OP_SEX_MARKER
2039       && op->reg1 != REG_A && op->reg1 != REG_B && op->reg1 != REG_CCR)
2040     as_bad (_("Invalid source register for this instruction, use 'tfr'."));
2041   else if (op->reg1 == REG_NONE || op->reg1 == REG_PC)
2042     as_bad (_("Invalid source register."));
2043
2044   if (format & M6812_OP_SEX_MARKER
2045       && op->reg2 != REG_D
2046       && op->reg2 != REG_X && op->reg2 != REG_Y && op->reg2 != REG_SP)
2047     as_bad (_("Invalid destination register for this instruction, use 'tfr'."));
2048   else if (op->reg2 == REG_NONE || op->reg2 == REG_PC)
2049     as_bad (_("Invalid destination register."));
2050
2051   byte = (op->reg1 << 4) | (op->reg2);
2052   if (format & M6812_OP_EXG_MARKER)
2053     byte |= 0x80;
2054
2055   f = frag_more (1);
2056   number_to_chars_bigendian (f, byte, 1);
2057   return 1;
2058 }
2059
2060 /* build_insn takes a pointer to the opcode entry in the opcode table,
2061    the array of operand expressions and builds the corresponding instruction.
2062    This operation only deals with non relative jumps insn (need special
2063    handling).  */
2064 static void
2065 build_insn (struct m68hc11_opcode *opcode, operand operands[],
2066             int nb_operands ATTRIBUTE_UNUSED)
2067 {
2068   int i;
2069   char *f;
2070   long format;
2071   int move_insn = 0;
2072
2073   /* Put the page code instruction if there is one.  */
2074   format = opcode->format;
2075
2076   if (format & M6811_OP_BRANCH)
2077     fix_new (frag_now, frag_now_fix (), 1,
2078              &abs_symbol, 0, 1, BFD_RELOC_M68HC11_RL_JUMP);
2079
2080   if (format & OP_EXTENDED)
2081     {
2082       int page_code;
2083
2084       f = m68hc11_new_insn (2);
2085       if (format & M6811_OP_PAGE2)
2086         page_code = M6811_OPCODE_PAGE2;
2087       else if (format & M6811_OP_PAGE3)
2088         page_code = M6811_OPCODE_PAGE3;
2089       else
2090         page_code = M6811_OPCODE_PAGE4;
2091
2092       number_to_chars_bigendian (f, page_code, 1);
2093       f++;
2094     }
2095   else
2096     f = m68hc11_new_insn (1);
2097
2098   number_to_chars_bigendian (f, opcode->opcode, 1);
2099
2100   i = 0;
2101
2102   /* The 68HC12 movb and movw instructions are special.  We have to handle
2103      them in a special way.  */
2104   if (format & (M6812_OP_IND16_P2 | M6812_OP_IDX_P2))
2105     {
2106       move_insn = 1;
2107       if (format & M6812_OP_IDX)
2108         {
2109           build_indexed_byte (&operands[0], format, 1);
2110           i = 1;
2111           format &= ~M6812_OP_IDX;
2112         }
2113       if (format & M6812_OP_IDX_P2)
2114         {
2115           build_indexed_byte (&operands[1], format, 1);
2116           i = 0;
2117           format &= ~M6812_OP_IDX_P2;
2118         }
2119     }
2120
2121   if (format & (M6811_OP_DIRECT | M6811_OP_IMM8))
2122     {
2123       fixup8 (&operands[i].exp,
2124               format & (M6811_OP_DIRECT | M6811_OP_IMM8 | M6812_OP_TRAP_ID),
2125               operands[i].mode);
2126       i++;
2127     }
2128   else if (IS_CALL_SYMBOL (format) && nb_operands == 1)
2129     {
2130       format &= ~M6812_OP_PAGE;
2131       fixup24 (&operands[i].exp, format & M6811_OP_IND16,
2132                operands[i].mode);
2133       i++;
2134     }
2135   else if (format & (M6811_OP_IMM16 | M6811_OP_IND16))
2136     {
2137       fixup16 (&operands[i].exp,
2138                format & (M6811_OP_IMM16 | M6811_OP_IND16 | M6812_OP_PAGE),
2139                operands[i].mode);
2140       i++;
2141     }
2142   else if (format & (M6811_OP_IX | M6811_OP_IY))
2143     {
2144       if ((format & M6811_OP_IX) && (operands[0].reg1 != REG_X))
2145         as_bad (_("Invalid indexed register, expecting register X."));
2146       if ((format & M6811_OP_IY) && (operands[0].reg1 != REG_Y))
2147         as_bad (_("Invalid indexed register, expecting register Y."));
2148
2149       fixup8 (&operands[0].exp, M6811_OP_IX, operands[0].mode);
2150       i = 1;
2151     }
2152   else if (format &
2153            (M6812_OP_IDX | M6812_OP_IDX_2 | M6812_OP_IDX_1
2154             | M6812_OP_D_IDX | M6812_OP_D_IDX_2))
2155     {
2156       build_indexed_byte (&operands[i], format, move_insn);
2157       i++;
2158     }
2159   else if (format & M6812_OP_REG && current_architecture & cpu6812)
2160     {
2161       build_reg_mode (&operands[i], format);
2162       i++;
2163     }
2164   if (format & M6811_OP_BITMASK)
2165     {
2166       fixup8 (&operands[i].exp, M6811_OP_BITMASK, operands[i].mode);
2167       i++;
2168     }
2169   if (format & M6811_OP_JUMP_REL)
2170     {
2171       fixup8 (&operands[i].exp, M6811_OP_JUMP_REL, operands[i].mode);
2172     }
2173   else if (format & M6812_OP_IND16_P2)
2174     {
2175       fixup16 (&operands[1].exp, M6811_OP_IND16, operands[1].mode);
2176     }
2177   if (format & M6812_OP_PAGE)
2178     {
2179       fixup8 (&operands[i].exp, M6812_OP_PAGE, operands[i].mode);
2180     }
2181 }
2182 \f
2183 /* Opcode identification and operand analysis.  */
2184
2185 /* find() gets a pointer to an entry in the opcode table.  It must look at all
2186    opcodes with the same name and use the operands to choose the correct
2187    opcode.  Returns the opcode pointer if there was a match and 0 if none.  */
2188 static struct m68hc11_opcode *
2189 find (struct m68hc11_opcode_def *opc, operand operands[], int nb_operands)
2190 {
2191   int i, match, pos;
2192   struct m68hc11_opcode *opcode;
2193   struct m68hc11_opcode *op_indirect;
2194
2195   op_indirect = 0;
2196   opcode = opc->opcode;
2197
2198   /* Now search the opcode table table for one with operands
2199      that matches what we've got.  We're only done if the operands matched so
2200      far AND there are no more to check.  */
2201   for (pos = match = 0; match == 0 && pos < opc->nb_modes; pos++, opcode++)
2202     {
2203       int poss_indirect = 0;
2204       long format = opcode->format;
2205       int expect;
2206
2207       expect = 0;
2208       if (opcode->format & M6811_OP_MASK)
2209         expect++;
2210       if (opcode->format & M6811_OP_BITMASK)
2211         expect++;
2212       if (opcode->format & (M6811_OP_JUMP_REL | M6812_OP_JUMP_REL16))
2213         expect++;
2214       if (opcode->format & (M6812_OP_IND16_P2 | M6812_OP_IDX_P2))
2215         expect++;
2216       if ((opcode->format & M6812_OP_PAGE)
2217           && (!IS_CALL_SYMBOL (opcode->format) || nb_operands == 2))
2218         expect++;
2219
2220       for (i = 0; expect == nb_operands && i < nb_operands; i++)
2221         {
2222           int mode = operands[i].mode;
2223
2224           if (mode & M6811_OP_IMM16)
2225             {
2226               if (format &
2227                   (M6811_OP_IMM8 | M6811_OP_IMM16 | M6811_OP_BITMASK))
2228                 continue;
2229               break;
2230             }
2231           if (mode == M6811_OP_DIRECT)
2232             {
2233               if (format & M6811_OP_DIRECT)
2234                 continue;
2235
2236               /* If the operand is a page 0 operand, remember a
2237                  possible <abs-16> addressing mode.  We mark
2238                  this and continue to check other operands.  */
2239               if (format & M6811_OP_IND16
2240                   && flag_strict_direct_addressing && op_indirect == 0)
2241                 {
2242                   poss_indirect = 1;
2243                   continue;
2244                 }
2245               break;
2246             }
2247           if (mode & M6811_OP_IND16)
2248             {
2249               if (i == 0 && (format & M6811_OP_IND16) != 0)
2250                 continue;
2251               if (i != 0 && (format & M6812_OP_PAGE) != 0)
2252                 continue;
2253               if (i != 0 && (format & M6812_OP_IND16_P2) != 0)
2254                 continue;
2255               if (i == 0 && (format & M6811_OP_BITMASK))
2256                 break;
2257             }
2258           if (mode & (M6811_OP_JUMP_REL | M6812_OP_JUMP_REL16))
2259             {
2260               if (format & (M6811_OP_JUMP_REL | M6812_OP_JUMP_REL16))
2261                 continue;
2262             }
2263           if (mode & M6812_OP_REG)
2264             {
2265               if (i == 0
2266                   && (format & M6812_OP_REG)
2267                   && (operands[i].reg2 == REG_NONE))
2268                 continue;
2269               if (i == 0
2270                   && (format & M6812_OP_REG)
2271                   && (format & M6812_OP_REG_2)
2272                   && (operands[i].reg2 != REG_NONE))
2273                 continue;
2274               if (i == 0
2275                   && (format & M6812_OP_IDX)
2276                   && (operands[i].reg2 != REG_NONE))
2277                 continue;
2278               if (i == 0
2279                   && (format & M6812_OP_IDX)
2280                   && (format & (M6812_OP_IND16_P2 | M6812_OP_IDX_P2)))
2281                 continue;
2282               if (i == 1
2283                   && (format & M6812_OP_IDX_P2))
2284                 continue;
2285               break;
2286             }
2287           if (mode & M6812_OP_IDX)
2288             {
2289               if (format & M6811_OP_IX && operands[i].reg1 == REG_X)
2290                 continue;
2291               if (format & M6811_OP_IY && operands[i].reg1 == REG_Y)
2292                 continue;
2293               if (i == 0
2294                   && format & (M6812_OP_IDX | M6812_OP_IDX_1 | M6812_OP_IDX_2)
2295                   && (operands[i].reg1 == REG_X
2296                       || operands[i].reg1 == REG_Y
2297                       || operands[i].reg1 == REG_SP
2298                       || operands[i].reg1 == REG_PC))
2299                 continue;
2300               if (i == 1 && format & M6812_OP_IDX_P2)
2301                 continue;
2302             }
2303           if (mode & format & (M6812_OP_D_IDX | M6812_OP_D_IDX_2))
2304             {
2305               if (i == 0)
2306                 continue;
2307             }
2308           if (mode & M6812_AUTO_INC_DEC)
2309             {
2310               if (i == 0
2311                   && format & (M6812_OP_IDX | M6812_OP_IDX_1 |
2312                                M6812_OP_IDX_2))
2313                 continue;
2314               if (i == 1 && format & M6812_OP_IDX_P2)
2315                 continue;
2316             }
2317           break;
2318         }
2319       match = i == nb_operands;
2320
2321       /* Operands are ok but an operand uses page 0 addressing mode
2322          while the insn supports abs-16 mode.  Keep a reference to this
2323          insns in case there is no insn supporting page 0 addressing.  */
2324       if (match && poss_indirect)
2325         {
2326           op_indirect = opcode;
2327           match = 0;
2328         }
2329       if (match)
2330         break;
2331     }
2332
2333   /* Page 0 addressing is used but not supported by any insn.
2334      If absolute addresses are supported, we use that insn.  */
2335   if (match == 0 && op_indirect)
2336     {
2337       opcode = op_indirect;
2338       match = 1;
2339     }
2340
2341   if (!match)
2342     {
2343       return (0);
2344     }
2345
2346   return opcode;
2347 }
2348
2349 /* Find the real opcode and its associated operands.  We use a progressive
2350    approach here.  On entry, 'opc' points to the first opcode in the
2351    table that matches the opcode name in the source line.  We try to
2352    isolate an operand, find a possible match in the opcode table.
2353    We isolate another operand if no match were found.  The table 'operands'
2354    is filled while operands are recognized.
2355
2356    Returns the opcode pointer that matches the opcode name in the
2357    source line and the associated operands.  */
2358 static struct m68hc11_opcode *
2359 find_opcode (struct m68hc11_opcode_def *opc, operand operands[],
2360              int *nb_operands)
2361 {
2362   struct m68hc11_opcode *opcode;
2363   int i;
2364
2365   if (opc->max_operands == 0)
2366     {
2367       *nb_operands = 0;
2368       return opc->opcode;
2369     }
2370
2371   for (i = 0; i < opc->max_operands;)
2372     {
2373       int result;
2374
2375       result = get_operand (&operands[i], i, opc->format);
2376       if (result <= 0)
2377         return 0;
2378
2379       /* Special case where the bitmask of the bclr/brclr
2380          instructions is not introduced by #.
2381          Example: bclr 3,x $80.  */
2382       if (i == 1 && (opc->format & M6811_OP_BITMASK)
2383           && (operands[i].mode & M6811_OP_IND16))
2384         {
2385           operands[i].mode = M6811_OP_IMM16;
2386         }
2387
2388       i += result;
2389       *nb_operands = i;
2390       if (i >= opc->min_operands)
2391         {
2392           opcode = find (opc, operands, i);
2393
2394           /* Another special case for 'call foo,page' instructions.
2395              Since we support 'call foo' and 'call foo,page' we must look
2396              if the optional page specification is present otherwise we will
2397              assemble immediately and treat the page spec as garbage.  */
2398           if (opcode && !(opcode->format & M6812_OP_PAGE))
2399              return opcode;
2400
2401           if (opcode && *input_line_pointer != ',')
2402             return opcode;
2403         }
2404
2405       if (*input_line_pointer == ',')
2406         input_line_pointer++;
2407     }
2408
2409   return 0;
2410 }
2411
2412 #define M6812_XBCC_MARKER (M6812_OP_TBCC_MARKER \
2413                            | M6812_OP_DBCC_MARKER \
2414                            | M6812_OP_IBCC_MARKER)
2415 \f
2416 /* Gas line assembler entry point.  */
2417
2418 /* This is the main entry point for the machine-dependent assembler.  str
2419    points to a machine-dependent instruction.  This function is supposed to
2420    emit the frags/bytes it assembles to.  */
2421 void
2422 md_assemble (char *str)
2423 {
2424   struct m68hc11_opcode_def *opc;
2425   struct m68hc11_opcode *opcode;
2426
2427   unsigned char *op_start, *save;
2428   unsigned char *op_end;
2429   char name[20];
2430   int nlen = 0;
2431   operand operands[M6811_MAX_OPERANDS];
2432   int nb_operands;
2433   int branch_optimize = 0;
2434   int alias_id = -1;
2435
2436   /* Drop leading whitespace.  */
2437   while (*str == ' ')
2438     str++;
2439
2440   /* Find the opcode end and get the opcode in 'name'.  The opcode is forced
2441      lower case (the opcode table only has lower case op-codes).  */
2442   for (op_start = op_end = (unsigned char *) (str);
2443        *op_end && nlen < 20 && !is_end_of_line[*op_end] && *op_end != ' ';
2444        op_end++)
2445     {
2446       name[nlen] = TOLOWER (op_start[nlen]);
2447       nlen++;
2448     }
2449   name[nlen] = 0;
2450
2451   if (nlen == 0)
2452     {
2453       as_bad (_("No instruction or missing opcode."));
2454       return;
2455     }
2456
2457   /* Find the opcode definition given its name.  */
2458   opc = (struct m68hc11_opcode_def *) hash_find (m68hc11_hash, name);
2459
2460   /* If it's not recognized, look for 'jbsr' and 'jbxx'.  These are
2461      pseudo insns for relative branch.  For these branchs, we always
2462      optimize them (turned into absolute branchs) even if --short-branchs
2463      is given.  */
2464   if (opc == NULL && name[0] == 'j' && name[1] == 'b')
2465     {
2466       opc = (struct m68hc11_opcode_def *) hash_find (m68hc11_hash, &name[1]);
2467       if (opc
2468           && (!(opc->format & M6811_OP_JUMP_REL)
2469               || (opc->format & M6811_OP_BITMASK)))
2470         opc = 0;
2471       if (opc)
2472         branch_optimize = 1;
2473     }
2474
2475   /* The following test should probably be removed.  This is not conform
2476      to Motorola assembler specs.  */
2477   if (opc == NULL && flag_mri)
2478     {
2479       if (*op_end == ' ' || *op_end == '\t')
2480         {
2481           while (*op_end == ' ' || *op_end == '\t')
2482             op_end++;
2483
2484           if (nlen < 19
2485               && (*op_end &&
2486                   (is_end_of_line[op_end[1]]
2487                    || op_end[1] == ' ' || op_end[1] == '\t'
2488                    || !ISALNUM (op_end[1])))
2489               && (*op_end == 'a' || *op_end == 'b'
2490                   || *op_end == 'A' || *op_end == 'B'
2491                   || *op_end == 'd' || *op_end == 'D'
2492                   || *op_end == 'x' || *op_end == 'X'
2493                   || *op_end == 'y' || *op_end == 'Y'))
2494             {
2495               name[nlen++] = TOLOWER (*op_end++);
2496               name[nlen] = 0;
2497               opc = (struct m68hc11_opcode_def *) hash_find (m68hc11_hash,
2498                                                              name);
2499             }
2500         }
2501     }
2502
2503   /* Identify a possible instruction alias.  There are some on the
2504      68HC12 to emulate a few 68HC11 instructions.  */
2505   if (opc == NULL && (current_architecture & cpu6812))
2506     {
2507       int i;
2508
2509       for (i = 0; i < m68hc12_num_alias; i++)
2510         if (strcmp (m68hc12_alias[i].name, name) == 0)
2511           {
2512             alias_id = i;
2513             break;
2514           }
2515     }
2516   if (opc == NULL && alias_id < 0)
2517     {
2518       as_bad (_("Opcode `%s' is not recognized."), name);
2519       return;
2520     }
2521   save = input_line_pointer;
2522   input_line_pointer = op_end;
2523
2524   if (opc)
2525     {
2526       opc->used++;
2527       opcode = find_opcode (opc, operands, &nb_operands);
2528     }
2529   else
2530     opcode = 0;
2531
2532   if ((opcode || alias_id >= 0) && !flag_mri)
2533     {
2534       char *p = input_line_pointer;
2535
2536       while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
2537         p++;
2538
2539       if (*p != '\n' && *p)
2540         as_bad (_("Garbage at end of instruction: `%s'."), p);
2541     }
2542
2543   input_line_pointer = save;
2544
2545   if (alias_id >= 0)
2546     {
2547       char *f = m68hc11_new_insn (m68hc12_alias[alias_id].size);
2548
2549       number_to_chars_bigendian (f, m68hc12_alias[alias_id].code1, 1);
2550       if (m68hc12_alias[alias_id].size > 1)
2551         number_to_chars_bigendian (f + 1, m68hc12_alias[alias_id].code2, 1);
2552
2553       return;
2554     }
2555
2556   /* Opcode is known but does not have valid operands.  Print out the
2557      syntax for this opcode.  */
2558   if (opcode == 0)
2559     {
2560       if (flag_print_insn_syntax)
2561         print_insn_format (name);
2562
2563       as_bad (_("Invalid operand for `%s'"), name);
2564       return;
2565     }
2566
2567   /* Treat dbeq/ibeq/tbeq instructions in a special way.  The branch is
2568      relative and must be in the range -256..255 (9-bits).  */
2569   if ((opcode->format & M6812_XBCC_MARKER)
2570       && (opcode->format & M6811_OP_JUMP_REL))
2571     build_dbranch_insn (opcode, operands, nb_operands, branch_optimize);
2572
2573   /* Relative jumps instructions are taken care of separately.  We have to make
2574      sure that the relative branch is within the range -128..127.  If it's out
2575      of range, the instructions are changed into absolute instructions.
2576      This is not supported for the brset and brclr instructions.  */
2577   else if ((opcode->format & (M6811_OP_JUMP_REL | M6812_OP_JUMP_REL16))
2578            && !(opcode->format & M6811_OP_BITMASK))
2579     build_jump_insn (opcode, operands, nb_operands, branch_optimize);
2580   else
2581     build_insn (opcode, operands, nb_operands);
2582 }
2583
2584 \f
2585 /* Pseudo op to control the ELF flags.  */
2586 static void
2587 s_m68hc11_mode (int x ATTRIBUTE_UNUSED)
2588 {
2589   char *name = input_line_pointer, ch;
2590
2591   while (!is_end_of_line[(unsigned char) *input_line_pointer])
2592     input_line_pointer++;
2593   ch = *input_line_pointer;
2594   *input_line_pointer = '\0';
2595
2596   if (strcmp (name, "mshort") == 0)
2597     {
2598       elf_flags &= ~E_M68HC11_I32;
2599     }
2600   else if (strcmp (name, "mlong") == 0)
2601     {
2602       elf_flags |= E_M68HC11_I32;
2603     }
2604   else if (strcmp (name, "mshort-double") == 0)
2605     {
2606       elf_flags &= ~E_M68HC11_F64;
2607     }
2608   else if (strcmp (name, "mlong-double") == 0)
2609     {
2610       elf_flags |= E_M68HC11_F64;
2611     }
2612   else
2613     {
2614       as_warn (_("Invalid mode: %s\n"), name);
2615     }
2616   *input_line_pointer = ch;
2617   demand_empty_rest_of_line ();
2618 }
2619
2620 /* Mark the symbols with STO_M68HC12_FAR to indicate the functions
2621    are using 'rtc' for returning.  It is necessary to use 'call'
2622    to invoke them.  This is also used by the debugger to correctly
2623    find the stack frame.  */
2624 static void
2625 s_m68hc11_mark_symbol (int mark)
2626 {
2627   char *name;
2628   int c;
2629   symbolS *symbolP;
2630   asymbol *bfdsym;
2631   elf_symbol_type *elfsym;
2632
2633   do
2634     {
2635       name = input_line_pointer;
2636       c = get_symbol_end ();
2637       symbolP = symbol_find_or_make (name);
2638       *input_line_pointer = c;
2639
2640       SKIP_WHITESPACE ();
2641
2642       bfdsym = symbol_get_bfdsym (symbolP);
2643       elfsym = elf_symbol_from (bfd_asymbol_bfd (bfdsym), bfdsym);
2644
2645       assert (elfsym);
2646
2647       /* Mark the symbol far (using rtc for function return).  */
2648       elfsym->internal_elf_sym.st_other |= mark;
2649
2650       if (c == ',')
2651         {
2652           input_line_pointer ++;
2653
2654           SKIP_WHITESPACE ();
2655
2656           if (*input_line_pointer == '\n')
2657             c = '\n';
2658         }
2659     }
2660   while (c == ',');
2661
2662   demand_empty_rest_of_line ();
2663 }
2664
2665 static void
2666 s_m68hc11_relax (int ignore ATTRIBUTE_UNUSED)
2667 {
2668   expressionS ex;
2669
2670   expression (&ex);
2671
2672   if (ex.X_op != O_symbol || ex.X_add_number != 0)
2673     {
2674       as_bad (_("bad .relax format"));
2675       ignore_rest_of_line ();
2676       return;
2677     }
2678
2679   fix_new_exp (frag_now, frag_now_fix (), 2, &ex, 1,
2680                BFD_RELOC_M68HC11_RL_GROUP);
2681
2682   demand_empty_rest_of_line ();
2683 }
2684
2685 \f
2686 /* Relocation, relaxation and frag conversions.  */
2687
2688 /* PC-relative offsets are relative to the start of the
2689    next instruction.  That is, the address of the offset, plus its
2690    size, since the offset is always the last part of the insn.  */
2691 long
2692 md_pcrel_from (fixS *fixP)
2693 {
2694   if (fixP->fx_r_type == BFD_RELOC_M68HC11_RL_JUMP)
2695     return 0;
2696
2697   return fixP->fx_size + fixP->fx_where + fixP->fx_frag->fr_address;
2698 }
2699
2700 /* If while processing a fixup, a reloc really needs to be created
2701    then it is done here.  */
2702 arelent *
2703 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
2704 {
2705   arelent *reloc;
2706
2707   reloc = (arelent *) xmalloc (sizeof (arelent));
2708   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
2709   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
2710   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
2711   if (fixp->fx_r_type == 0)
2712     reloc->howto = bfd_reloc_type_lookup (stdoutput, BFD_RELOC_16);
2713   else
2714     reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
2715   if (reloc->howto == (reloc_howto_type *) NULL)
2716     {
2717       as_bad_where (fixp->fx_file, fixp->fx_line,
2718                     _("Relocation %d is not supported by object file format."),
2719                     (int) fixp->fx_r_type);
2720       return NULL;
2721     }
2722
2723   /* Since we use Rel instead of Rela, encode the vtable entry to be
2724      used in the relocation's section offset.  */
2725   if (fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
2726     reloc->address = fixp->fx_offset;
2727
2728   reloc->addend = 0;
2729   return reloc;
2730 }
2731
2732 /* We need a port-specific relaxation function to cope with sym2 - sym1
2733    relative expressions with both symbols in the same segment (but not
2734    necessarily in the same frag as this insn), for example:
2735      ldab sym2-(sym1-2),pc
2736     sym1:
2737    The offset can be 5, 9 or 16 bits long.  */
2738
2739 long
2740 m68hc11_relax_frag (segT seg ATTRIBUTE_UNUSED, fragS *fragP,
2741                     long stretch ATTRIBUTE_UNUSED)
2742 {
2743   long growth;
2744   offsetT aim = 0;
2745   symbolS *symbolP;
2746   const relax_typeS *this_type;
2747   const relax_typeS *start_type;
2748   relax_substateT next_state;
2749   relax_substateT this_state;
2750   const relax_typeS *table = TC_GENERIC_RELAX_TABLE;
2751
2752   /* We only have to cope with frags as prepared by
2753      md_estimate_size_before_relax.  The STATE_BITS16 case may geet here
2754      because of the different reasons that it's not relaxable.  */
2755   switch (fragP->fr_subtype)
2756     {
2757     case ENCODE_RELAX (STATE_INDEXED_PCREL, STATE_BITS16):
2758     case ENCODE_RELAX (STATE_INDEXED_OFFSET, STATE_BITS16):
2759       /* When we get to this state, the frag won't grow any more.  */
2760       return 0;
2761
2762     case ENCODE_RELAX (STATE_INDEXED_PCREL, STATE_BITS5):
2763     case ENCODE_RELAX (STATE_INDEXED_OFFSET, STATE_BITS5):
2764     case ENCODE_RELAX (STATE_INDEXED_PCREL, STATE_BITS9):
2765     case ENCODE_RELAX (STATE_INDEXED_OFFSET, STATE_BITS9):
2766       if (fragP->fr_symbol == NULL
2767           || S_GET_SEGMENT (fragP->fr_symbol) != absolute_section)
2768         as_fatal (_("internal inconsistency problem in %s: fr_symbol %lx"),
2769                   __FUNCTION__, (long) fragP->fr_symbol);
2770       symbolP = fragP->fr_symbol;
2771       if (symbol_resolved_p (symbolP))
2772         as_fatal (_("internal inconsistency problem in %s: resolved symbol"),
2773                   __FUNCTION__);
2774       aim = S_GET_VALUE (symbolP);
2775       break;
2776
2777     default:
2778       as_fatal (_("internal inconsistency problem in %s: fr_subtype %d"),
2779                   __FUNCTION__, fragP->fr_subtype);
2780     }
2781
2782   /* The rest is stolen from relax_frag.  There's no obvious way to
2783      share the code, but fortunately no requirement to keep in sync as
2784      long as fragP->fr_symbol does not have its segment changed.  */
2785
2786   this_state = fragP->fr_subtype;
2787   start_type = this_type = table + this_state;
2788
2789   if (aim < 0)
2790     {
2791       /* Look backwards.  */
2792       for (next_state = this_type->rlx_more; next_state;)
2793         if (aim >= this_type->rlx_backward)
2794           next_state = 0;
2795         else
2796           {
2797             /* Grow to next state.  */
2798             this_state = next_state;
2799             this_type = table + this_state;
2800             next_state = this_type->rlx_more;
2801           }
2802     }
2803   else
2804     {
2805       /* Look forwards.  */
2806       for (next_state = this_type->rlx_more; next_state;)
2807         if (aim <= this_type->rlx_forward)
2808           next_state = 0;
2809         else
2810           {
2811             /* Grow to next state.  */
2812             this_state = next_state;
2813             this_type = table + this_state;
2814             next_state = this_type->rlx_more;
2815           }
2816     }
2817
2818   growth = this_type->rlx_length - start_type->rlx_length;
2819   if (growth != 0)
2820     fragP->fr_subtype = this_state;
2821   return growth;
2822 }
2823
2824 void
2825 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED, asection *sec ATTRIBUTE_UNUSED,
2826                  fragS *fragP)
2827 {
2828   fixS *fixp;
2829   long value;
2830   long disp;
2831   char *buffer_address = fragP->fr_literal;
2832
2833   /* Address in object code of the displacement.  */
2834   register int object_address = fragP->fr_fix + fragP->fr_address;
2835
2836   buffer_address += fragP->fr_fix;
2837
2838   /* The displacement of the address, from current location.  */
2839   value = S_GET_VALUE (fragP->fr_symbol);
2840   disp = (value + fragP->fr_offset) - object_address;
2841
2842   switch (fragP->fr_subtype)
2843     {
2844     case ENCODE_RELAX (STATE_PC_RELATIVE, STATE_BYTE):
2845       fragP->fr_opcode[1] = disp;
2846       break;
2847
2848     case ENCODE_RELAX (STATE_PC_RELATIVE, STATE_WORD):
2849       /* This relax is only for bsr and bra.  */
2850       assert (IS_OPCODE (fragP->fr_opcode[0], M6811_BSR)
2851               || IS_OPCODE (fragP->fr_opcode[0], M6811_BRA)
2852               || IS_OPCODE (fragP->fr_opcode[0], M6812_BSR));
2853
2854       fragP->fr_opcode[0] = convert_branch (fragP->fr_opcode[0]);
2855
2856       fix_new (fragP, fragP->fr_fix - 1, 2,
2857                fragP->fr_symbol, fragP->fr_offset, 0, BFD_RELOC_16);
2858       fragP->fr_fix += 1;
2859       break;
2860
2861     case ENCODE_RELAX (STATE_CONDITIONAL_BRANCH, STATE_BYTE):
2862     case ENCODE_RELAX (STATE_CONDITIONAL_BRANCH_6812, STATE_BYTE):
2863       fragP->fr_opcode[1] = disp;
2864       break;
2865
2866     case ENCODE_RELAX (STATE_CONDITIONAL_BRANCH, STATE_WORD):
2867       /* Invert branch.  */
2868       fragP->fr_opcode[0] ^= 1;
2869       fragP->fr_opcode[1] = 3;  /* Branch offset.  */
2870       buffer_address[0] = M6811_JMP;
2871       fix_new (fragP, fragP->fr_fix + 1, 2,
2872                fragP->fr_symbol, fragP->fr_offset, 0, BFD_RELOC_16);
2873       fragP->fr_fix += 3;
2874       break;
2875
2876     case ENCODE_RELAX (STATE_CONDITIONAL_BRANCH_6812, STATE_WORD):
2877       /* Translate branch into a long branch.  */
2878       fragP->fr_opcode[1] = fragP->fr_opcode[0];
2879       fragP->fr_opcode[0] = M6811_OPCODE_PAGE2;
2880
2881       fixp = fix_new (fragP, fragP->fr_fix, 2,
2882                       fragP->fr_symbol, fragP->fr_offset, 1,
2883                       BFD_RELOC_16_PCREL);
2884       fixp->fx_pcrel_adjust = 2;
2885       fragP->fr_fix += 2;
2886       break;
2887
2888     case ENCODE_RELAX (STATE_INDEXED_PCREL, STATE_BITS5):
2889       if (fragP->fr_symbol != 0
2890           && S_GET_SEGMENT (fragP->fr_symbol) != absolute_section)
2891         value = disp;
2892       /* fall through  */
2893
2894     case ENCODE_RELAX (STATE_INDEXED_OFFSET, STATE_BITS5):
2895       fragP->fr_opcode[0] = fragP->fr_opcode[0] << 6;
2896       fragP->fr_opcode[0] |= value & 0x1f;
2897       break;
2898
2899     case ENCODE_RELAX (STATE_INDEXED_PCREL, STATE_BITS9):
2900       /* For a PC-relative offset, use the displacement with a -1 correction
2901          to take into account the additional byte of the insn.  */
2902       if (fragP->fr_symbol != 0
2903           && S_GET_SEGMENT (fragP->fr_symbol) != absolute_section)
2904         value = disp - 1;
2905       /* fall through  */
2906
2907     case ENCODE_RELAX (STATE_INDEXED_OFFSET, STATE_BITS9):
2908       fragP->fr_opcode[0] = (fragP->fr_opcode[0] << 3);
2909       fragP->fr_opcode[0] |= 0xE0;
2910       fragP->fr_opcode[0] |= (value >> 8) & 1;
2911       fragP->fr_opcode[1] = value;
2912       fragP->fr_fix += 1;
2913       break;
2914
2915     case ENCODE_RELAX (STATE_INDEXED_PCREL, STATE_BITS16):
2916     case ENCODE_RELAX (STATE_INDEXED_OFFSET, STATE_BITS16):
2917       fragP->fr_opcode[0] = (fragP->fr_opcode[0] << 3);
2918       fragP->fr_opcode[0] |= 0xe2;
2919       if ((fragP->fr_opcode[0] & 0x0ff) == 0x0fa
2920           && fragP->fr_symbol != 0
2921           && S_GET_SEGMENT (fragP->fr_symbol) != absolute_section)
2922         {
2923           fixp = fix_new (fragP, fragP->fr_fix, 2,
2924                           fragP->fr_symbol, fragP->fr_offset,
2925                           1, BFD_RELOC_16_PCREL);
2926         }
2927       else
2928         {
2929           fix_new (fragP, fragP->fr_fix, 2,
2930                    fragP->fr_symbol, fragP->fr_offset, 0, BFD_RELOC_16);
2931         }
2932       fragP->fr_fix += 2;
2933       break;
2934
2935     case ENCODE_RELAX (STATE_XBCC_BRANCH, STATE_BYTE):
2936       if (disp < 0)
2937         fragP->fr_opcode[0] |= 0x10;
2938
2939       fragP->fr_opcode[1] = disp & 0x0FF;
2940       break;
2941
2942     case ENCODE_RELAX (STATE_XBCC_BRANCH, STATE_WORD):
2943       /* Invert branch.  */
2944       fragP->fr_opcode[0] ^= 0x20;
2945       fragP->fr_opcode[1] = 3;  /* Branch offset.  */
2946       buffer_address[0] = M6812_JMP;
2947       fix_new (fragP, fragP->fr_fix + 1, 2,
2948                fragP->fr_symbol, fragP->fr_offset, 0, BFD_RELOC_16);
2949       fragP->fr_fix += 3;
2950       break;
2951
2952     default:
2953       break;
2954     }
2955 }
2956
2957 /* On an ELF system, we can't relax a weak symbol.  The weak symbol
2958    can be overridden at final link time by a non weak symbol.  We can
2959    relax externally visible symbol because there is no shared library
2960    and such symbol can't be overridden (unless they are weak).  */
2961 static int
2962 relaxable_symbol (symbolS *symbol)
2963 {
2964   return ! S_IS_WEAK (symbol);
2965 }
2966
2967 /* Force truly undefined symbols to their maximum size, and generally set up
2968    the frag list to be relaxed.  */
2969 int
2970 md_estimate_size_before_relax (fragS *fragP, asection *segment)
2971 {
2972   if (RELAX_LENGTH (fragP->fr_subtype) == STATE_UNDF)
2973     {
2974       if (S_GET_SEGMENT (fragP->fr_symbol) != segment
2975           || !relaxable_symbol (fragP->fr_symbol)
2976           || (segment != absolute_section
2977               && RELAX_STATE (fragP->fr_subtype) == STATE_INDEXED_OFFSET))
2978         {
2979           /* Non-relaxable cases.  */
2980           int old_fr_fix;
2981           char *buffer_address;
2982
2983           old_fr_fix = fragP->fr_fix;
2984           buffer_address = fragP->fr_fix + fragP->fr_literal;
2985
2986           switch (RELAX_STATE (fragP->fr_subtype))
2987             {
2988             case STATE_PC_RELATIVE:
2989
2990               /* This relax is only for bsr and bra.  */
2991               assert (IS_OPCODE (fragP->fr_opcode[0], M6811_BSR)
2992                       || IS_OPCODE (fragP->fr_opcode[0], M6811_BRA)
2993                       || IS_OPCODE (fragP->fr_opcode[0], M6812_BSR));
2994
2995               if (flag_fixed_branchs)
2996                 as_bad_where (fragP->fr_file, fragP->fr_line,
2997                               _("bra or bsr with undefined symbol."));
2998
2999               /* The symbol is undefined or in a separate section.
3000                  Turn bra into a jmp and bsr into a jsr.  The insn
3001                  becomes 3 bytes long (instead of 2).  A fixup is
3002                  necessary for the unresolved symbol address.  */
3003               fragP->fr_opcode[0] = convert_branch (fragP->fr_opcode[0]);
3004
3005               fix_new (fragP, fragP->fr_fix - 1, 2, fragP->fr_symbol,
3006                        fragP->fr_offset, 0, BFD_RELOC_16);
3007               fragP->fr_fix++;
3008               break;
3009
3010             case STATE_CONDITIONAL_BRANCH:
3011               assert (current_architecture & cpu6811);
3012
3013               fragP->fr_opcode[0] ^= 1; /* Reverse sense of branch.  */
3014               fragP->fr_opcode[1] = 3;  /* Skip next jmp insn (3 bytes).  */
3015
3016               /* Don't use fr_opcode[2] because this may be
3017                  in a different frag.  */
3018               buffer_address[0] = M6811_JMP;
3019
3020               fragP->fr_fix++;
3021               fix_new (fragP, fragP->fr_fix, 2, fragP->fr_symbol,
3022                        fragP->fr_offset, 0, BFD_RELOC_16);
3023               fragP->fr_fix += 2;
3024               break;
3025
3026             case STATE_INDEXED_OFFSET:
3027               assert (current_architecture & cpu6812);
3028
3029               if (fragP->fr_symbol
3030                   && S_GET_SEGMENT (fragP->fr_symbol) == absolute_section)
3031                 {
3032                    fragP->fr_subtype = ENCODE_RELAX (STATE_INDEXED_OFFSET,
3033                                                      STATE_BITS5);
3034                    /* Return the size of the variable part of the frag. */
3035                    return md_relax_table[fragP->fr_subtype].rlx_length;
3036                 }
3037               else
3038                 {
3039                    /* Switch the indexed operation to 16-bit mode.  */
3040                    fragP->fr_opcode[0] = fragP->fr_opcode[0] << 3;
3041                    fragP->fr_opcode[0] |= 0xe2;
3042                    fix_new (fragP, fragP->fr_fix, 2, fragP->fr_symbol,
3043                             fragP->fr_offset, 0, BFD_RELOC_16);
3044                    fragP->fr_fix += 2;
3045                 }
3046               break;
3047
3048             case STATE_INDEXED_PCREL:
3049               assert (current_architecture & cpu6812);
3050
3051               if (fragP->fr_symbol
3052                   && S_GET_SEGMENT (fragP->fr_symbol) == absolute_section)
3053                 {
3054                    fragP->fr_subtype = ENCODE_RELAX (STATE_INDEXED_PCREL,
3055                                                      STATE_BITS5);
3056                    /* Return the size of the variable part of the frag. */
3057                    return md_relax_table[fragP->fr_subtype].rlx_length;
3058                 }
3059               else
3060                 {
3061                    fixS* fixp;
3062
3063                    fragP->fr_opcode[0] = fragP->fr_opcode[0] << 3;
3064                    fragP->fr_opcode[0] |= 0xe2;
3065                    fixp = fix_new (fragP, fragP->fr_fix, 2, fragP->fr_symbol,
3066                                    fragP->fr_offset, 1, BFD_RELOC_16_PCREL);
3067                    fragP->fr_fix += 2;
3068                 }
3069               break;
3070
3071             case STATE_XBCC_BRANCH:
3072               assert (current_architecture & cpu6812);
3073
3074               fragP->fr_opcode[0] ^= 0x20;      /* Reverse sense of branch.  */
3075               fragP->fr_opcode[1] = 3;  /* Skip next jmp insn (3 bytes).  */
3076
3077               /* Don't use fr_opcode[2] because this may be
3078                  in a different frag.  */
3079               buffer_address[0] = M6812_JMP;
3080
3081               fragP->fr_fix++;
3082               fix_new (fragP, fragP->fr_fix, 2, fragP->fr_symbol,
3083                        fragP->fr_offset, 0, BFD_RELOC_16);
3084               fragP->fr_fix += 2;
3085               break;
3086
3087             case STATE_CONDITIONAL_BRANCH_6812:
3088               assert (current_architecture & cpu6812);
3089
3090               /* Translate into a lbcc branch.  */
3091               fragP->fr_opcode[1] = fragP->fr_opcode[0];
3092               fragP->fr_opcode[0] = M6811_OPCODE_PAGE2;
3093
3094               fix_new (fragP, fragP->fr_fix, 2, fragP->fr_symbol,
3095                        fragP->fr_offset, 1, BFD_RELOC_16_PCREL);
3096               fragP->fr_fix += 2;
3097               break;
3098
3099             default:
3100               as_fatal (_("Subtype %d is not recognized."), fragP->fr_subtype);
3101             }
3102           frag_wane (fragP);
3103
3104           /* Return the growth in the fixed part of the frag.  */
3105           return fragP->fr_fix - old_fr_fix;
3106         }
3107
3108       /* Relaxable cases.  */
3109       switch (RELAX_STATE (fragP->fr_subtype))
3110         {
3111         case STATE_PC_RELATIVE:
3112           /* This relax is only for bsr and bra.  */
3113           assert (IS_OPCODE (fragP->fr_opcode[0], M6811_BSR)
3114                   || IS_OPCODE (fragP->fr_opcode[0], M6811_BRA)
3115                   || IS_OPCODE (fragP->fr_opcode[0], M6812_BSR));
3116
3117           fragP->fr_subtype = ENCODE_RELAX (STATE_PC_RELATIVE, STATE_BYTE);
3118           break;
3119
3120         case STATE_CONDITIONAL_BRANCH:
3121           assert (current_architecture & cpu6811);
3122
3123           fragP->fr_subtype = ENCODE_RELAX (STATE_CONDITIONAL_BRANCH,
3124                                             STATE_BYTE);
3125           break;
3126
3127         case STATE_INDEXED_OFFSET:
3128           assert (current_architecture & cpu6812);
3129
3130           fragP->fr_subtype = ENCODE_RELAX (STATE_INDEXED_OFFSET,
3131                                             STATE_BITS5);
3132           break;
3133
3134         case STATE_INDEXED_PCREL:
3135           assert (current_architecture & cpu6812);
3136
3137           fragP->fr_subtype = ENCODE_RELAX (STATE_INDEXED_PCREL,
3138                                             STATE_BITS5);
3139           break;
3140
3141         case STATE_XBCC_BRANCH:
3142           assert (current_architecture & cpu6812);
3143
3144           fragP->fr_subtype = ENCODE_RELAX (STATE_XBCC_BRANCH, STATE_BYTE);
3145           break;
3146
3147         case STATE_CONDITIONAL_BRANCH_6812:
3148           assert (current_architecture & cpu6812);
3149
3150           fragP->fr_subtype = ENCODE_RELAX (STATE_CONDITIONAL_BRANCH_6812,
3151                                             STATE_BYTE);
3152           break;
3153         }
3154     }
3155
3156   if (fragP->fr_subtype >= sizeof (md_relax_table) / sizeof (md_relax_table[0]))
3157     as_fatal (_("Subtype %d is not recognized."), fragP->fr_subtype);
3158
3159   /* Return the size of the variable part of the frag.  */
3160   return md_relax_table[fragP->fr_subtype].rlx_length;
3161 }
3162
3163 /* See whether we need to force a relocation into the output file.  */
3164 int
3165 tc_m68hc11_force_relocation (fixS *fixP)
3166 {
3167   if (fixP->fx_r_type == BFD_RELOC_M68HC11_RL_GROUP)
3168     return 1;
3169
3170   return generic_force_reloc (fixP);
3171 }
3172
3173 /* Here we decide which fixups can be adjusted to make them relative
3174    to the beginning of the section instead of the symbol.  Basically
3175    we need to make sure that the linker relaxation is done
3176    correctly, so in some cases we force the original symbol to be
3177    used.  */
3178 int
3179 tc_m68hc11_fix_adjustable (fixS *fixP)
3180 {
3181   switch (fixP->fx_r_type)
3182     {
3183       /* For the linker relaxation to work correctly, these relocs
3184          need to be on the symbol itself.  */
3185     case BFD_RELOC_16:
3186     case BFD_RELOC_M68HC11_RL_JUMP:
3187     case BFD_RELOC_M68HC11_RL_GROUP:
3188     case BFD_RELOC_VTABLE_INHERIT:
3189     case BFD_RELOC_VTABLE_ENTRY:
3190     case BFD_RELOC_32:
3191
3192       /* The memory bank addressing translation also needs the original
3193          symbol.  */
3194     case BFD_RELOC_M68HC11_LO16:
3195     case BFD_RELOC_M68HC11_PAGE:
3196     case BFD_RELOC_M68HC11_24:
3197       return 0;
3198
3199     default:
3200       return 1;
3201     }
3202 }
3203
3204 void
3205 md_apply_fix3 (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
3206 {
3207   char *where;
3208   long value = * valP;
3209   int op_type;
3210
3211   if (fixP->fx_addsy == (symbolS *) NULL)
3212     fixP->fx_done = 1;
3213
3214   /* We don't actually support subtracting a symbol.  */
3215   if (fixP->fx_subsy != (symbolS *) NULL)
3216     as_bad_where (fixP->fx_file, fixP->fx_line, _("Expression too complex."));
3217
3218   op_type = fixP->fx_r_type;
3219
3220   /* Patch the instruction with the resolved operand.  Elf relocation
3221      info will also be generated to take care of linker/loader fixups.
3222      The 68HC11 addresses only 64Kb, we are only concerned by 8 and 16-bit
3223      relocs.  BFD_RELOC_8 is basically used for .page0 access (the linker
3224      will warn for overflows).  BFD_RELOC_8_PCREL should not be generated
3225      because it's either resolved or turned out into non-relative insns (see
3226      relax table, bcc, bra, bsr transformations)
3227
3228      The BFD_RELOC_32 is necessary for the support of --gstabs.  */
3229   where = fixP->fx_frag->fr_literal + fixP->fx_where;
3230
3231   switch (fixP->fx_r_type)
3232     {
3233     case BFD_RELOC_32:
3234       bfd_putb32 ((bfd_vma) value, (unsigned char *) where);
3235       break;
3236
3237     case BFD_RELOC_24:
3238     case BFD_RELOC_M68HC11_24:
3239       bfd_putb16 ((bfd_vma) (value & 0x0ffff), (unsigned char *) where);
3240       ((bfd_byte*) where)[2] = ((value >> 16) & 0x0ff);
3241       break;
3242
3243     case BFD_RELOC_16:
3244     case BFD_RELOC_16_PCREL:
3245     case BFD_RELOC_M68HC11_LO16:
3246       bfd_putb16 ((bfd_vma) value, (unsigned char *) where);
3247       if (value < -65537 || value > 65535)
3248         as_bad_where (fixP->fx_file, fixP->fx_line,
3249                       _("Value out of 16-bit range."));
3250       break;
3251
3252     case BFD_RELOC_M68HC11_HI8:
3253       value = value >> 8;
3254       /* Fall through.  */
3255
3256     case BFD_RELOC_M68HC11_LO8:
3257     case BFD_RELOC_8:
3258     case BFD_RELOC_M68HC11_PAGE:
3259 #if 0
3260       bfd_putb8 ((bfd_vma) value, (unsigned char *) where);
3261 #endif
3262       ((bfd_byte *) where)[0] = (bfd_byte) value;
3263       break;
3264
3265     case BFD_RELOC_8_PCREL:
3266 #if 0
3267       bfd_putb8 ((bfd_vma) value, (unsigned char *) where);
3268 #endif
3269       ((bfd_byte *) where)[0] = (bfd_byte) value;
3270
3271       if (value < -128 || value > 127)
3272         as_bad_where (fixP->fx_file, fixP->fx_line,
3273                       _("Value %ld too large for 8-bit PC-relative branch."),
3274                       value);
3275       break;
3276
3277     case BFD_RELOC_M68HC11_3B:
3278       if (value <= 0 || value > 8)
3279         as_bad_where (fixP->fx_file, fixP->fx_line,
3280                       _("Auto increment/decrement offset '%ld' is out of range."),
3281                       value);
3282       if (where[0] & 0x8)
3283         value = 8 - value;
3284       else
3285         value--;
3286
3287       where[0] = where[0] | (value & 0x07);
3288       break;
3289
3290     case BFD_RELOC_M68HC11_RL_JUMP:
3291     case BFD_RELOC_M68HC11_RL_GROUP:
3292     case BFD_RELOC_VTABLE_INHERIT:
3293     case BFD_RELOC_VTABLE_ENTRY:
3294       fixP->fx_done = 0;
3295       return;
3296
3297     default:
3298       as_fatal (_("Line %d: unknown relocation type: 0x%x."),
3299                 fixP->fx_line, fixP->fx_r_type);
3300     }
3301 }
3302
3303 /* Set the ELF specific flags.  */
3304 void
3305 m68hc11_elf_final_processing (void)
3306 {
3307   if (current_architecture & cpu6812s)
3308     elf_flags |= EF_M68HCS12_MACH;
3309   elf_elfheader (stdoutput)->e_flags &= ~EF_M68HC11_ABI;
3310   elf_elfheader (stdoutput)->e_flags |= elf_flags;
3311 }