Home | History | Annotate | Line # | Download | only in config
tc-cr16.c revision 1.1.1.12
      1 /* tc-cr16.c -- Assembler code for the CR16 CPU core.
      2    Copyright (C) 2007-2026 Free Software Foundation, Inc.
      3 
      4    Contributed by M R Swami Reddy <MR.Swami.Reddy (at) nsc.com>
      5 
      6    This file is part of GAS, the GNU Assembler.
      7 
      8    GAS is free software; you can redistribute it and/or modify
      9    it under the terms of the GNU General Public License as published by
     10    the Free Software Foundation; either version 3, or (at your option)
     11    any later version.
     12 
     13    GAS is distributed in the hope that it will be useful,
     14    but WITHOUT ANY WARRANTY; without even the implied warranty of
     15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     16    GNU General Public License for more details.
     17 
     18    You should have received a copy of the GNU General Public License
     19    along with GAS; see the file COPYING.  If not, write to the
     20    Free Software Foundation, 51 Franklin Street - Fifth Floor, Boston,
     21    MA 02110-1301, USA.  */
     22 
     23 #include "as.h"
     24 #include "safe-ctype.h"
     25 #include "dwarf2dbg.h"
     26 #include "opcode/cr16.h"
     27 #include "elf/cr16.h"
     28 
     29 #include <limits.h>
     30 #ifndef CHAR_BIT
     31 #define CHAR_BIT 8
     32 #endif
     33 
     34 /* Word is considered here as a 16-bit unsigned short int.  */
     35 #define WORD_SHIFT  16
     36 
     37 /* Register is 2-byte size.  */
     38 #define REG_SIZE   2
     39 
     40 /* Maximum size of a single instruction (in words).  */
     41 #define INSN_MAX_SIZE   3
     42 
     43 /* Maximum bits which may be set in a `mask16' operand.  */
     44 #define MAX_REGS_IN_MASK16  8
     45 
     46 /* Assign a number NUM, shifted by SHIFT bytes, into a location
     47    pointed by index BYTE of array 'output_opcode'.  */
     48 #define CR16_PRINT(BYTE, NUM, SHIFT)   output_opcode[BYTE] |= (NUM) << (SHIFT)
     49 
     50 /* Operand errors.  */
     51 typedef enum
     52   {
     53     OP_LEGAL = 0,       /* Legal operand.  */
     54     OP_OUT_OF_RANGE,    /* Operand not within permitted range.  */
     55     OP_NOT_EVEN         /* Operand is Odd number, should be even.  */
     56   }
     57 op_err;
     58 
     59 /* Opcode mnemonics hash table.  */
     60 static htab_t cr16_inst_hash;
     61 /* CR16 registers hash table.  */
     62 static htab_t reg_hash;
     63 /* CR16 register pair hash table.  */
     64 static htab_t regp_hash;
     65 /* CR16 processor registers hash table.  */
     66 static htab_t preg_hash;
     67 /* CR16 processor registers 32 bit hash table.  */
     68 static htab_t pregp_hash;
     69 /* Current instruction we're assembling.  */
     70 const inst *instruction;
     71 
     72 
     73 static int code_label = 0;
     74 
     75 /* Global variables.  */
     76 
     77 /* Array to hold an instruction encoding.  */
     78 long output_opcode[2];
     79 
     80 /* Nonzero means a relocatable symbol.  */
     81 int relocatable;
     82 
     83 /* A copy of the original instruction (used in error messages).  */
     84 char ins_parse[MAX_INST_LEN];
     85 
     86 /* The current processed argument number.  */
     87 int cur_arg_num;
     88 
     89 /* Generic assembler global variables which must be defined by all targets.  */
     90 
     91 /* Characters which always start a comment.  */
     92 const char comment_chars[] = "#";
     93 
     94 /* Characters which start a comment at the beginning of a line.  */
     95 const char line_comment_chars[] = "#";
     96 
     97 /* This array holds machine specific line separator characters.  */
     98 const char line_separator_chars[] = ";";
     99 
    100 /* Chars that can be used to separate mant from exp in floating point nums.  */
    101 const char EXP_CHARS[] = "eE";
    102 
    103 /* Chars that mean this number is a floating point constant as in 0f12.456  */
    104 const char FLT_CHARS[] = "f'";
    105 
    106 #ifdef OBJ_ELF
    107 /* Pre-defined "_GLOBAL_OFFSET_TABLE_"  */
    108 symbolS * GOT_symbol;
    109 #endif
    110 
    111 /* Target-specific multicharacter options, not const-declared at usage.  */
    112 const char md_shortopts[] = "";
    113 const struct option md_longopts[] =
    114 {
    115   {NULL, no_argument, NULL, 0}
    116 };
    117 const size_t md_longopts_size = sizeof (md_longopts);
    118 
    119 static void
    120 l_cons (int nbytes)
    121 {
    122   expressionS exp;
    123 
    124 #ifdef md_flush_pending_output
    125   md_flush_pending_output ();
    126 #endif
    127 
    128   if (is_it_end_of_statement ())
    129     {
    130       demand_empty_rest_of_line ();
    131       return;
    132     }
    133 
    134 #ifdef TC_ADDRESS_BYTES
    135   if (nbytes == 0)
    136     nbytes = TC_ADDRESS_BYTES ();
    137 #endif
    138 
    139 #ifdef md_cons_align
    140   md_cons_align (nbytes);
    141 #endif
    142 
    143   do
    144     {
    145       unsigned int bits_available = BITS_PER_CHAR * nbytes;
    146       char *hold = input_line_pointer;
    147 
    148       expression (&exp);
    149 
    150       if (*input_line_pointer == ':')
    151 	{
    152 	  /* Bitfields.  */
    153 	  long value = 0;
    154 
    155 	  for (;;)
    156 	    {
    157 	      unsigned long width;
    158 
    159 	      if (*input_line_pointer != ':')
    160 		{
    161 		  input_line_pointer = hold;
    162 		  break;
    163 		}
    164 	      if (exp.X_op == O_absent)
    165 		{
    166 		  as_warn (_("using a bit field width of zero"));
    167 		  exp.X_add_number = 0;
    168 		  exp.X_op = O_constant;
    169 		}
    170 
    171 	      if (exp.X_op != O_constant)
    172 		{
    173 		  *input_line_pointer = '\0';
    174 		  as_bad (_("field width \"%s\" too complex for a bitfield"),
    175 			  hold);
    176 		  *input_line_pointer = ':';
    177 		  demand_empty_rest_of_line ();
    178 		  return;
    179 		}
    180 
    181 	      if ((width = exp.X_add_number) >
    182 		  (unsigned int)(BITS_PER_CHAR * nbytes))
    183 		{
    184 		  as_warn (ngettext ("field width %lu too big to fit in %d"
    185 				     " byte: truncated to %d bits",
    186 				     "field width %lu too big to fit in %d"
    187 				     " bytes: truncated to %d bits",
    188 				     nbytes),
    189 			   width, nbytes, (BITS_PER_CHAR * nbytes));
    190 		  width = BITS_PER_CHAR * nbytes;
    191 		}
    192 
    193 	      if (width > bits_available)
    194 		{
    195 		  /* FIXME-SOMEDAY: backing up and reparsing is wasteful.  */
    196 		  input_line_pointer = hold;
    197 		  exp.X_add_number = value;
    198 		  break;
    199 		}
    200 
    201 	      /* Skip ':'.  */
    202 	      hold = ++input_line_pointer;
    203 
    204 	      expression (&exp);
    205 	      if (exp.X_op != O_constant)
    206 		{
    207 		  char cache = *input_line_pointer;
    208 
    209 		  *input_line_pointer = '\0';
    210 		  as_bad (_("field value \"%s\" too complex for a bitfield"),
    211 			  hold);
    212 		  *input_line_pointer = cache;
    213 		  demand_empty_rest_of_line ();
    214 		  return;
    215 		}
    216 
    217 	      value |= ((~(-(1 << width)) & exp.X_add_number)
    218 			<< ((BITS_PER_CHAR * nbytes) - bits_available));
    219 
    220 	      if ((bits_available -= width) == 0
    221 		  || is_it_end_of_statement ()
    222 		  || *input_line_pointer != ',')
    223 		break;
    224 
    225 	      hold = ++input_line_pointer;
    226 	      expression (&exp);
    227 	    }
    228 
    229 	  exp.X_add_number = value;
    230 	  exp.X_op = O_constant;
    231 	  exp.X_unsigned = 1;
    232 	}
    233 
    234       if ((*(input_line_pointer) == '@') && (*(input_line_pointer +1) == 'c'))
    235 	code_label = 1;
    236       emit_expr (&exp, nbytes);
    237       if ((*(input_line_pointer) == '@') && (*(input_line_pointer +1) == 'c'))
    238 	{
    239 	  input_line_pointer +=3;
    240 	  break;
    241 	}
    242     }
    243   while ((*input_line_pointer++ == ','));
    244 
    245   /* Put terminator back into stream.  */
    246   input_line_pointer--;
    247 
    248   demand_empty_rest_of_line ();
    249 }
    250 
    251 /* This table describes all the machine specific pseudo-ops
    252    the assembler has to support.  The fields are:
    253    *** Pseudo-op name without dot.
    254    *** Function to call to execute this pseudo-op.
    255    *** Integer arg to pass to the function.  */
    256 
    257 const pseudo_typeS md_pseudo_table[] =
    258 {
    259   /* In CR16 machine, align is in bytes (not a ptwo boundary).  */
    260   {"align", s_align_bytes, 0},
    261   {"long", l_cons,  4 },
    262   {"4byte", l_cons, 4 },
    263   {0, 0, 0}
    264 };
    265 
    266 /* CR16 relaxation table.  */
    267 const relax_typeS md_relax_table[] =
    268 {
    269   /* bCC  */
    270   {0x7f, -0x80, 2, 1},                  /*  8 */
    271   {0xfffe, -0x10000, 4, 2},             /* 16 */
    272   {0xfffffe, -0x1000000, 6, 0},         /* 24 */
    273 };
    274 
    275 /* Return the bit size for a given operand.  */
    276 
    277 static int
    278 get_opbits (operand_type op)
    279 {
    280   if (op < MAX_OPRD)
    281     return cr16_optab[op].bit_size;
    282 
    283   return 0;
    284 }
    285 
    286 /* Return the argument type of a given operand.  */
    287 
    288 static argtype
    289 get_optype (operand_type op)
    290 {
    291   if (op < MAX_OPRD)
    292     return cr16_optab[op].arg_type;
    293   else
    294     return nullargs;
    295 }
    296 
    297 /* Return the flags of a given operand.  */
    298 
    299 static int
    300 get_opflags (operand_type op)
    301 {
    302   if (op < MAX_OPRD)
    303     return cr16_optab[op].flags;
    304 
    305   return 0;
    306 }
    307 
    308 /* Get the cc code.  */
    309 
    310 static int
    311 get_cc (char *cc_name)
    312 {
    313    unsigned int i;
    314 
    315    for (i = 0; i < cr16_num_cc; i++)
    316      if (strcmp (cc_name, cr16_b_cond_tab[i]) == 0)
    317        return i;
    318 
    319    return -1;
    320 }
    321 
    322 /* Get the core processor register 'reg_name'.  */
    323 
    324 static reg
    325 get_register (char *reg_name)
    326 {
    327   const reg_entry *rreg;
    328 
    329   rreg = str_hash_find (reg_hash, reg_name);
    330 
    331   if (rreg != NULL)
    332     return rreg->value.reg_val;
    333 
    334   return nullregister;
    335 }
    336 /* Get the core processor register-pair 'reg_name'.  */
    337 
    338 static reg
    339 get_register_pair (char *reg_name)
    340 {
    341   const reg_entry *rreg;
    342   char tmp_rp[16]="\0";
    343 
    344   /* Add '(' and ')' to the reg pair, if it's not present.  */
    345   if (reg_name[0] != '(')
    346     {
    347       tmp_rp[0] = '(';
    348       strcat (tmp_rp, reg_name);
    349       strcat (tmp_rp,")");
    350       rreg = str_hash_find (regp_hash, tmp_rp);
    351     }
    352   else
    353     rreg = str_hash_find (regp_hash, reg_name);
    354 
    355   if (rreg != NULL)
    356     return rreg->value.reg_val;
    357 
    358   return nullregister;
    359 }
    360 
    361 /* Get the index register 'reg_name'.  */
    362 
    363 static reg
    364 get_index_register (char *reg_name)
    365 {
    366   const reg_entry *rreg;
    367 
    368   rreg = str_hash_find (reg_hash, reg_name);
    369 
    370   if ((rreg != NULL)
    371       && ((rreg->value.reg_val == 12) || (rreg->value.reg_val == 13)))
    372     return rreg->value.reg_val;
    373 
    374   return nullregister;
    375 }
    376 /* Get the core processor index register-pair 'reg_name'.  */
    377 
    378 static reg
    379 get_index_register_pair (char *reg_name)
    380 {
    381   const reg_entry *rreg;
    382 
    383   rreg = str_hash_find (regp_hash, reg_name);
    384 
    385   if (rreg != NULL)
    386     {
    387       if ((rreg->value.reg_val != 1) || (rreg->value.reg_val != 7)
    388 	  || (rreg->value.reg_val != 9) || (rreg->value.reg_val > 10))
    389 	return rreg->value.reg_val;
    390 
    391       as_bad (_("Unknown register pair - index relative mode: `%d'"), rreg->value.reg_val);
    392     }
    393 
    394   return nullregister;
    395 }
    396 
    397 /* Get the processor register 'preg_name'.  */
    398 
    399 static preg
    400 get_pregister (char *preg_name)
    401 {
    402   const reg_entry *prreg;
    403 
    404   prreg = str_hash_find (preg_hash, preg_name);
    405 
    406   if (prreg != NULL)
    407     return prreg->value.preg_val;
    408 
    409   return nullpregister;
    410 }
    411 
    412 /* Get the processor register 'preg_name 32 bit'.  */
    413 
    414 static preg
    415 get_pregisterp (char *preg_name)
    416 {
    417   const reg_entry *prreg;
    418 
    419   prreg = str_hash_find (pregp_hash, preg_name);
    420 
    421   if (prreg != NULL)
    422     return prreg->value.preg_val;
    423 
    424   return nullpregister;
    425 }
    426 
    427 
    428 /* Round up a section size to the appropriate boundary.  */
    429 
    430 valueT
    431 md_section_align (segT seg, valueT val)
    432 {
    433   /* Round .text section to a multiple of 2.  */
    434   if (seg == text_section)
    435     return (val + 1) & ~1;
    436   return val;
    437 }
    438 
    439 /* Parse an operand that is machine-specific (remove '*').  */
    440 
    441 void
    442 md_operand (expressionS * exp)
    443 {
    444   char c = *input_line_pointer;
    445 
    446   switch (c)
    447     {
    448     case '*':
    449       input_line_pointer++;
    450       expression (exp);
    451       break;
    452     default:
    453       break;
    454     }
    455 }
    456 
    457 /* Reset global variables before parsing a new instruction.  */
    458 
    459 static void
    460 reset_vars (char *op)
    461 {
    462   cur_arg_num = relocatable = 0;
    463   memset (& output_opcode, '\0', sizeof (output_opcode));
    464 
    465   /* Save a copy of the original OP (used in error messages).  */
    466   strncpy (ins_parse, op, sizeof ins_parse - 1);
    467   ins_parse [sizeof ins_parse - 1] = 0;
    468 }
    469 
    470 /* This macro decides whether a particular reloc is an entry in a
    471    switch table.  It is used when relaxing, because the linker needs
    472    to know about all such entries so that it can adjust them if
    473    necessary.  */
    474 
    475 #define SWITCH_TABLE(fix)						\
    476   ((fix)->fx_addsy != NULL						\
    477    && (fix)->fx_subsy != NULL						\
    478    && ((fix)->fx_r_type == BFD_RELOC_CR16_NUM8				\
    479        || (fix)->fx_r_type == BFD_RELOC_CR16_NUM16			\
    480        || (fix)->fx_r_type == BFD_RELOC_CR16_NUM32			\
    481        || (fix)->fx_r_type == BFD_RELOC_CR16_NUM32a)			\
    482    && S_GET_SEGMENT ((fix)->fx_addsy) != undefined_section		\
    483    && S_GET_SEGMENT ((fix)->fx_addsy) == S_GET_SEGMENT ((fix)->fx_subsy))
    484 
    485 /* See whether we need to force a relocation into the output file.
    486    This is used to force out switch and PC relative relocations when
    487    relaxing.  */
    488 
    489 int
    490 cr16_force_relocation (fixS *fix)
    491 {
    492   if (generic_force_reloc (fix) || SWITCH_TABLE (fix))
    493     return 1;
    494 
    495   return 0;
    496 }
    497 
    498 /* Record a fixup for a cons expression.  */
    499 
    500 void
    501 cr16_cons_fix_new (fragS *frag, int offset, int len, expressionS *exp,
    502 		   bfd_reloc_code_real_type rtype)
    503 {
    504   switch (len)
    505     {
    506     default: rtype = BFD_RELOC_NONE; break;
    507     case 1: rtype = BFD_RELOC_CR16_NUM8 ; break;
    508     case 2: rtype = BFD_RELOC_CR16_NUM16; break;
    509     case 4:
    510       if (code_label)
    511 	{
    512 	  rtype = BFD_RELOC_CR16_NUM32a;
    513 	  code_label = 0;
    514 	}
    515       else
    516 	rtype = BFD_RELOC_CR16_NUM32;
    517       break;
    518     }
    519 
    520   fix_new_exp (frag, offset, len, exp, 0, rtype);
    521 }
    522 
    523 /* Generate a relocation entry for a fixup.  */
    524 
    525 arelent *
    526 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS * fixP)
    527 {
    528   arelent * reloc;
    529 
    530   /* If symbols are local and resolved, then no relocation needed.  */
    531   if ( ((fixP->fx_addsy)
    532 	&& (S_GET_SEGMENT (fixP->fx_addsy) == absolute_section))
    533        || ((fixP->fx_subsy)
    534 	   && (S_GET_SEGMENT (fixP->fx_subsy) == absolute_section)))
    535     return NULL;
    536 
    537   reloc = notes_alloc (sizeof (arelent));
    538   reloc->sym_ptr_ptr = notes_alloc (sizeof (asymbol *));
    539   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixP->fx_addsy);
    540   reloc->address = fixP->fx_frag->fr_address + fixP->fx_where;
    541   reloc->addend = fixP->fx_offset;
    542 
    543   if (fixP->fx_subsy != NULL)
    544     {
    545       if (SWITCH_TABLE (fixP))
    546 	{
    547 	  /* Keep the current difference in the addend.  */
    548 	  reloc->addend = (S_GET_VALUE (fixP->fx_addsy)
    549 			   - S_GET_VALUE (fixP->fx_subsy) + fixP->fx_offset);
    550 
    551 	  switch (fixP->fx_r_type)
    552 	    {
    553 	    case BFD_RELOC_CR16_NUM8:
    554 	      fixP->fx_r_type = BFD_RELOC_CR16_SWITCH8;
    555 	      break;
    556 	    case BFD_RELOC_CR16_NUM16:
    557 	      fixP->fx_r_type = BFD_RELOC_CR16_SWITCH16;
    558 	      break;
    559 	    case BFD_RELOC_CR16_NUM32:
    560 	      fixP->fx_r_type = BFD_RELOC_CR16_SWITCH32;
    561 	      break;
    562 	    case BFD_RELOC_CR16_NUM32a:
    563 	      fixP->fx_r_type = BFD_RELOC_CR16_NUM32a;
    564 	      break;
    565 	    default:
    566 	      abort ();
    567 	      break;
    568 	    }
    569 	}
    570       else
    571 	{
    572 	  /* We only resolve difference expressions in the same section.  */
    573 	  as_bad_subtract (fixP);
    574 	  return NULL;
    575 	}
    576     }
    577 #ifdef OBJ_ELF
    578   if ((fixP->fx_r_type == BFD_RELOC_CR16_GOT_REGREL20)
    579       && GOT_symbol
    580       && fixP->fx_addsy == GOT_symbol)
    581     {
    582       reloc->addend = fixP->fx_offset = reloc->address;
    583     }
    584   else if ((fixP->fx_r_type == BFD_RELOC_CR16_GOTC_REGREL20)
    585 	   && GOT_symbol
    586 	   && fixP->fx_addsy == GOT_symbol)
    587     {
    588       reloc->addend = fixP->fx_offset = reloc->address;
    589     }
    590 #endif
    591 
    592   gas_assert ((int) fixP->fx_r_type > 0);
    593   reloc->howto = bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
    594 
    595   if (reloc->howto == NULL)
    596     {
    597       as_bad_where (fixP->fx_file, fixP->fx_line,
    598 		    _("internal error: reloc %d (`%s') not supported by object file format"),
    599 		    fixP->fx_r_type,
    600 		    bfd_get_reloc_code_name (fixP->fx_r_type));
    601       return NULL;
    602     }
    603   gas_assert (!fixP->fx_pcrel == !reloc->howto->pc_relative);
    604 
    605   return reloc;
    606 }
    607 
    608 /* Prepare machine-dependent frags for relaxation.  */
    609 
    610 int
    611 md_estimate_size_before_relax (fragS *fragp, asection *seg)
    612 {
    613   /* If symbol is undefined or located in a different section,
    614      select the largest supported relocation.  */
    615   relax_substateT subtype;
    616   relax_substateT rlx_state[] = {0, 2};
    617 
    618   for (subtype = 0; subtype < ARRAY_SIZE (rlx_state); subtype += 2)
    619     {
    620       if (fragp->fr_subtype == rlx_state[subtype]
    621 	  && (!S_IS_DEFINED (fragp->fr_symbol)
    622 	      || seg != S_GET_SEGMENT (fragp->fr_symbol)))
    623 	{
    624 	  fragp->fr_subtype = rlx_state[subtype + 1];
    625 	  break;
    626 	}
    627     }
    628 
    629   if (fragp->fr_subtype >= ARRAY_SIZE (md_relax_table))
    630     abort ();
    631 
    632   return md_relax_table[fragp->fr_subtype].rlx_length;
    633 }
    634 
    635 void
    636 md_convert_frag (bfd *abfd ATTRIBUTE_UNUSED,
    637 		 asection *sec ATTRIBUTE_UNUSED,
    638 		 fragS *fragP)
    639 {
    640   /* 'opcode' points to the start of the instruction, whether
    641      we need to change the instruction's fixed encoding.  */
    642   char *opcode = &fragP->fr_literal[0] + fragP->fr_fix;
    643   bfd_reloc_code_real_type reloc;
    644 
    645   switch (fragP->fr_subtype)
    646     {
    647     case 0:
    648       reloc = BFD_RELOC_CR16_DISP8;
    649       break;
    650     case 1:
    651       /* If the subtype is not changed due to :m operand qualifier,
    652 	 then no need to update the opcode value.  */
    653       if ((int)opcode[1] != 0x18)
    654 	{
    655 	  opcode[0] = (opcode[0] & 0xf0);
    656 	  opcode[1] = 0x18;
    657 	}
    658       reloc = BFD_RELOC_CR16_DISP16;
    659       break;
    660     case 2:
    661       /* If the subtype is not changed due to :l operand qualifier,
    662 	 then no need to update the opcode value.  */
    663       if ((int)opcode[1] != 0)
    664 	{
    665 	  opcode[2] = opcode[0];
    666 	  opcode[0] = opcode[1];
    667 	  opcode[1] = 0x0;
    668 	}
    669       reloc = BFD_RELOC_CR16_DISP24;
    670       break;
    671     default:
    672       abort();
    673     }
    674 
    675   fix_new (fragP, fragP->fr_fix,
    676 	   bfd_get_reloc_size (bfd_reloc_type_lookup (stdoutput, reloc)),
    677 	   fragP->fr_symbol, fragP->fr_offset, 1, reloc);
    678   fragP->fr_var = 0;
    679   fragP->fr_fix += md_relax_table[fragP->fr_subtype].rlx_length;
    680 }
    681 
    682 symbolS *
    683 md_undefined_symbol (char *name)
    684 {
    685   if (*name == '_' && *(name + 1) == 'G'
    686       && strcmp (name, "_GLOBAL_OFFSET_TABLE_") == 0)
    687     {
    688       if (!GOT_symbol)
    689 	{
    690 	  if (symbol_find (name))
    691 	    as_bad (_("GOT already in symbol table"));
    692 	  GOT_symbol = symbol_new (name, undefined_section,
    693 				   &zero_address_frag, 0);
    694 	}
    695       return GOT_symbol;
    696     }
    697   return 0;
    698 }
    699 
    700 /* Process machine-dependent command line options.  Called once for
    701    each option on the command line that the machine-independent part of
    702    GAS does not understand.  */
    703 
    704 int
    705 md_parse_option (int c ATTRIBUTE_UNUSED, const char *arg ATTRIBUTE_UNUSED)
    706 {
    707   return 0;
    708 }
    709 
    710 /* Machine-dependent usage-output.  */
    711 
    712 void
    713 md_show_usage (FILE *stream ATTRIBUTE_UNUSED)
    714 {
    715   return;
    716 }
    717 
    718 const char *
    719 md_atof (int type, char *litP, int *sizeP)
    720 {
    721   return ieee_md_atof (type, litP, sizeP, target_big_endian);
    722 }
    723 
    724 /* Apply a fixS (fixup of an instruction or data that we didn't have
    725    enough info to complete immediately) to the data in a frag.
    726    Since linkrelax is nonzero and TC_LINKRELAX_FIXUP is defined to disable
    727    relaxation of debug sections, this function is called only when
    728    fixuping relocations of debug sections.  */
    729 
    730 void
    731 md_apply_fix (fixS *fixP, valueT *valP, segT seg)
    732 {
    733   valueT val = * valP;
    734 
    735   if (fixP->fx_addsy == NULL
    736       && fixP->fx_pcrel == 0)
    737     fixP->fx_done = 1;
    738   else if (fixP->fx_pcrel == 1
    739       && fixP->fx_addsy != NULL
    740       && S_GET_SEGMENT (fixP->fx_addsy) == seg)
    741     fixP->fx_done = 1;
    742   else
    743     fixP->fx_done = 0;
    744 
    745   if (fixP->fx_addsy != NULL && !fixP->fx_pcrel)
    746     {
    747       val = fixP->fx_offset;
    748       fixP->fx_done = 1;
    749     }
    750 
    751   if (fixP->fx_done)
    752     {
    753       char *buf = fixP->fx_frag->fr_literal + fixP->fx_where;
    754 
    755       fixP->fx_offset = 0;
    756 
    757       switch (fixP->fx_r_type)
    758 	{
    759 	case BFD_RELOC_CR16_NUM8:
    760 	  bfd_put_8 (stdoutput, val, buf);
    761 	  break;
    762 	case BFD_RELOC_CR16_NUM16:
    763 	  bfd_put_16 (stdoutput, val, buf);
    764 	  break;
    765 	case BFD_RELOC_CR16_NUM32:
    766 	  bfd_put_32 (stdoutput, val, buf);
    767 	  break;
    768 	case BFD_RELOC_CR16_NUM32a:
    769 	  bfd_put_32 (stdoutput, val, buf);
    770 	  break;
    771 	default:
    772 	  /* We shouldn't ever get here because linkrelax is nonzero.  */
    773 	  abort ();
    774 	  break;
    775 	}
    776       fixP->fx_done = 0;
    777     }
    778   else
    779     fixP->fx_offset = * valP;
    780 }
    781 
    782 /* The location from which a PC relative jump should be calculated,
    783    given a PC relative reloc.  */
    784 
    785 long
    786 md_pcrel_from (fixS *fixp)
    787 {
    788   return fixp->fx_frag->fr_address + fixp->fx_where;
    789 }
    790 
    791 static void
    792 initialise_reg_hash_table (htab_t *hash_table,
    793 			   const reg_entry *register_table,
    794 			   const unsigned int num_entries)
    795 {
    796   const reg_entry *rreg;
    797 
    798   *hash_table = str_htab_create ();
    799 
    800   for (rreg = register_table;
    801        rreg < (register_table + num_entries);
    802        rreg++)
    803     if (str_hash_insert (*hash_table, rreg->name, rreg, 0) != NULL)
    804       as_fatal (_("duplicate %s"), rreg->name);
    805 }
    806 
    807 /* This function is called once, at assembler startup time.  This should
    808    set up all the tables, etc that the MD part of the assembler needs.  */
    809 
    810 void
    811 md_begin (void)
    812 {
    813   int i = 0;
    814 
    815   /* Set up a hash table for the instructions.  */
    816   cr16_inst_hash = str_htab_create ();
    817 
    818   while (cr16_instruction[i].mnemonic != NULL)
    819     {
    820       const char *mnemonic = cr16_instruction[i].mnemonic;
    821 
    822       if (str_hash_insert (cr16_inst_hash, mnemonic, cr16_instruction + i, 0))
    823 	as_fatal (_("duplicate %s"), mnemonic);
    824 
    825       /* Insert unique names into hash table.  The CR16 instruction set
    826 	 has many identical opcode names that have different opcodes based
    827 	 on the operands.  This hash table then provides a quick index to
    828 	 the first opcode with a particular name in the opcode table.  */
    829       do
    830 	{
    831 	  ++i;
    832 	}
    833       while (cr16_instruction[i].mnemonic != NULL
    834 	     && streq (cr16_instruction[i].mnemonic, mnemonic));
    835     }
    836 
    837   /* Initialize reg_hash hash table.  */
    838   initialise_reg_hash_table (& reg_hash, cr16_regtab, NUMREGS);
    839   /* Initialize regp_hash hash table.  */
    840   initialise_reg_hash_table (& regp_hash, cr16_regptab, NUMREGPS);
    841   /* Initialize preg_hash hash table.  */
    842   initialise_reg_hash_table (& preg_hash, cr16_pregtab, NUMPREGS);
    843   /* Initialize pregp_hash hash table.  */
    844   initialise_reg_hash_table (& pregp_hash, cr16_pregptab, NUMPREGPS);
    845 
    846   /*  Set linkrelax here to avoid fixups in most sections.  */
    847   linkrelax = 1;
    848 }
    849 
    850 /* Process constants (immediate/absolute)
    851    and labels (jump targets/Memory locations).  */
    852 
    853 static void
    854 process_label_constant (char *str, ins * cr16_ins)
    855 {
    856   char *saved_input_line_pointer;
    857   int symbol_with_at = 0;
    858   int symbol_with_s = 0;
    859   int symbol_with_m = 0;
    860   int symbol_with_l = 0;
    861   int symbol_with_at_got = 0;
    862   int symbol_with_at_gotc = 0;
    863   argument *cur_arg = cr16_ins->arg + cur_arg_num;  /* Current argument.  */
    864 
    865   saved_input_line_pointer = input_line_pointer;
    866   input_line_pointer = str;
    867 
    868   expression (&cr16_ins->exp);
    869 
    870   switch (cr16_ins->exp.X_op)
    871     {
    872     case O_big:
    873     case O_absent:
    874       /* Missing or bad expr becomes absolute 0.  */
    875       as_bad (_("missing or invalid displacement expression `%s' taken as 0"),
    876 	      str);
    877       cr16_ins->exp.X_op = O_constant;
    878       cr16_ins->exp.X_add_number = 0;
    879       cr16_ins->exp.X_add_symbol = NULL;
    880       cr16_ins->exp.X_op_symbol = NULL;
    881       /* Fall through.  */
    882 
    883     case O_constant:
    884       cur_arg->X_op = O_constant;
    885       cur_arg->constant = cr16_ins->exp.X_add_number;
    886       break;
    887 
    888     case O_symbol:
    889     case O_subtract:
    890     case O_add:
    891       cur_arg->X_op = O_symbol;
    892       cur_arg->constant = cr16_ins->exp.X_add_number;
    893       cr16_ins->exp.X_add_number = 0;
    894       cr16_ins->rtype = BFD_RELOC_NONE;
    895       relocatable = 1;
    896 
    897       if (startswith (input_line_pointer, "@c"))
    898 	symbol_with_at = 1;
    899 
    900       if (startswith (input_line_pointer, "@l")
    901 	  || startswith (input_line_pointer, ":l"))
    902 	symbol_with_l = 1;
    903 
    904       if (startswith (input_line_pointer, "@m")
    905 	  || startswith (input_line_pointer, ":m"))
    906 	symbol_with_m = 1;
    907 
    908       if (startswith (input_line_pointer, "@s")
    909 	  || startswith (input_line_pointer, ":s"))
    910 	symbol_with_s = 1;
    911 
    912       if (startswith (input_line_pointer, "@cGOT")
    913 	  || startswith (input_line_pointer, "@cgot"))
    914 	{
    915 	  if (GOT_symbol == NULL)
    916 	    GOT_symbol = symbol_find_or_make (GLOBAL_OFFSET_TABLE_NAME);
    917 
    918 	  symbol_with_at_gotc = 1;
    919 	}
    920       else if (startswith (input_line_pointer, "@GOT")
    921 	       || startswith (input_line_pointer, "@got"))
    922 	{
    923 	  if ((startswith (input_line_pointer, "+"))
    924 	      || (startswith (input_line_pointer, "-")))
    925 	    as_warn (_("GOT bad expression with %s."), input_line_pointer);
    926 
    927 	  if (GOT_symbol == NULL)
    928 	    GOT_symbol = symbol_find_or_make (GLOBAL_OFFSET_TABLE_NAME);
    929 
    930 	  symbol_with_at_got = 1;
    931 	}
    932 
    933       switch (cur_arg->type)
    934 	{
    935 	case arg_cr:
    936 	  if (IS_INSN_TYPE (LD_STOR_INS) || IS_INSN_TYPE (CSTBIT_INS))
    937 	    {
    938 	      if (symbol_with_at_got)
    939 		cr16_ins->rtype = BFD_RELOC_CR16_GOT_REGREL20;
    940 	      else if (symbol_with_at_gotc)
    941 		cr16_ins->rtype = BFD_RELOC_CR16_GOTC_REGREL20;
    942 	      else if (cur_arg->size == 20)
    943 		cr16_ins->rtype = BFD_RELOC_CR16_REGREL20;
    944 	      else
    945 		cr16_ins->rtype = BFD_RELOC_CR16_REGREL20a;
    946 	    }
    947 	  break;
    948 
    949 	case arg_crp:
    950 	  if (IS_INSN_TYPE (LD_STOR_INS) || IS_INSN_TYPE (CSTBIT_INS))
    951 	    {
    952 	      if (symbol_with_at_got)
    953 		cr16_ins->rtype = BFD_RELOC_CR16_GOT_REGREL20;
    954 	      else if (symbol_with_at_gotc)
    955 		cr16_ins->rtype = BFD_RELOC_CR16_GOTC_REGREL20;
    956 	    } else {
    957 	    switch (instruction->size)
    958 	      {
    959 	      case 1:
    960 		switch (cur_arg->size)
    961 		  {
    962 		  case 0:
    963 		    cr16_ins->rtype = BFD_RELOC_CR16_REGREL0;
    964 		    break;
    965 		  case 4:
    966 		    if (IS_INSN_MNEMONIC ("loadb") || IS_INSN_MNEMONIC ("storb"))
    967 		      cr16_ins->rtype = BFD_RELOC_CR16_REGREL4;
    968 		    else
    969 		      cr16_ins->rtype = BFD_RELOC_CR16_REGREL4a;
    970 		    break;
    971 		  default: break;
    972 		  }
    973 		break;
    974 	      case 2:
    975 		cr16_ins->rtype = BFD_RELOC_CR16_REGREL16;
    976 		break;
    977 	      case 3:
    978 		if (cur_arg->size == 20)
    979 		  cr16_ins->rtype = BFD_RELOC_CR16_REGREL20;
    980 		else
    981 		  cr16_ins->rtype = BFD_RELOC_CR16_REGREL20a;
    982 		break;
    983 	      default:
    984 		break;
    985 	      }
    986 	  }
    987 	  break;
    988 
    989 	case arg_idxr:
    990 	  if (IS_INSN_TYPE (LD_STOR_INS) || IS_INSN_TYPE (CSTBIT_INS))
    991 	    {
    992 	      if (symbol_with_at_got)
    993 		cr16_ins->rtype = BFD_RELOC_CR16_GOT_REGREL20;
    994 	      else if (symbol_with_at_gotc)
    995 		cr16_ins->rtype = BFD_RELOC_CR16_GOTC_REGREL20;
    996 	      else
    997 		cr16_ins->rtype = BFD_RELOC_CR16_REGREL20;
    998 	    }
    999 	  break;
   1000 
   1001 	case arg_idxrp:
   1002 	  if (IS_INSN_TYPE (LD_STOR_INS) || IS_INSN_TYPE (CSTBIT_INS))
   1003 	    {
   1004 	      if (symbol_with_at_got)
   1005 		cr16_ins->rtype = BFD_RELOC_CR16_GOT_REGREL20;
   1006 	      else if (symbol_with_at_gotc)
   1007 		cr16_ins->rtype = BFD_RELOC_CR16_GOTC_REGREL20;
   1008 	      else {
   1009 		switch (instruction->size)
   1010 		  {
   1011 		  case 1: cr16_ins->rtype = BFD_RELOC_CR16_REGREL0; break;
   1012 		  case 2: cr16_ins->rtype = BFD_RELOC_CR16_REGREL14; break;
   1013 		  case 3: cr16_ins->rtype = BFD_RELOC_CR16_REGREL20; break;
   1014 		  default: break;
   1015 		  }
   1016 	      }
   1017 	    }
   1018 	  break;
   1019 
   1020 	case arg_c:
   1021 	  if (IS_INSN_MNEMONIC ("bal"))
   1022 	    cr16_ins->rtype = BFD_RELOC_CR16_DISP24;
   1023 	  else if (IS_INSN_TYPE (BRANCH_INS))
   1024 	    {
   1025 	      if (symbol_with_l)
   1026 		cr16_ins->rtype = BFD_RELOC_CR16_DISP24;
   1027 	      else if (symbol_with_m)
   1028 		cr16_ins->rtype = BFD_RELOC_CR16_DISP16;
   1029 	      else
   1030 		cr16_ins->rtype = BFD_RELOC_CR16_DISP8;
   1031 	    }
   1032 	  else if (IS_INSN_TYPE (STOR_IMM_INS) || IS_INSN_TYPE (LD_STOR_INS)
   1033 		   || IS_INSN_TYPE (CSTBIT_INS))
   1034 	    {
   1035 	      if (symbol_with_s)
   1036 		as_bad (_("operand %d: illegal use expression: `%s`"), cur_arg_num + 1, str);
   1037 	      if (symbol_with_at_got)
   1038 		cr16_ins->rtype = BFD_RELOC_CR16_GOT_REGREL20;
   1039 	      else if (symbol_with_at_gotc)
   1040 		cr16_ins->rtype = BFD_RELOC_CR16_GOTC_REGREL20;
   1041 	      else if (symbol_with_m)
   1042 		cr16_ins->rtype = BFD_RELOC_CR16_ABS20;
   1043 	      else /* Default to (symbol_with_l) */
   1044 		cr16_ins->rtype = BFD_RELOC_CR16_ABS24;
   1045 	    }
   1046 	  else if (IS_INSN_TYPE (BRANCH_NEQ_INS))
   1047 	    cr16_ins->rtype = BFD_RELOC_CR16_DISP4;
   1048 	  break;
   1049 
   1050 	case arg_ic:
   1051 	  if (IS_INSN_TYPE (ARITH_INS))
   1052 	    {
   1053 	      if (symbol_with_at_got)
   1054 		cr16_ins->rtype = BFD_RELOC_CR16_GOT_REGREL20;
   1055 	      else if (symbol_with_at_gotc)
   1056 		cr16_ins->rtype = BFD_RELOC_CR16_GOTC_REGREL20;
   1057 	      else if (symbol_with_s)
   1058 		cr16_ins->rtype = BFD_RELOC_CR16_IMM4;
   1059 	      else if (symbol_with_m)
   1060 		cr16_ins->rtype = BFD_RELOC_CR16_IMM20;
   1061 	      else if (symbol_with_at)
   1062 		cr16_ins->rtype = BFD_RELOC_CR16_IMM32a;
   1063 	      else /* Default to (symbol_with_l) */
   1064 		cr16_ins->rtype = BFD_RELOC_CR16_IMM32;
   1065 	    }
   1066 	  else if (IS_INSN_TYPE (ARITH_BYTE_INS))
   1067 	    {
   1068 	      cr16_ins->rtype = BFD_RELOC_CR16_IMM16;
   1069 	    }
   1070 	  break;
   1071 	default:
   1072 	  break;
   1073 	}
   1074       break;
   1075 
   1076     default:
   1077       cur_arg->X_op = cr16_ins->exp.X_op;
   1078       break;
   1079     }
   1080 
   1081   input_line_pointer = saved_input_line_pointer;
   1082   return;
   1083 }
   1084 
   1085 /* Retrieve the opcode image of a given register.
   1086    If the register is illegal for the current instruction,
   1087    issue an error.  */
   1088 
   1089 static int
   1090 getreg_image (reg r)
   1091 {
   1092   const reg_entry *rreg;
   1093   char *reg_name;
   1094   int is_procreg = 0; /* Nonzero means argument should be processor reg.  */
   1095 
   1096   /* Check whether the register is in registers table.  */
   1097   if (r < MAX_REG)
   1098     rreg = cr16_regtab + r;
   1099   else /* Register not found.  */
   1100     {
   1101       as_bad (_("Unknown register: `%d'"), r);
   1102       return 0;
   1103     }
   1104 
   1105   reg_name = rreg->name;
   1106 
   1107   /* Issue a error message when register is illegal.  */
   1108 #define IMAGE_ERR						\
   1109   as_bad (_("Illegal register (`%s') in Instruction: `%s'"),	\
   1110 	  reg_name, ins_parse);
   1111 
   1112   switch (rreg->type)
   1113     {
   1114     case CR16_R_REGTYPE:
   1115       if (! is_procreg)
   1116 	return rreg->image;
   1117       else
   1118 	IMAGE_ERR;
   1119       break;
   1120 
   1121     case CR16_P_REGTYPE:
   1122       return rreg->image;
   1123       break;
   1124 
   1125     default:
   1126       IMAGE_ERR;
   1127       break;
   1128     }
   1129 
   1130   return 0;
   1131 }
   1132 
   1133 /* Parsing different types of operands
   1134    -> constants             Immediate/Absolute/Relative numbers
   1135    -> Labels                Relocatable symbols
   1136    -> (reg pair base)       Register pair base
   1137    -> (rbase)               Register base
   1138    -> disp(rbase)           Register relative
   1139    -> [rinx]disp(reg pair)  Register index with reg pair mode
   1140    -> disp(rbase,ridx,scl)  Register index mode.  */
   1141 
   1142 static void
   1143 set_operand (char *operand, ins * cr16_ins)
   1144 {
   1145   char *operandS; /* Pointer to start of sub-operand.  */
   1146   char *operandE; /* Pointer to end of sub-operand.  */
   1147 
   1148   argument *cur_arg = &cr16_ins->arg[cur_arg_num]; /* Current argument.  */
   1149 
   1150   /* Initialize pointers.  */
   1151   operandS = operandE = operand;
   1152 
   1153   switch (cur_arg->type)
   1154     {
   1155     case arg_ic:    /* Case $0x18.  */
   1156       operandS++;
   1157       /* Fall through.  */
   1158     case arg_c:     /* Case 0x18.  */
   1159       /* Set constant.  */
   1160       process_label_constant (operandS, cr16_ins);
   1161 
   1162       if (cur_arg->type != arg_ic)
   1163 	cur_arg->type = arg_c;
   1164       break;
   1165 
   1166     case arg_icr:   /* Case $0x18(r1).  */
   1167       operandS++;
   1168     case arg_cr:    /* Case 0x18(r1).   */
   1169       /* Set displacement constant.  */
   1170       while (*operandE != '(')
   1171 	operandE++;
   1172       *operandE = '\0';
   1173       process_label_constant (operandS, cr16_ins);
   1174       operandS = operandE;
   1175       /* Fall through.  */
   1176     case arg_rbase: /* Case (r1) or (r1,r0).  */
   1177       operandS++;
   1178       /* Set register base.  */
   1179       while (*operandE != ')')
   1180 	operandE++;
   1181       *operandE = '\0';
   1182       if ((cur_arg->r = get_register (operandS)) == nullregister)
   1183 	as_bad (_("Illegal register `%s' in Instruction `%s'"),
   1184 		operandS, ins_parse);
   1185 
   1186       /* set the arg->rp, if reg is "r12" or "r13" or "14" or "15" */
   1187       if ((cur_arg->type != arg_rbase)
   1188 	  && ((getreg_image (cur_arg->r) == 12)
   1189 	      || (getreg_image (cur_arg->r) == 13)
   1190 	      || (getreg_image (cur_arg->r) == 14)
   1191 	      || (getreg_image (cur_arg->r) == 15)))
   1192 	{
   1193 	  cur_arg->type = arg_crp;
   1194 	  cur_arg->rp = cur_arg->r;
   1195 	}
   1196       break;
   1197 
   1198     case arg_crp:    /* Case 0x18(r1,r0).   */
   1199       /* Set displacement constant.  */
   1200       while (*operandE != '(')
   1201 	operandE++;
   1202       *operandE = '\0';
   1203       process_label_constant (operandS, cr16_ins);
   1204       operandS = operandE;
   1205       operandS++;
   1206       /* Set register pair base.  */
   1207       while (*operandE != ')')
   1208 	operandE++;
   1209       *operandE = '\0';
   1210       if ((cur_arg->rp = get_register_pair (operandS)) == nullregister)
   1211 	as_bad (_("Illegal register pair `%s' in Instruction `%s'"),
   1212 		operandS, ins_parse);
   1213       break;
   1214 
   1215     case arg_idxr:
   1216       /* Set register pair base.  */
   1217       if ((strchr (operandS,'(') != NULL))
   1218 	{
   1219 	  while ((*operandE != '(') && (! is_whitespace (*operandE)))
   1220 	    operandE++;
   1221 	  if ((cur_arg->rp = get_index_register_pair (operandE)) == nullregister)
   1222 	    as_bad (_("Illegal register pair `%s' in Instruction `%s'"),
   1223 		    operandS, ins_parse);
   1224 	  *operandE++ = '\0';
   1225 	  cur_arg->type = arg_idxrp;
   1226 	}
   1227       else
   1228 	cur_arg->rp = -1;
   1229 
   1230       operandE = operandS;
   1231       /* Set displacement constant.  */
   1232       while (*operandE != ']')
   1233 	operandE++;
   1234       process_label_constant (++operandE, cr16_ins);
   1235       *operandE++ = '\0';
   1236       operandE = operandS;
   1237 
   1238       /* Set index register .  */
   1239       operandS = strchr (operandE,'[');
   1240       if (operandS != NULL)
   1241 	{ /* Eliminate '[', detach from rest of operand.  */
   1242 	  *operandS++ = '\0';
   1243 
   1244 	  operandE = strchr (operandS, ']');
   1245 
   1246 	  if (operandE == NULL)
   1247 	    as_bad (_("unmatched '['"));
   1248 	  else
   1249 	    { /* Eliminate ']' and make sure it was the last thing
   1250 		 in the string.  */
   1251 	      *operandE = '\0';
   1252 	      if (*(operandE + 1) != '\0')
   1253 		as_bad (_("garbage after index spec ignored"));
   1254 	    }
   1255 	}
   1256 
   1257       if ((cur_arg->i_r = get_index_register (operandS)) == nullregister)
   1258 	as_bad (_("Illegal register `%s' in Instruction `%s'"),
   1259 		operandS, ins_parse);
   1260       *operandE = '\0';
   1261       *operandS = '\0';
   1262       break;
   1263 
   1264     default:
   1265       break;
   1266     }
   1267 }
   1268 
   1269 /* Parse a single operand.
   1270    operand - Current operand to parse.
   1271    cr16_ins - Current assembled instruction.  */
   1272 
   1273 static void
   1274 parse_operand (char *operand, ins * cr16_ins)
   1275 {
   1276   int ret_val;
   1277   argument *cur_arg = cr16_ins->arg + cur_arg_num; /* Current argument.  */
   1278 
   1279   /* Initialize the type to NULL before parsing.  */
   1280   cur_arg->type = nullargs;
   1281 
   1282   /* Check whether this is a condition code .  */
   1283   if ((IS_INSN_MNEMONIC ("b")) && ((ret_val = get_cc (operand)) != -1))
   1284     {
   1285       cur_arg->type = arg_cc;
   1286       cur_arg->cc = ret_val;
   1287       cur_arg->X_op = O_register;
   1288       return;
   1289     }
   1290 
   1291   /* Check whether this is a general processor register.  */
   1292   if ((ret_val = get_register (operand)) != nullregister)
   1293     {
   1294       cur_arg->type = arg_r;
   1295       cur_arg->r = ret_val;
   1296       cur_arg->X_op = 0;
   1297       return;
   1298     }
   1299 
   1300   /* Check whether this is a general processor register pair.  */
   1301   if ((operand[0] == '(')
   1302       && ((ret_val = get_register_pair (operand)) != nullregister))
   1303     {
   1304       cur_arg->type = arg_rp;
   1305       cur_arg->rp = ret_val;
   1306       cur_arg->X_op = O_register;
   1307       return;
   1308     }
   1309 
   1310   /* Check whether the operand is a processor register.
   1311      For "lprd" and "sprd" instruction, only 32 bit
   1312      processor registers used.  */
   1313   if (!(IS_INSN_MNEMONIC ("lprd") || (IS_INSN_MNEMONIC ("sprd")))
   1314       && ((ret_val = get_pregister (operand)) != nullpregister))
   1315     {
   1316       cur_arg->type = arg_pr;
   1317       cur_arg->pr = ret_val;
   1318       cur_arg->X_op = O_register;
   1319       return;
   1320     }
   1321 
   1322   /* Check whether this is a processor register - 32 bit.  */
   1323   if ((ret_val = get_pregisterp (operand)) != nullpregister)
   1324     {
   1325       cur_arg->type = arg_prp;
   1326       cur_arg->prp = ret_val;
   1327       cur_arg->X_op = O_register;
   1328       return;
   1329     }
   1330 
   1331   /* Deal with special characters.  */
   1332   switch (operand[0])
   1333     {
   1334     case '$':
   1335       if (strchr (operand, '(') != NULL)
   1336 	cur_arg->type = arg_icr;
   1337       else
   1338 	cur_arg->type = arg_ic;
   1339       goto set_params;
   1340       break;
   1341 
   1342     case '(':
   1343       cur_arg->type = arg_rbase;
   1344       goto set_params;
   1345       break;
   1346 
   1347     case '[':
   1348       cur_arg->type = arg_idxr;
   1349       goto set_params;
   1350       break;
   1351 
   1352     default:
   1353       break;
   1354     }
   1355 
   1356   if (strchr (operand, '(') != NULL)
   1357     {
   1358       if (strchr (operand, ',') != NULL
   1359 	  && (strchr (operand, ',') > strchr (operand, '(')))
   1360 	cur_arg->type = arg_crp;
   1361       else
   1362 	cur_arg->type = arg_cr;
   1363     }
   1364   else
   1365     cur_arg->type = arg_c;
   1366 
   1367   /* Parse an operand according to its type.  */
   1368  set_params:
   1369   cur_arg->constant = 0;
   1370   set_operand (operand, cr16_ins);
   1371 }
   1372 
   1373 /* Parse the various operands. Each operand is then analyzed to fillup
   1374    the fields in the cr16_ins data structure.  */
   1375 
   1376 static void
   1377 parse_operands (ins * cr16_ins, char *operands)
   1378 {
   1379   char *operandS;            /* Operands string.  */
   1380   char *operandH, *operandT; /* Single operand head/tail pointers.  */
   1381   int allocated = 0;         /* Indicates a new operands string was allocated.*/
   1382   char *operand[MAX_OPERANDS];/* Separating the operands.  */
   1383   int op_num = 0;             /* Current operand number we are parsing.  */
   1384   int bracket_flag = 0;       /* Indicates a bracket '(' was found.  */
   1385   int sq_bracket_flag = 0;    /* Indicates a square bracket '[' was found.  */
   1386 
   1387   /* Preprocess the list of registers, if necessary.  */
   1388   operandS = operandH = operandT = operands;
   1389 
   1390   while (*operandT != '\0')
   1391     {
   1392       if (*operandT == ',' && bracket_flag != 1 && sq_bracket_flag != 1)
   1393 	{
   1394 	  *operandT++ = '\0';
   1395 	  operand[op_num++] = strdup (operandH);
   1396 	  operandH = operandT;
   1397 	  continue;
   1398 	}
   1399 
   1400       if (is_whitespace (*operandT))
   1401 	as_bad (_("Illegal operands (whitespace): `%s'"), ins_parse);
   1402 
   1403       if (*operandT == '(')
   1404 	bracket_flag = 1;
   1405       else if (*operandT == '[')
   1406 	sq_bracket_flag = 1;
   1407 
   1408       if (*operandT == ')')
   1409 	{
   1410 	  if (bracket_flag)
   1411 	    bracket_flag = 0;
   1412 	  else
   1413 	    as_fatal (_("Missing matching brackets : `%s'"), ins_parse);
   1414 	}
   1415       else if (*operandT == ']')
   1416 	{
   1417 	  if (sq_bracket_flag)
   1418 	    sq_bracket_flag = 0;
   1419 	  else
   1420 	    as_fatal (_("Missing matching brackets : `%s'"), ins_parse);
   1421 	}
   1422 
   1423       if (bracket_flag == 1 && *operandT == ')')
   1424 	bracket_flag = 0;
   1425       else if (sq_bracket_flag == 1 && *operandT == ']')
   1426 	sq_bracket_flag = 0;
   1427 
   1428       operandT++;
   1429     }
   1430 
   1431   /* Adding the last operand.  */
   1432   operand[op_num++] = strdup (operandH);
   1433   cr16_ins->nargs = op_num;
   1434 
   1435   /* Verifying correct syntax of operands (all brackets should be closed).  */
   1436   if (bracket_flag || sq_bracket_flag)
   1437     as_fatal (_("Missing matching brackets : `%s'"), ins_parse);
   1438 
   1439   /* Now we parse each operand separately.  */
   1440   for (op_num = 0; op_num < cr16_ins->nargs; op_num++)
   1441     {
   1442       cur_arg_num = op_num;
   1443       parse_operand (operand[op_num], cr16_ins);
   1444       free (operand[op_num]);
   1445     }
   1446 
   1447   if (allocated)
   1448     free (operandS);
   1449 }
   1450 
   1451 /* Get the trap index in dispatch table, given its name.
   1452    This routine is used by assembling the 'excp' instruction.  */
   1453 
   1454 static int
   1455 gettrap (char *s)
   1456 {
   1457   const trap_entry *trap;
   1458 
   1459   for (trap = cr16_traps; trap < (cr16_traps + NUMTRAPS); trap++)
   1460     if (strcasecmp (trap->name, s) == 0)
   1461       return trap->entry;
   1462 
   1463   /* To make compatible with CR16 4.1 tools, the below 3-lines of
   1464    * code added. Refer: Development Tracker item #123 */
   1465   for (trap = cr16_traps; trap < (cr16_traps + NUMTRAPS); trap++)
   1466     if (trap->entry  == (unsigned int) atoi (s))
   1467       return trap->entry;
   1468 
   1469   as_bad (_("Unknown exception: `%s'"), s);
   1470   return 0;
   1471 }
   1472 
   1473 /* Top level module where instruction parsing starts.
   1474    cr16_ins - data structure holds some information.
   1475    operands - holds the operands part of the whole instruction.  */
   1476 
   1477 static void
   1478 parse_insn (ins *insn, char *operands)
   1479 {
   1480   int i;
   1481 
   1482   /* Handle instructions with no operands.  */
   1483   for (i = 0; cr16_no_op_insn[i] != NULL; i++)
   1484   {
   1485     if (streq (cr16_no_op_insn[i], instruction->mnemonic))
   1486     {
   1487       insn->nargs = 0;
   1488       return;
   1489     }
   1490   }
   1491 
   1492   /* Handle 'excp' instructions.  */
   1493   if (IS_INSN_MNEMONIC ("excp"))
   1494     {
   1495       insn->nargs = 1;
   1496       insn->arg[0].type = arg_ic;
   1497       insn->arg[0].constant = gettrap (operands);
   1498       insn->arg[0].X_op = O_constant;
   1499       return;
   1500     }
   1501 
   1502   if (operands != NULL)
   1503     parse_operands (insn, operands);
   1504 }
   1505 
   1506 /* bCC instruction requires special handling.  */
   1507 static char *
   1508 get_b_cc (char * op)
   1509 {
   1510   unsigned int i;
   1511 
   1512   if (op[1] == 0 || (op[2] != 0 && op[3] != 0))
   1513     return NULL;
   1514 
   1515   for (i = 0; i < cr16_num_cc ; i++)
   1516     if (streq (op + 1, cr16_b_cond_tab[i]))
   1517       return (char *) cr16_b_cond_tab[i];
   1518 
   1519    return NULL;
   1520 }
   1521 
   1522 /* bCC instruction requires special handling.  */
   1523 static int
   1524 is_bcc_insn (char * op)
   1525 {
   1526   if (!(streq (op, "bal") || streq (op, "beq0b") || streq (op, "bnq0b")
   1527 	|| streq (op, "beq0w") || streq (op, "bnq0w")))
   1528     if ((op[0] == 'b') && (get_b_cc (op) != NULL))
   1529       return 1;
   1530   return 0;
   1531 }
   1532 
   1533 /* Cinv instruction requires special handling.  */
   1534 
   1535 static void
   1536 check_cinv_options (char * operand)
   1537 {
   1538   char *p = operand;
   1539 
   1540   while (*++p != ']')
   1541     {
   1542       switch (*p)
   1543 	{
   1544 	case ',':
   1545 	case 'i':
   1546 	case 'u':
   1547 	case 'd':
   1548 	  break;
   1549 	default:
   1550 	  if (is_whitespace (*p))
   1551 	    break;
   1552 	  as_bad (_("Illegal `cinv' parameter: `%c'"), *p);
   1553 	}
   1554     }
   1555 }
   1556 
   1557 /* Retrieve the opcode image of a given register pair.
   1558    If the register is illegal for the current instruction,
   1559    issue an error.  */
   1560 
   1561 static int
   1562 getregp_image (reg r)
   1563 {
   1564   const reg_entry *rreg;
   1565   char *reg_name;
   1566 
   1567   /* Check whether the register is in registers table.  */
   1568   if (r < MAX_REG)
   1569     rreg = cr16_regptab + r;
   1570   /* Register not found.  */
   1571   else
   1572     {
   1573       as_bad (_("Unknown register pair: `%d'"), r);
   1574       return 0;
   1575     }
   1576 
   1577   reg_name = rreg->name;
   1578 
   1579   /* Issue a error message when register  pair is illegal.  */
   1580 #define RPAIR_IMAGE_ERR							\
   1581   as_bad (_("Illegal register pair (`%s') in Instruction: `%s'"),	\
   1582 	  reg_name, ins_parse);						\
   1583   break;
   1584 
   1585   switch (rreg->type)
   1586     {
   1587     case CR16_RP_REGTYPE:
   1588       return rreg->image;
   1589     default:
   1590       RPAIR_IMAGE_ERR;
   1591     }
   1592 
   1593   return 0;
   1594 }
   1595 
   1596 /* Retrieve the opcode image of a given index register pair.
   1597    If the register is illegal for the current instruction,
   1598    issue an error.  */
   1599 
   1600 static int
   1601 getidxregp_image (reg r)
   1602 {
   1603   const reg_entry *rreg;
   1604   char *reg_name;
   1605 
   1606   /* Check whether the register is in registers table.  */
   1607   if (r < MAX_REG)
   1608     rreg = cr16_regptab + r;
   1609   /* Register not found.  */
   1610   else
   1611     {
   1612       as_bad (_("Unknown register pair: `%d'"), r);
   1613       return 0;
   1614     }
   1615 
   1616   reg_name = rreg->name;
   1617 
   1618   /* Issue a error message when register  pair is illegal.  */
   1619 #define IDX_RPAIR_IMAGE_ERR						\
   1620   as_bad (_("Illegal index register pair (`%s') in Instruction: `%s'"), \
   1621 	  reg_name, ins_parse);						\
   1622 
   1623   if (rreg->type == CR16_RP_REGTYPE)
   1624     {
   1625       switch (rreg->image)
   1626 	{
   1627 	case 0:  return 0; break;
   1628 	case 2:  return 1; break;
   1629 	case 4:  return 2; break;
   1630 	case 6:  return 3; break;
   1631 	case 8:  return 4; break;
   1632 	case 10: return 5; break;
   1633 	case 3:  return 6; break;
   1634 	case 5:  return 7; break;
   1635 	default:
   1636 	  break;
   1637 	}
   1638     }
   1639 
   1640   IDX_RPAIR_IMAGE_ERR;
   1641   return 0;
   1642 }
   1643 
   1644 /* Retrieve the opcode image of a given processor register.
   1645    If the register is illegal for the current instruction,
   1646    issue an error.  */
   1647 static int
   1648 getprocreg_image (int r)
   1649 {
   1650   const reg_entry *rreg;
   1651   char *reg_name;
   1652 
   1653   /* Check whether the register is in registers table.  */
   1654   if (r >= MAX_REG && r < MAX_PREG)
   1655     rreg = &cr16_pregtab[r - MAX_REG];
   1656   /* Register not found.  */
   1657   else
   1658     {
   1659       as_bad (_("Unknown processor register : `%d'"), r);
   1660       return 0;
   1661     }
   1662 
   1663   reg_name = rreg->name;
   1664 
   1665   /* Issue a error message when register  pair is illegal.  */
   1666 #define PROCREG_IMAGE_ERR						\
   1667   as_bad (_("Illegal processor register (`%s') in Instruction: `%s'"),	\
   1668 	  reg_name, ins_parse);						\
   1669   break;
   1670 
   1671   switch (rreg->type)
   1672     {
   1673     case CR16_P_REGTYPE:
   1674       return rreg->image;
   1675     default:
   1676       PROCREG_IMAGE_ERR;
   1677     }
   1678 
   1679   return 0;
   1680 }
   1681 
   1682 /* Retrieve the opcode image of a given processor register.
   1683    If the register is illegal for the current instruction,
   1684    issue an error.  */
   1685 static int
   1686 getprocregp_image (int r)
   1687 {
   1688   const reg_entry *rreg;
   1689   char *reg_name;
   1690   int pregptab_disp = 0;
   1691 
   1692   /* Check whether the register is in registers table.  */
   1693   if (r >= MAX_REG && r < MAX_PREG)
   1694     {
   1695       r = r - MAX_REG;
   1696       switch (r)
   1697 	{
   1698 	case 4: pregptab_disp = 1;  break;
   1699 	case 6: pregptab_disp = 2;  break;
   1700 	case 8:
   1701 	case 9:
   1702 	case 10:
   1703 	  pregptab_disp = 3;  break;
   1704 	case 12:
   1705 	  pregptab_disp = 4;  break;
   1706 	case 14:
   1707 	  pregptab_disp = 5;  break;
   1708 	default: break;
   1709 	}
   1710       rreg = &cr16_pregptab[r - pregptab_disp];
   1711     }
   1712   /* Register not found.  */
   1713   else
   1714     {
   1715       as_bad (_("Unknown processor register (32 bit) : `%d'"), r);
   1716       return 0;
   1717     }
   1718 
   1719   reg_name = rreg->name;
   1720 
   1721   /* Issue a error message when register  pair is illegal.  */
   1722 #define PROCREGP_IMAGE_ERR						\
   1723   as_bad (_("Illegal 32 bit - processor register (`%s') in Instruction: `%s'"), \
   1724 	  reg_name, ins_parse);						\
   1725   break;
   1726 
   1727   switch (rreg->type)
   1728     {
   1729     case CR16_P_REGTYPE:
   1730       return rreg->image;
   1731     default:
   1732       PROCREGP_IMAGE_ERR;
   1733     }
   1734 
   1735   return 0;
   1736 }
   1737 
   1738 /* Routine used to represent integer X using NBITS bits.  */
   1739 
   1740 static long
   1741 getconstant (long x, int nbits)
   1742 {
   1743   if ((unsigned) nbits >= sizeof (x) * CHAR_BIT)
   1744     return x;
   1745   return x & ((1UL << nbits) - 1);
   1746 }
   1747 
   1748 /* Print a constant value to 'output_opcode':
   1749    ARG holds the operand's type and value.
   1750    SHIFT represents the location of the operand to be print into.
   1751    NBITS determines the size (in bits) of the constant.  */
   1752 
   1753 static void
   1754 print_constant (int nbits, int shift, argument *arg)
   1755 {
   1756   unsigned long mask = 0;
   1757   unsigned long constant = getconstant (arg->constant, nbits);
   1758 
   1759   switch (nbits)
   1760     {
   1761     case 32:
   1762     case 28:
   1763       /* mask the upper part of the constant, that is, the bits
   1764 	 going to the lowest byte of output_opcode[0].
   1765 	 The upper part of output_opcode[1] is always filled,
   1766 	 therefore it is always masked with 0xFFFF.  */
   1767       mask = (1 << (nbits - 16)) - 1;
   1768       /* Divide the constant between two consecutive words :
   1769 	 0        1         2         3
   1770 	 +---------+---------+---------+---------+
   1771 	 |         | X X X X | x X x X |         |
   1772 	 +---------+---------+---------+---------+
   1773 	 output_opcode[0]    output_opcode[1]     */
   1774 
   1775       CR16_PRINT (0, (constant >> WORD_SHIFT) & mask, 0);
   1776       CR16_PRINT (1, constant & 0xFFFF, WORD_SHIFT);
   1777       break;
   1778 
   1779     case 21:
   1780       if ((nbits == 21) && (IS_INSN_TYPE (LD_STOR_INS)))
   1781 	nbits = 20;
   1782       /* Fall through.  */
   1783     case 24:
   1784     case 22:
   1785     case 20:
   1786       /* mask the upper part of the constant, that is, the bits
   1787 	 going to the lowest byte of output_opcode[0].
   1788 	 The upper part of output_opcode[1] is always filled,
   1789 	 therefore it is always masked with 0xFFFF.  */
   1790       mask = (1 << (nbits - 16)) - 1;
   1791       /* Divide the constant between two consecutive words :
   1792 	 0        1         2          3
   1793 	 +---------+---------+---------+---------+
   1794 	 |         | X X X X | - X - X |         |
   1795 	 +---------+---------+---------+---------+
   1796 	 output_opcode[0]    output_opcode[1]     */
   1797 
   1798       if (instruction->size > 2 && shift == WORD_SHIFT)
   1799 	{
   1800 	  if (arg->type == arg_idxrp)
   1801 	    {
   1802 	      CR16_PRINT (0, ((constant >> WORD_SHIFT) & mask) << 8, 0);
   1803 	      CR16_PRINT (1, constant & 0xFFFF, WORD_SHIFT);
   1804 	    }
   1805 	  else
   1806 	    {
   1807 	      CR16_PRINT (0,
   1808 			  ((((constant >> WORD_SHIFT) & mask & 0xf) << 8)
   1809 			   | (((constant >> WORD_SHIFT) & mask & 0xf0) >> 4)),
   1810 			  0);
   1811 	      CR16_PRINT (1, constant & 0xFFFF, WORD_SHIFT);
   1812 	    }
   1813 	}
   1814       else
   1815 	CR16_PRINT (0, constant, shift);
   1816       break;
   1817 
   1818     case 14:
   1819       if (arg->type == arg_idxrp)
   1820 	{
   1821 	  if (instruction->size == 2)
   1822 	    {
   1823 	      CR16_PRINT (0, (constant)      & 0xf, shift);      /* 0-3 bits.  */
   1824 	      CR16_PRINT (0, (constant >> 4) & 0x3, shift + 20); /* 4-5 bits.  */
   1825 	      CR16_PRINT (0, (constant >> 6) & 0x3, shift + 14); /* 6-7 bits.  */
   1826 	      CR16_PRINT (0, (constant >> 8) & 0x3f, shift + 8); /* 8-13 bits.  */
   1827 	    }
   1828 	  else
   1829 	    CR16_PRINT (0, constant, shift);
   1830 	}
   1831       break;
   1832 
   1833     case 16:
   1834     case 12:
   1835       /* When instruction size is 3 and 'shift' is 16, a 16-bit constant is
   1836 	 always filling the upper part of output_opcode[1]. If we mistakenly
   1837 	 write it to output_opcode[0], the constant prefix (that is, 'match')
   1838 	 will be overridden.
   1839 	 0        1         2         3
   1840 	 +---------+---------+---------+---------+
   1841 	 | 'match' |         | X X X X |         |
   1842 	 +---------+---------+---------+---------+
   1843 	 output_opcode[0]    output_opcode[1]     */
   1844 
   1845       if (instruction->size > 2 && shift == WORD_SHIFT)
   1846 	CR16_PRINT (1, constant, WORD_SHIFT);
   1847       else
   1848 	CR16_PRINT (0, constant, shift);
   1849       break;
   1850 
   1851     case 8:
   1852       CR16_PRINT (0, (constant / 2) & 0xf, shift);
   1853       CR16_PRINT (0, (constant / 2) >> 4, shift + 8);
   1854       break;
   1855 
   1856     default:
   1857       CR16_PRINT (0, constant, shift);
   1858       break;
   1859     }
   1860 }
   1861 
   1862 /* Print an operand to 'output_opcode', which later on will be
   1863    printed to the object file:
   1864    ARG holds the operand's type, size and value.
   1865    SHIFT represents the printing location of operand.
   1866    NBITS determines the size (in bits) of a constant operand.  */
   1867 
   1868 static void
   1869 print_operand (int nbits, int shift, argument *arg)
   1870 {
   1871   switch (arg->type)
   1872     {
   1873     case arg_cc:
   1874       CR16_PRINT (0, arg->cc, shift);
   1875       break;
   1876 
   1877     case arg_r:
   1878       CR16_PRINT (0, getreg_image (arg->r), shift);
   1879       break;
   1880 
   1881     case arg_rp:
   1882       CR16_PRINT (0, getregp_image (arg->rp), shift);
   1883       break;
   1884 
   1885     case arg_pr:
   1886       CR16_PRINT (0, getprocreg_image (arg->pr), shift);
   1887       break;
   1888 
   1889     case arg_prp:
   1890       CR16_PRINT (0, getprocregp_image (arg->prp), shift);
   1891       break;
   1892 
   1893     case arg_idxrp:
   1894       /*    16      12      8    6      0
   1895 	    +-----------------------------+
   1896 	    | r_index | disp  | rp_base   |
   1897 	    +-----------------------------+          */
   1898 
   1899       if (instruction->size == 3)
   1900 	{
   1901 	  CR16_PRINT (0, getidxregp_image (arg->rp), 0);
   1902 	  CR16_PRINT (0, getreg_image (arg->i_r) & 1, 3);
   1903 	}
   1904       else
   1905 	{
   1906 	  CR16_PRINT (0, getidxregp_image (arg->rp), 16);
   1907 	  CR16_PRINT (0, getreg_image (arg->i_r) & 1, 19);
   1908 	}
   1909       print_constant (nbits, shift, arg);
   1910       break;
   1911 
   1912     case arg_idxr:
   1913       CR16_PRINT (0, getreg_image (arg->i_r) & 1,
   1914 		  (IS_INSN_TYPE (CSTBIT_INS)
   1915 		   && instruction->mnemonic[4] == 'b') ? 23 : 24);
   1916       print_constant (nbits, shift, arg);
   1917       break;
   1918 
   1919     case arg_ic:
   1920     case arg_c:
   1921       print_constant (nbits, shift, arg);
   1922       break;
   1923 
   1924     case arg_rbase:
   1925       CR16_PRINT (0, getreg_image (arg->r), shift);
   1926       break;
   1927 
   1928     case arg_cr:
   1929       print_constant (nbits, shift, arg);
   1930       /* Add the register argument to the output_opcode.  */
   1931       CR16_PRINT (0, getreg_image (arg->r), shift - 16);
   1932       break;
   1933 
   1934     case arg_crp:
   1935       print_constant (nbits, shift, arg);
   1936       if ((IS_INSN_TYPE (LD_STOR_INS) || IS_INSN_TYPE (CSTBIT_INS))
   1937 	  && instruction->size == 1)
   1938 	CR16_PRINT (0, getregp_image (arg->rp), 16);
   1939       else if (instruction->size > 1)
   1940 	CR16_PRINT (0, getregp_image (arg->rp), (shift + 16) & 31);
   1941       else
   1942 	CR16_PRINT (0, getregp_image (arg->rp), shift);
   1943       break;
   1944 
   1945     default:
   1946       break;
   1947     }
   1948 }
   1949 
   1950 /* Retrieve the number of operands for the current assembled instruction.  */
   1951 
   1952 static int
   1953 get_number_of_operands (void)
   1954 {
   1955   int i;
   1956 
   1957   for (i = 0; instruction->operands[i].op_type && i < MAX_OPERANDS; i++)
   1958     ;
   1959   return i;
   1960 }
   1961 
   1962 /* Verify that the number NUM can be represented in BITS bits (that is,
   1963    within its permitted range), based on the instruction's FLAGS.
   1964    If UPDATE is nonzero, update the value of NUM if necessary.
   1965    Return OP_LEGAL upon success, actual error type upon failure.  */
   1966 
   1967 static op_err
   1968 check_range (long *num, int bits, int unsigned flags, int update)
   1969 {
   1970   int32_t min, max;
   1971   op_err retval = OP_LEGAL;
   1972   int32_t value = *num;
   1973 
   1974   /* Verify operand value is even.  */
   1975   if (flags & OP_EVEN)
   1976     {
   1977       if (value % 2)
   1978 	return OP_NOT_EVEN;
   1979     }
   1980 
   1981   if (flags & OP_DEC)
   1982     {
   1983       value -= 1;
   1984       if (update)
   1985 	*num = value;
   1986     }
   1987 
   1988   if (flags & OP_SHIFT)
   1989     {
   1990       value >>= 1;
   1991       if (update)
   1992 	*num = value;
   1993     }
   1994   else if (flags & OP_SHIFT_DEC)
   1995     {
   1996       value = (value >> 1) - 1;
   1997       if (update)
   1998 	*num = value;
   1999     }
   2000 
   2001   if (flags & OP_ABS20)
   2002     {
   2003       if (value > 0xEFFFF)
   2004 	return OP_OUT_OF_RANGE;
   2005     }
   2006 
   2007   if (flags & OP_ESC)
   2008     {
   2009       if (value == 0xB || value == 0x9)
   2010 	return OP_OUT_OF_RANGE;
   2011       else if (value == -1)
   2012 	{
   2013 	  if (update)
   2014 	    *num = 9;
   2015 	  return retval;
   2016 	}
   2017     }
   2018 
   2019   if (flags & OP_ESC1)
   2020     {
   2021       if (value > 13)
   2022 	return OP_OUT_OF_RANGE;
   2023     }
   2024 
   2025   if (bits == 0)
   2026     {
   2027       if (value != 0)
   2028 	retval = OP_OUT_OF_RANGE;
   2029       return retval;
   2030     }
   2031 
   2032   if (flags & OP_SIGNED)
   2033     {
   2034       max = (1U << (bits - 1)) - 1;
   2035       min = - (1U << (bits - 1));
   2036       if (value > max || value < min)
   2037 	retval = OP_OUT_OF_RANGE;
   2038     }
   2039   else if (flags & OP_UNSIGNED)
   2040     {
   2041       max = (1U << (bits - 1) << 1) - 1;
   2042       if ((uint32_t) value > (uint32_t) max)
   2043 	retval = OP_OUT_OF_RANGE;
   2044     }
   2045   else if (flags & OP_NEG)
   2046     {
   2047       min = - ((1U << (bits - 1)) - 1);
   2048       if (value < min)
   2049 	retval = OP_OUT_OF_RANGE;
   2050     }
   2051   return retval;
   2052 }
   2053 
   2054 /* Bunch of error checking.
   2055    The checks are made after a matching instruction was found.  */
   2056 
   2057 static void
   2058 warn_if_needed (ins *insn)
   2059 {
   2060   /* If the post-increment address mode is used and the load/store
   2061      source register is the same as rbase, the result of the
   2062      instruction is undefined.  */
   2063   if (IS_INSN_TYPE (LD_STOR_INS_INC))
   2064     {
   2065       /* Enough to verify that one of the arguments is a simple reg.  */
   2066       if ((insn->arg[0].type == arg_r) || (insn->arg[1].type == arg_r))
   2067 	if (insn->arg[0].r == insn->arg[1].r)
   2068 	  as_bad (_("Same src/dest register is used (`r%d'), "
   2069 		    "result is undefined"), insn->arg[0].r);
   2070     }
   2071 
   2072   if (IS_INSN_MNEMONIC ("pop")
   2073       || IS_INSN_MNEMONIC ("push")
   2074       || IS_INSN_MNEMONIC ("popret"))
   2075     {
   2076       unsigned int count = insn->arg[0].constant, reg_val;
   2077 
   2078       /* Check if count operand caused to save/retrieve the RA twice
   2079 	 to generate warning message.  */
   2080       if (insn->nargs > 2)
   2081 	{
   2082 	  reg_val = getreg_image (insn->arg[1].r);
   2083 
   2084 	  if (   ((reg_val == 9) &&  (count > 7))
   2085 		 || ((reg_val == 10) && (count > 6))
   2086 		 || ((reg_val == 11) && (count > 5))
   2087 		 || ((reg_val == 12) && (count > 4))
   2088 		 || ((reg_val == 13) && (count > 2))
   2089 		 || ((reg_val == 14) && (count > 0)))
   2090 	    as_warn (_("RA register is saved twice."));
   2091 
   2092 	  /* Check if the third operand is "RA" or "ra" */
   2093 	  if (!(((insn->arg[2].r) == ra) || ((insn->arg[2].r) == RA)))
   2094 	    as_bad (_("`%s' Illegal use of registers."), ins_parse);
   2095 	}
   2096 
   2097       if (insn->nargs > 1)
   2098 	{
   2099 	  reg_val = getreg_image (insn->arg[1].r);
   2100 
   2101 	  /* If register is a register pair ie r12/r13/r14 in operand1, then
   2102 	     the count constant should be validated.  */
   2103 	  if (((reg_val == 11) && (count > 7))
   2104 	      || ((reg_val == 12) && (count > 6))
   2105 	      || ((reg_val == 13) && (count > 4))
   2106 	      || ((reg_val == 14) && (count > 2))
   2107 	      || ((reg_val == 15) && (count > 0)))
   2108 	    as_bad (_("`%s' Illegal count-register combination."), ins_parse);
   2109 	}
   2110       else
   2111 	{
   2112 	  /* Check if the operand is "RA" or "ra" */
   2113 	  if (!(((insn->arg[0].r) == ra) || ((insn->arg[0].r) == RA)))
   2114 	    as_bad (_("`%s' Illegal use of register."), ins_parse);
   2115 	}
   2116     }
   2117 
   2118   /* Some instruction assume the stack pointer as rptr operand.
   2119      Issue an error when the register to be loaded is also SP.  */
   2120   if (instruction->flags & NO_SP)
   2121     {
   2122       if (getreg_image (insn->arg[1].r) == getreg_image (sp))
   2123 	as_bad (_("`%s' has undefined result"), ins_parse);
   2124     }
   2125 
   2126   /* If the rptr register is specified as one of the registers to be loaded,
   2127      the final contents of rptr are undefined. Thus, we issue an error.  */
   2128   if (instruction->flags & NO_RPTR)
   2129     {
   2130       if ((1 << getreg_image (insn->arg[0].r)) & insn->arg[1].constant)
   2131 	as_bad (_("Same src/dest register is used (`r%d'),result is undefined"),
   2132 		getreg_image (insn->arg[0].r));
   2133     }
   2134 }
   2135 
   2136 /* In some cases, we need to adjust the instruction pointer although a
   2137    match was already found. Here, we gather all these cases.
   2138    Returns 1 if instruction pointer was adjusted, otherwise 0.  */
   2139 
   2140 static int
   2141 adjust_if_needed (ins *insn ATTRIBUTE_UNUSED)
   2142 {
   2143   int ret_value = 0;
   2144 
   2145   if ((IS_INSN_TYPE (CSTBIT_INS)) || (IS_INSN_TYPE (LD_STOR_INS)))
   2146     {
   2147       if ((instruction->operands[0].op_type == abs24)
   2148 	  && ((insn->arg[0].constant) > 0xF00000))
   2149 	{
   2150 	  insn->arg[0].constant &= 0xFFFFF;
   2151 	  instruction--;
   2152 	  ret_value = 1;
   2153 	}
   2154     }
   2155 
   2156   return ret_value;
   2157 }
   2158 
   2159 /* Assemble a single instruction:
   2160    INSN is already parsed (that is, all operand values and types are set).
   2161    For instruction to be assembled, we need to find an appropriate template in
   2162    the instruction table, meeting the following conditions:
   2163     1: Has the same number of operands.
   2164     2: Has the same operand types.
   2165     3: Each operand size is sufficient to represent the instruction's values.
   2166    Returns 1 upon success, 0 upon failure.  */
   2167 
   2168 static int
   2169 assemble_insn (const char *mnemonic, ins *insn)
   2170 {
   2171   /* Type of each operand in the current template.  */
   2172   argtype cur_type[MAX_OPERANDS];
   2173   /* Size (in bits) of each operand in the current template.  */
   2174   unsigned int cur_size[MAX_OPERANDS];
   2175   /* Flags of each operand in the current template.  */
   2176   unsigned int cur_flags[MAX_OPERANDS];
   2177   /* Instruction type to match.  */
   2178   unsigned int ins_type;
   2179   /* Boolean flag to mark whether a match was found.  */
   2180   int match = 0;
   2181   int i;
   2182   /* Nonzero if an instruction with same number of operands was found.  */
   2183   int found_same_number_of_operands = 0;
   2184   /* Nonzero if an instruction with same argument types was found.  */
   2185   int found_same_argument_types = 0;
   2186   /* Nonzero if a constant was found within the required range.  */
   2187   int found_const_within_range  = 0;
   2188   /* Argument number of an operand with invalid type.  */
   2189   int invalid_optype = -1;
   2190   /* Argument number of an operand with invalid constant value.  */
   2191   int invalid_const  = -1;
   2192   /* Operand error (used for issuing various constant error messages).  */
   2193   op_err op_error, const_err = OP_LEGAL;
   2194 
   2195   /* Retrieve data (based on FUNC) for each operand of a given instruction.  */
   2196 #define GET_CURRENT_DATA(FUNC, ARRAY)			\
   2197   for (i = 0; i < insn->nargs; i++)			\
   2198     ARRAY[i] = FUNC (instruction->operands[i].op_type)
   2199 
   2200 #define GET_CURRENT_TYPE    GET_CURRENT_DATA (get_optype, cur_type)
   2201 #define GET_CURRENT_SIZE    GET_CURRENT_DATA (get_opbits, cur_size)
   2202 #define GET_CURRENT_FLAGS   GET_CURRENT_DATA (get_opflags, cur_flags)
   2203 
   2204   /* Instruction has no operands -> only copy the constant opcode.   */
   2205   if (insn->nargs == 0)
   2206     {
   2207       output_opcode[0] = BIN (instruction->match, instruction->match_bits);
   2208       return 1;
   2209     }
   2210 
   2211   /* In some case, same mnemonic can appear with different instruction types.
   2212      For example, 'storb' is supported with 3 different types :
   2213      LD_STOR_INS, LD_STOR_INS_INC, STOR_IMM_INS.
   2214      We assume that when reaching this point, the instruction type was
   2215      pre-determined. We need to make sure that the type stays the same
   2216      during a search for matching instruction.  */
   2217   ins_type = CR16_INS_TYPE (instruction->flags);
   2218 
   2219   while (/* Check that match is still not found.  */
   2220 	 match != 1
   2221 	 /* Check we didn't get to end of table.  */
   2222 	 && instruction->mnemonic != NULL
   2223 	 /* Check that the actual mnemonic is still available.  */
   2224 	 && IS_INSN_MNEMONIC (mnemonic)
   2225 	 /* Check that the instruction type wasn't changed.  */
   2226 	 && IS_INSN_TYPE (ins_type))
   2227     {
   2228       /* Check whether number of arguments is legal.  */
   2229       if (get_number_of_operands () != insn->nargs)
   2230 	goto next_insn;
   2231       found_same_number_of_operands = 1;
   2232 
   2233       /* Initialize arrays with data of each operand in current template.  */
   2234       GET_CURRENT_TYPE;
   2235       GET_CURRENT_SIZE;
   2236       GET_CURRENT_FLAGS;
   2237 
   2238       /* Check for type compatibility.  */
   2239       for (i = 0; i < insn->nargs; i++)
   2240 	{
   2241 	  if (cur_type[i] != insn->arg[i].type)
   2242 	    {
   2243 	      if (invalid_optype == -1)
   2244 		invalid_optype = i + 1;
   2245 	      goto next_insn;
   2246 	    }
   2247 	}
   2248       found_same_argument_types = 1;
   2249 
   2250       for (i = 0; i < insn->nargs; i++)
   2251 	{
   2252 	  /* If 'bal' instruction size is '2' and reg operand is not 'ra'
   2253 	     then goto next instruction.  */
   2254 	  if (IS_INSN_MNEMONIC ("bal") && (i == 0)
   2255 	      && (instruction->size == 2) && (insn->arg[i].rp != 14))
   2256 	    goto next_insn;
   2257 
   2258 	  /* If 'storb' instruction with 'sp' reg and 16-bit disp of
   2259 	   * reg-pair, leads to undefined trap, so this should use
   2260 	   * 20-bit disp of reg-pair.  */
   2261 	  if (IS_INSN_MNEMONIC ("storb") && (instruction->size == 2)
   2262 	      && (insn->arg[i].r == 15) && (insn->arg[i + 1].type == arg_crp))
   2263 	    goto next_insn;
   2264 
   2265 	  /* Only check range - don't update the constant's value, since the
   2266 	     current instruction may not be the last we try to match.
   2267 	     The constant's value will be updated later, right before printing
   2268 	     it to the object file.  */
   2269 	  if ((insn->arg[i].X_op == O_constant)
   2270 	      && (op_error = check_range (&insn->arg[i].constant, cur_size[i],
   2271 					  cur_flags[i], 0)))
   2272 	    {
   2273 	      if (invalid_const == -1)
   2274 		{
   2275 		  invalid_const = i + 1;
   2276 		  const_err = op_error;
   2277 		}
   2278 	      goto next_insn;
   2279 	    }
   2280 	  /* For symbols, we make sure the relocation size (which was already
   2281 	     determined) is sufficient.  */
   2282 	  else if ((insn->arg[i].X_op == O_symbol)
   2283 		   && ((bfd_reloc_type_lookup (stdoutput, insn->rtype))->bitsize
   2284 		       > cur_size[i]))
   2285 	    goto next_insn;
   2286 	}
   2287       found_const_within_range = 1;
   2288 
   2289       /* If we got till here -> Full match is found.  */
   2290       match = 1;
   2291       break;
   2292 
   2293       /* Try again with next instruction.  */
   2294     next_insn:
   2295       instruction++;
   2296     }
   2297 
   2298   if (!match)
   2299     {
   2300       /* We haven't found a match - instruction can't be assembled.  */
   2301       if (!found_same_number_of_operands)
   2302 	as_bad (_("Incorrect number of operands"));
   2303       else if (!found_same_argument_types)
   2304 	as_bad (_("Illegal type of operand (arg %d)"), invalid_optype);
   2305       else if (!found_const_within_range)
   2306 	{
   2307 	  switch (const_err)
   2308 	    {
   2309 	    case OP_OUT_OF_RANGE:
   2310 	      as_bad (_("Operand out of range (arg %d)"), invalid_const);
   2311 	      break;
   2312 	    case OP_NOT_EVEN:
   2313 	      as_bad (_("Operand has odd displacement (arg %d)"), invalid_const);
   2314 	      break;
   2315 	    default:
   2316 	      as_bad (_("Illegal operand (arg %d)"), invalid_const);
   2317 	      break;
   2318 	    }
   2319 	}
   2320 
   2321       return 0;
   2322     }
   2323   else
   2324     /* Full match - print the encoding to output file.  */
   2325     {
   2326       /* Make further checking (such that couldn't be made earlier).
   2327 	 Warn the user if necessary.  */
   2328       warn_if_needed (insn);
   2329 
   2330       /* Check whether we need to adjust the instruction pointer.  */
   2331       if (adjust_if_needed (insn))
   2332 	/* If instruction pointer was adjusted, we need to update
   2333 	   the size of the current template operands.  */
   2334 	GET_CURRENT_SIZE;
   2335 
   2336       for (i = 0; i < insn->nargs; i++)
   2337 	{
   2338 	  int j = instruction->flags & REVERSE_MATCH ?
   2339 	    i == 0 ? 1 :
   2340 	    i == 1 ? 0 : i :
   2341 	    i;
   2342 
   2343 	  /* This time, update constant value before printing it.  */
   2344 	  if ((insn->arg[j].X_op == O_constant)
   2345 	      && (check_range (&insn->arg[j].constant, cur_size[j],
   2346 			       cur_flags[j], 1) != OP_LEGAL))
   2347 	    as_fatal (_("Illegal operand (arg %d)"), j+1);
   2348 	}
   2349 
   2350       /* First, copy the instruction's opcode.  */
   2351       output_opcode[0] = BIN (instruction->match, instruction->match_bits);
   2352 
   2353       for (i = 0; i < insn->nargs; i++)
   2354 	{
   2355 	  /* For BAL (ra),disp17 instruction only. And also set the
   2356 	     DISP24a relocation type.  */
   2357 	  if (IS_INSN_MNEMONIC ("bal") && (instruction->size == 2) && i == 0)
   2358 	    {
   2359 	      insn->rtype = BFD_RELOC_CR16_DISP24a;
   2360 	      continue;
   2361 	    }
   2362 	  cur_arg_num = i;
   2363 	  print_operand (cur_size[i], instruction->operands[i].shift,
   2364 			 &insn->arg[i]);
   2365 	}
   2366     }
   2367 
   2368   return 1;
   2369 }
   2370 
   2371 /* Print the instruction.
   2372    Handle also cases where the instruction is relaxable/relocatable.  */
   2373 
   2374 static void
   2375 print_insn (ins *insn)
   2376 {
   2377   unsigned int i, j, insn_size;
   2378   char *this_frag;
   2379   unsigned short words[4];
   2380   int addr_mod;
   2381 
   2382   /* Arrange the insn encodings in a WORD size array.  */
   2383   for (i = 0, j = 0; i < 2; i++)
   2384     {
   2385       words[j++] = (output_opcode[i] >> 16) & 0xFFFF;
   2386       words[j++] = output_opcode[i] & 0xFFFF;
   2387     }
   2388 
   2389   /* Handle relocation.  */
   2390   if ((instruction->flags & RELAXABLE) && relocatable)
   2391     {
   2392       int relax_subtype;
   2393       /* Write the maximal instruction size supported.  */
   2394       insn_size = INSN_MAX_SIZE;
   2395 
   2396       if (IS_INSN_TYPE (BRANCH_INS))
   2397 	{
   2398 	  switch (insn->rtype)
   2399 	    {
   2400 	    case BFD_RELOC_CR16_DISP24:
   2401 	      relax_subtype = 2;
   2402 	      break;
   2403 	    case BFD_RELOC_CR16_DISP16:
   2404 	      relax_subtype = 1;
   2405 	      break;
   2406 	    default:
   2407 	      relax_subtype = 0;
   2408 	      break;
   2409 	    }
   2410 	}
   2411       else
   2412 	abort ();
   2413 
   2414       this_frag = frag_var (rs_machine_dependent, insn_size *2,
   2415 			    4, relax_subtype,
   2416 			    insn->exp.X_add_symbol,
   2417 			    0,
   2418 			    0);
   2419     }
   2420   else
   2421     {
   2422       insn_size = instruction->size;
   2423       this_frag = frag_more (insn_size * 2);
   2424 
   2425       if ((relocatable) && (insn->rtype != BFD_RELOC_NONE))
   2426 	{
   2427 	  reloc_howto_type *reloc_howto;
   2428 	  int size;
   2429 
   2430 	  reloc_howto = bfd_reloc_type_lookup (stdoutput, insn->rtype);
   2431 
   2432 	  if (!reloc_howto)
   2433 	    abort ();
   2434 
   2435 	  size = bfd_get_reloc_size (reloc_howto);
   2436 
   2437 	  if (size < 1 || size > 4)
   2438 	    abort ();
   2439 
   2440 	  fix_new_exp (frag_now, this_frag - frag_now->fr_literal,
   2441 		       size, &insn->exp, reloc_howto->pc_relative,
   2442 		       insn->rtype);
   2443 	}
   2444     }
   2445 
   2446   /* Verify a 2-byte code alignment.  */
   2447   addr_mod = frag_now_fix () & 1;
   2448   if (frag_now->has_code && frag_now->insn_addr != addr_mod)
   2449     as_bad (_("instruction address is not a multiple of 2"));
   2450   frag_now->insn_addr = addr_mod;
   2451   frag_now->has_code = 1;
   2452 
   2453   /* Write the instruction encoding to frag.  */
   2454   for (i = 0; i < insn_size; i++)
   2455     {
   2456       md_number_to_chars (this_frag, words[i], 2);
   2457       this_frag += 2;
   2458     }
   2459 }
   2460 
   2461 /* Actually assemble an instruction.  */
   2462 
   2463 static void
   2464 cr16_assemble (const char *op, char *param)
   2465 {
   2466   ins cr16_ins;
   2467 
   2468   /* Find the instruction.  */
   2469   instruction = str_hash_find (cr16_inst_hash, op);
   2470   if (instruction == NULL)
   2471     {
   2472       as_bad (_("Unknown opcode: `%s'"), op);
   2473       return;
   2474     }
   2475 
   2476   /* Tie dwarf2 debug info to the address at the start of the insn.  */
   2477   dwarf2_emit_insn (0);
   2478 
   2479   /* Parse the instruction's operands.  */
   2480   parse_insn (&cr16_ins, param);
   2481 
   2482   /* Assemble the instruction - return upon failure.  */
   2483   if (assemble_insn (op, &cr16_ins) == 0)
   2484     return;
   2485 
   2486   /* Print the instruction.  */
   2487   print_insn (&cr16_ins);
   2488 }
   2489 
   2490 /* This is the guts of the machine-dependent assembler.  OP points to a
   2491    machine dependent instruction.  This function is supposed to emit
   2492    the frags/bytes it assembles to.  */
   2493 
   2494 void
   2495 md_assemble (char *op)
   2496 {
   2497   ins cr16_ins;
   2498   char *param, param1[32];
   2499 
   2500   /* Reset global variables for a new instruction.  */
   2501   reset_vars (op);
   2502 
   2503   /* Strip the mnemonic.  */
   2504   for (param = op; *param != 0 && !is_whitespace (*param); param++)
   2505     ;
   2506   *param++ = '\0';
   2507 
   2508   /* bCC instructions and adjust the mnemonic by adding extra white spaces.  */
   2509   if (is_bcc_insn (op))
   2510     {
   2511       strcpy (param1, get_b_cc (op));
   2512       strcat (param1,",");
   2513       strcat (param1, param);
   2514       param = param1;
   2515       cr16_assemble ("b", param);
   2516       return;
   2517     }
   2518 
   2519   /* Checking the cinv options and adjust the mnemonic by removing the
   2520      extra white spaces.  */
   2521   if (streq ("cinv", op))
   2522     {
   2523       /* Validate the cinv options.  */
   2524       unsigned int op_len, param_len;
   2525       check_cinv_options (param);
   2526       op_len = strlen (op);
   2527       param_len = strlen (param) + 1;
   2528       memmove (op + op_len, param, param_len);
   2529     }
   2530 
   2531   /* MAPPING - SHIFT INSN, if imm4/imm16 positive values
   2532      lsh[b/w] imm4/imm6, reg ==> ashu[b/w] imm4/imm16, reg
   2533      as CR16 core doesn't support lsh[b/w] right shift operations.  */
   2534   if ((streq ("lshb", op) || streq ("lshw", op) || streq ("lshd", op))
   2535       && (param [0] == '$'))
   2536     {
   2537       strcpy (param1, param);
   2538       /* Find the instruction.  */
   2539       instruction = str_hash_find (cr16_inst_hash, op);
   2540       parse_operands (&cr16_ins, param1);
   2541       if (((&cr16_ins)->arg[0].type == arg_ic)
   2542 	  && ((&cr16_ins)->arg[0].constant >= 0))
   2543 	{
   2544 	  if (streq ("lshb", op))
   2545 	    cr16_assemble ("ashub", param);
   2546 	  else if (streq ("lshd", op))
   2547 	    cr16_assemble ("ashud", param);
   2548 	  else
   2549 	    cr16_assemble ("ashuw", param);
   2550 	  return;
   2551 	}
   2552     }
   2553 
   2554   cr16_assemble (op, param);
   2555 }
   2556