Home | History | Annotate | Download | only in config
      1 /* Altera Nios II assembler.
      2    Copyright (C) 2012-2014 Free Software Foundation, Inc.
      3    Contributed by Nigel Gray (ngray (at) altera.com).
      4    Contributed by Mentor Graphics, Inc.
      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 Free
     20    Software Foundation, 51 Franklin Street - Fifth Floor, Boston, MA
     21    02110-1301, USA.  */
     22 
     23 #include "as.h"
     24 #include "opcode/nios2.h"
     25 #include "elf/nios2.h"
     26 #include "tc-nios2.h"
     27 #include "bfd.h"
     28 #include "dwarf2dbg.h"
     29 #include "subsegs.h"
     30 #include "safe-ctype.h"
     31 #include "dw2gencfi.h"
     32 
     33 #ifndef OBJ_ELF
     34 /* We are not supporting any other target so we throw a compile time error.  */
     35 OBJ_ELF not defined
     36 #endif
     37 
     38 /* We can choose our endianness at run-time, regardless of configuration.  */
     39 extern int target_big_endian;
     40 
     41 /* This array holds the chars that always start a comment.  If the
     42    pre-processor is disabled, these aren't very useful.  */
     43 const char comment_chars[] = "#";
     44 
     45 /* This array holds the chars that only start a comment at the beginning of
     46    a line.  If the line seems to have the form '# 123 filename'
     47    .line and .file directives will appear in the pre-processed output.  */
     48 /* Note that input_file.c hand checks for '#' at the beginning of the
     49    first line of the input file.  This is because the compiler outputs
     50    #NO_APP at the beginning of its output.  */
     51 /* Also note that C style comments are always supported.  */
     52 const char line_comment_chars[] = "#";
     53 
     54 /* This array holds machine specific line separator characters.  */
     55 const char line_separator_chars[] = ";";
     56 
     57 /* Chars that can be used to separate mant from exp in floating point nums.  */
     58 const char EXP_CHARS[] = "eE";
     59 
     60 /* Chars that mean this number is a floating point constant.  */
     61 /* As in 0f12.456 */
     62 /* or	 0d1.2345e12 */
     63 const char FLT_CHARS[] = "rRsSfFdDxXpP";
     64 
     65 /* Also be aware that MAXIMUM_NUMBER_OF_CHARS_FOR_FLOAT may have to be
     66    changed in read.c.  Ideally it shouldn't have to know about it at all,
     67    but nothing is ideal around here.  */
     68 
     69 /* Machine-dependent command-line options.  */
     70 
     71 const char *md_shortopts = "r";
     72 
     73 struct option md_longopts[] = {
     74 #define OPTION_RELAX_ALL (OPTION_MD_BASE + 0)
     75   {"relax-all", no_argument, NULL, OPTION_RELAX_ALL},
     76 #define OPTION_NORELAX (OPTION_MD_BASE + 1)
     77   {"no-relax", no_argument, NULL, OPTION_NORELAX},
     78 #define OPTION_RELAX_SECTION (OPTION_MD_BASE + 2)
     79   {"relax-section", no_argument, NULL, OPTION_RELAX_SECTION},
     80 #define OPTION_EB (OPTION_MD_BASE + 3)
     81   {"EB", no_argument, NULL, OPTION_EB},
     82 #define OPTION_EL (OPTION_MD_BASE + 4)
     83   {"EL", no_argument, NULL, OPTION_EL}
     84 };
     85 
     86 size_t md_longopts_size = sizeof (md_longopts);
     87 
     88 /* The assembler supports three different relaxation modes, controlled by
     89    command-line options.  */
     90 typedef enum
     91 {
     92   relax_section = 0,
     93   relax_none,
     94   relax_all
     95 } relax_optionT;
     96 
     97 /* Struct contains all assembler options set with .set.  */
     98 struct
     99 {
    100   /* .set noat -> noat = 1 allows assembly code to use at without warning
    101      and macro expansions generate a warning.
    102      .set at -> noat = 0, assembly code using at warn but macro expansions
    103      do not generate warnings.  */
    104   bfd_boolean noat;
    105 
    106   /* .set nobreak -> nobreak = 1 allows assembly code to use ba,bt without
    107 				 warning.
    108      .set break -> nobreak = 0, assembly code using ba,bt warns.  */
    109   bfd_boolean nobreak;
    110 
    111   /* .cmd line option -relax-all allows all branches and calls to be replaced
    112      with longer versions.
    113      -no-relax inhibits branch/call conversion.
    114      The default value is relax_section, which relaxes branches within
    115      a section.  */
    116   relax_optionT relax;
    117 
    118 } nios2_as_options = {FALSE, FALSE, relax_section};
    119 
    120 
    121 typedef struct nios2_insn_reloc
    122 {
    123   /* Any expression in the instruction is parsed into this field,
    124      which is passed to fix_new_exp() to generate a fixup.  */
    125   expressionS reloc_expression;
    126 
    127   /* The type of the relocation to be applied.  */
    128   bfd_reloc_code_real_type reloc_type;
    129 
    130   /* PC-relative.  */
    131   unsigned int reloc_pcrel;
    132 
    133   /* The next relocation to be applied to the instruction.  */
    134   struct nios2_insn_reloc *reloc_next;
    135 } nios2_insn_relocS;
    136 
    137 /* This struct is used to hold state when assembling instructions.  */
    138 typedef struct nios2_insn_info
    139 {
    140   /* Assembled instruction.  */
    141   unsigned long insn_code;
    142 
    143   /* Constant bits masked into insn_code for self-check mode.  */
    144   unsigned long constant_bits;
    145 
    146   /* Pointer to the relevant bit of the opcode table.  */
    147   const struct nios2_opcode *insn_nios2_opcode;
    148   /* After parsing ptrs to the tokens in the instruction fill this array
    149      it is terminated with a null pointer (hence the first +1).
    150      The second +1 is because in some parts of the code the opcode
    151      is not counted as a token, but still placed in this array.  */
    152   const char *insn_tokens[NIOS2_MAX_INSN_TOKENS + 1 + 1];
    153 
    154   /* This holds information used to generate fixups
    155      and eventually relocations if it is not null.  */
    156   nios2_insn_relocS *insn_reloc;
    157 } nios2_insn_infoS;
    158 
    159 
    160 /* This struct is used to convert Nios II pseudo-ops into the
    161    corresponding real op.  */
    162 typedef struct nios2_ps_insn_info
    163 {
    164   /* Map this pseudo_op... */
    165   const char *pseudo_insn;
    166 
    167   /* ...to this real instruction.  */
    168   const char *insn;
    169 
    170   /* Call this function to modify the operands....  */
    171   void (*arg_modifer_func) (char ** parsed_args, const char *arg, int num,
    172 			    int start);
    173 
    174   /* ...with these arguments.  */
    175   const char *arg_modifier;
    176   int num;
    177   int index;
    178 
    179   /* If arg_modifier_func allocates new memory, provide this function
    180      to free it afterwards.  */
    181   void (*arg_cleanup_func) (char **parsed_args, int num, int start);
    182 } nios2_ps_insn_infoS;
    183 
    184 /* Opcode hash table.  */
    185 static struct hash_control *nios2_opcode_hash = NULL;
    186 #define nios2_opcode_lookup(NAME) \
    187   ((struct nios2_opcode *) hash_find (nios2_opcode_hash, (NAME)))
    188 
    189 /* Register hash table.  */
    190 static struct hash_control *nios2_reg_hash = NULL;
    191 #define nios2_reg_lookup(NAME) \
    192   ((struct nios2_reg *) hash_find (nios2_reg_hash, (NAME)))
    193 
    194 
    195 /* Pseudo-op hash table.  */
    196 static struct hash_control *nios2_ps_hash = NULL;
    197 #define nios2_ps_lookup(NAME) \
    198   ((nios2_ps_insn_infoS *) hash_find (nios2_ps_hash, (NAME)))
    199 
    200 /* The known current alignment of the current section.  */
    201 static int nios2_current_align;
    202 static segT nios2_current_align_seg;
    203 
    204 static int nios2_auto_align_on = 1;
    205 
    206 /* The last seen label in the current section.  This is used to auto-align
    207    labels preceeding instructions.  */
    208 static symbolS *nios2_last_label;
    209 
    210 #ifdef OBJ_ELF
    211 /* Pre-defined "_GLOBAL_OFFSET_TABLE_"	*/
    212 symbolS *GOT_symbol;
    213 #endif
    214 
    215 
    216 /** Utility routines.  */
    218 /* Function md_chars_to_number takes the sequence of
    219    bytes in buf and returns the corresponding value
    220    in an int. n must be 1, 2 or 4.  */
    221 static valueT
    222 md_chars_to_number (char *buf, int n)
    223 {
    224   int i;
    225   valueT val;
    226 
    227   gas_assert (n == 1 || n == 2 || n == 4);
    228 
    229   val = 0;
    230   if (target_big_endian)
    231     for (i = 0; i < n; ++i)
    232       val = val | ((buf[i] & 0xff) << 8 * (n - (i + 1)));
    233   else
    234     for (i = 0; i < n; ++i)
    235       val = val | ((buf[i] & 0xff) << 8 * i);
    236   return val;
    237 }
    238 
    239 
    240 /* This function turns a C long int, short int or char
    241    into the series of bytes that represent the number
    242    on the target machine.  */
    243 void
    244 md_number_to_chars (char *buf, valueT val, int n)
    245 {
    246   gas_assert (n == 1 || n == 2 || n == 4 || n == 8);
    247   if (target_big_endian)
    248     number_to_chars_bigendian (buf, val, n);
    249   else
    250     number_to_chars_littleendian (buf, val, n);
    251 }
    252 
    253 /* Turn a string in input_line_pointer into a floating point constant
    254    of type TYPE, and store the appropriate bytes in *LITP.  The number
    255    of LITTLENUMS emitted is stored in *SIZEP.  An error message is
    256    returned, or NULL on OK.  */
    257 char *
    258 md_atof (int type, char *litP, int *sizeP)
    259 {
    260   int prec;
    261   LITTLENUM_TYPE words[4];
    262   char *t;
    263   int i;
    264 
    265   switch (type)
    266     {
    267     case 'f':
    268       prec = 2;
    269       break;
    270     case 'd':
    271       prec = 4;
    272       break;
    273     default:
    274       *sizeP = 0;
    275       return _("bad call to md_atof");
    276     }
    277 
    278   t = atof_ieee (input_line_pointer, type, words);
    279   if (t)
    280     input_line_pointer = t;
    281 
    282   *sizeP = prec * 2;
    283 
    284   if (! target_big_endian)
    285     for (i = prec - 1; i >= 0; i--, litP += 2)
    286       md_number_to_chars (litP, (valueT) words[i], 2);
    287   else
    288     for (i = 0; i < prec; i++, litP += 2)
    289       md_number_to_chars (litP, (valueT) words[i], 2);
    290 
    291   return NULL;
    292 }
    293 
    294 /* Return true if STR starts with PREFIX, which should be a string literal.  */
    295 #define strprefix(STR, PREFIX) \
    296   (strncmp ((STR), PREFIX, strlen (PREFIX)) == 0)
    297 
    298 
    299 /* Return true if STR is prefixed with a special relocation operator.  */
    300 static int
    301 nios2_special_relocation_p (const char *str)
    302 {
    303   return (strprefix (str, "%lo")
    304 	  || strprefix (str, "%hi")
    305 	  || strprefix (str, "%hiadj")
    306 	  || strprefix (str, "%gprel")
    307 	  || strprefix (str, "%got")
    308 	  || strprefix (str, "%call")
    309 	  || strprefix (str, "%gotoff_lo")
    310 	  || strprefix (str, "%gotoff_hiadj")
    311 	  || strprefix (str, "%tls_gd")
    312 	  || strprefix (str, "%tls_ldm")
    313 	  || strprefix (str, "%tls_ldo")
    314 	  || strprefix (str, "%tls_ie")
    315 	  || strprefix (str, "%tls_le")
    316 	  || strprefix (str, "%gotoff"));
    317 }
    318 
    319 
    320 /* nop fill pattern for text section.  */
    321 static char const nop[4] = { 0x3a, 0x88, 0x01, 0x00 };
    322 
    323 /* Handles all machine-dependent alignment needs.  */
    324 static void
    325 nios2_align (int log_size, const char *pfill, symbolS *label)
    326 {
    327   int align;
    328   long max_alignment = 15;
    329 
    330   /* The front end is prone to changing segments out from under us
    331      temporarily when -g is in effect.  */
    332   int switched_seg_p = (nios2_current_align_seg != now_seg);
    333 
    334   align = log_size;
    335   if (align > max_alignment)
    336     {
    337       align = max_alignment;
    338       as_bad (_("Alignment too large: %d. assumed"), align);
    339     }
    340   else if (align < 0)
    341     {
    342       as_warn (_("Alignment negative: 0 assumed"));
    343       align = 0;
    344     }
    345 
    346   if (align != 0)
    347     {
    348       if (subseg_text_p (now_seg) && align >= 2)
    349 	{
    350 	  /* First, make sure we're on a four-byte boundary, in case
    351 	     someone has been putting .byte values the text section.  */
    352 	  if (nios2_current_align < 2 || switched_seg_p)
    353 	    frag_align (2, 0, 0);
    354 
    355 	  /* Now fill in the alignment pattern.  */
    356 	  if (pfill != NULL)
    357 	    frag_align_pattern (align, pfill, sizeof nop, 0);
    358 	  else
    359 	    frag_align (align, 0, 0);
    360 	}
    361       else
    362 	frag_align (align, 0, 0);
    363 
    364       if (!switched_seg_p)
    365 	nios2_current_align = align;
    366 
    367       /* If the last label was in a different section we can't align it.  */
    368       if (label != NULL && !switched_seg_p)
    369 	{
    370 	  symbolS *sym;
    371 	  int label_seen = FALSE;
    372 	  struct frag *old_frag;
    373 	  valueT old_value;
    374 	  valueT new_value;
    375 
    376 	  gas_assert (S_GET_SEGMENT (label) == now_seg);
    377 
    378 	  old_frag = symbol_get_frag (label);
    379 	  old_value = S_GET_VALUE (label);
    380 	  new_value = (valueT) frag_now_fix ();
    381 
    382 	  /* It is possible to have more than one label at a particular
    383 	     address, especially if debugging is enabled, so we must
    384 	     take care to adjust all the labels at this address in this
    385 	     fragment.  To save time we search from the end of the symbol
    386 	     list, backwards, since the symbols we are interested in are
    387 	     almost certainly the ones that were most recently added.
    388 	     Also to save time we stop searching once we have seen at least
    389 	     one matching label, and we encounter a label that is no longer
    390 	     in the target fragment.  Note, this search is guaranteed to
    391 	     find at least one match when sym == label, so no special case
    392 	     code is necessary.  */
    393 	  for (sym = symbol_lastP; sym != NULL; sym = symbol_previous (sym))
    394 	    if (symbol_get_frag (sym) == old_frag
    395 		&& S_GET_VALUE (sym) == old_value)
    396 	      {
    397 		label_seen = TRUE;
    398 		symbol_set_frag (sym, frag_now);
    399 		S_SET_VALUE (sym, new_value);
    400 	      }
    401 	    else if (label_seen && symbol_get_frag (sym) != old_frag)
    402 	      break;
    403 	}
    404       record_alignment (now_seg, align);
    405     }
    406 }
    407 
    408 
    409 /** Support for self-check mode.  */
    411 
    412 /* Mode of the assembler.  */
    413 typedef enum
    414 {
    415   NIOS2_MODE_ASSEMBLE,		/* Ordinary operation.  */
    416   NIOS2_MODE_TEST		/* Hidden mode used for self testing.  */
    417 } NIOS2_MODE;
    418 
    419 static NIOS2_MODE nios2_mode = NIOS2_MODE_ASSEMBLE;
    420 
    421 /* This function is used to in self-checking mode
    422    to check the assembled instruction
    423    opcode should be the assembled opcode, and exp_opcode
    424    the parsed string representing the expected opcode.  */
    425 static void
    426 nios2_check_assembly (unsigned int opcode, const char *exp_opcode)
    427 {
    428   if (nios2_mode == NIOS2_MODE_TEST)
    429     {
    430       if (exp_opcode == NULL)
    431 	as_bad (_("expecting opcode string in self test mode"));
    432       else if (opcode != strtoul (exp_opcode, NULL, 16))
    433 	as_bad (_("assembly 0x%08x, expected %s"), opcode, exp_opcode);
    434     }
    435 }
    436 
    437 
    438 /** Support for machine-dependent assembler directives.  */
    440 /* Handle the .align pseudo-op.  This aligns to a power of two.  It
    441    also adjusts any current instruction label.  We treat this the same
    442    way the MIPS port does: .align 0 turns off auto alignment.  */
    443 static void
    444 s_nios2_align (int ignore ATTRIBUTE_UNUSED)
    445 {
    446   int align;
    447   char fill;
    448   const char *pfill = NULL;
    449   long max_alignment = 15;
    450 
    451   align = get_absolute_expression ();
    452   if (align > max_alignment)
    453     {
    454       align = max_alignment;
    455       as_bad (_("Alignment too large: %d. assumed"), align);
    456     }
    457   else if (align < 0)
    458     {
    459       as_warn (_("Alignment negative: 0 assumed"));
    460       align = 0;
    461     }
    462 
    463   if (*input_line_pointer == ',')
    464     {
    465       input_line_pointer++;
    466       fill = get_absolute_expression ();
    467       pfill = (const char *) &fill;
    468     }
    469   else if (subseg_text_p (now_seg))
    470     pfill = (const char *) &nop;
    471   else
    472     {
    473       pfill = NULL;
    474       nios2_last_label = NULL;
    475     }
    476 
    477   if (align != 0)
    478     {
    479       nios2_auto_align_on = 1;
    480       nios2_align (align, pfill, nios2_last_label);
    481       nios2_last_label = NULL;
    482     }
    483   else
    484     nios2_auto_align_on = 0;
    485 
    486   demand_empty_rest_of_line ();
    487 }
    488 
    489 /* Handle the .text pseudo-op.  This is like the usual one, but it
    490    clears the saved last label and resets known alignment.  */
    491 static void
    492 s_nios2_text (int i)
    493 {
    494   s_text (i);
    495   nios2_last_label = NULL;
    496   nios2_current_align = 0;
    497   nios2_current_align_seg = now_seg;
    498 }
    499 
    500 /* Handle the .data pseudo-op.  This is like the usual one, but it
    501    clears the saved last label and resets known alignment.  */
    502 static void
    503 s_nios2_data (int i)
    504 {
    505   s_data (i);
    506   nios2_last_label = NULL;
    507   nios2_current_align = 0;
    508   nios2_current_align_seg = now_seg;
    509 }
    510 
    511 /* Handle the .section pseudo-op.  This is like the usual one, but it
    512    clears the saved last label and resets known alignment.  */
    513 static void
    514 s_nios2_section (int ignore)
    515 {
    516   obj_elf_section (ignore);
    517   nios2_last_label = NULL;
    518   nios2_current_align = 0;
    519   nios2_current_align_seg = now_seg;
    520 }
    521 
    522 /* Explicitly unaligned cons.  */
    523 static void
    524 s_nios2_ucons (int nbytes)
    525 {
    526   int hold;
    527   hold = nios2_auto_align_on;
    528   nios2_auto_align_on = 0;
    529   cons (nbytes);
    530   nios2_auto_align_on = hold;
    531 }
    532 
    533 /* Handle the .sdata directive.  */
    534 static void
    535 s_nios2_sdata (int ignore ATTRIBUTE_UNUSED)
    536 {
    537   get_absolute_expression ();  /* Ignored.  */
    538   subseg_new (".sdata", 0);
    539   demand_empty_rest_of_line ();
    540 }
    541 
    542 /* .set sets assembler options eg noat/at and is also used
    543    to set symbol values (.equ, .equiv ).  */
    544 static void
    545 s_nios2_set (int equiv)
    546 {
    547   char *directive = input_line_pointer;
    548   char delim = get_symbol_end ();
    549   char *endline = input_line_pointer;
    550   *endline = delim;
    551 
    552   /* We only want to handle ".set XXX" if the
    553      user has tried ".set XXX, YYY" they are not
    554      trying a directive.  This prevents
    555      us from polluting the name space.  */
    556   SKIP_WHITESPACE ();
    557   if (is_end_of_line[(unsigned char) *input_line_pointer])
    558     {
    559       bfd_boolean done = TRUE;
    560       *endline = 0;
    561 
    562       if (!strcmp (directive, "noat"))
    563 	  nios2_as_options.noat = TRUE;
    564       else if (!strcmp (directive, "at"))
    565 	  nios2_as_options.noat = FALSE;
    566       else if (!strcmp (directive, "nobreak"))
    567 	  nios2_as_options.nobreak = TRUE;
    568       else if (!strcmp (directive, "break"))
    569 	  nios2_as_options.nobreak = FALSE;
    570       else if (!strcmp (directive, "norelax"))
    571 	  nios2_as_options.relax = relax_none;
    572       else if (!strcmp (directive, "relaxsection"))
    573 	  nios2_as_options.relax = relax_section;
    574       else if (!strcmp (directive, "relaxall"))
    575 	  nios2_as_options.relax = relax_all;
    576       else
    577 	done = FALSE;
    578 
    579       if (done)
    580 	{
    581 	  *endline = delim;
    582 	  demand_empty_rest_of_line ();
    583 	  return;
    584 	}
    585     }
    586 
    587   /* If we fall through to here, either we have ".set XXX, YYY"
    588      or we have ".set XXX" where XXX is unknown or we have
    589      a syntax error.  */
    590   input_line_pointer = directive;
    591   *endline = delim;
    592   s_set (equiv);
    593 }
    594 
    595 /* Machine-dependent assembler directives.
    596    Format of each entry is:
    597    { "directive", handler_func, param }	 */
    598 const pseudo_typeS md_pseudo_table[] = {
    599   {"align", s_nios2_align, 0},
    600   {"text", s_nios2_text, 0},
    601   {"data", s_nios2_data, 0},
    602   {"section", s_nios2_section, 0},
    603   {"section.s", s_nios2_section, 0},
    604   {"sect", s_nios2_section, 0},
    605   {"sect.s", s_nios2_section, 0},
    606   /* .dword and .half are included for compatibility with MIPS.  */
    607   {"dword", cons, 8},
    608   {"half", cons, 2},
    609   /* NIOS2 native word size is 4 bytes, so we override
    610      the GAS default of 2.  */
    611   {"word", cons, 4},
    612   /* Explicitly unaligned directives.  */
    613   {"2byte", s_nios2_ucons, 2},
    614   {"4byte", s_nios2_ucons, 4},
    615   {"8byte", s_nios2_ucons, 8},
    616   {"16byte", s_nios2_ucons, 16},
    617 #ifdef OBJ_ELF
    618   {"sdata", s_nios2_sdata, 0},
    619 #endif
    620   {"set", s_nios2_set, 0},
    621   {NULL, NULL, 0}
    622 };
    623 
    624 
    625 /** Relaxation support. */
    627 
    628 /* We support two relaxation modes:  a limited PC-relative mode with
    629    -relax-section (the default), and an absolute jump mode with -relax-all.
    630 
    631    Nios II PC-relative branch instructions only support 16-bit offsets.
    632    And, there's no good way to add a 32-bit constant to the PC without
    633    using two registers.
    634 
    635    To deal with this, for the pc-relative relaxation mode we convert
    636      br label
    637    into a series of 16-bit adds, like:
    638      nextpc at
    639      addi at, at, 32767
    640      ...
    641      addi at, at, remainder
    642      jmp at
    643 
    644    Similarly, conditional branches are converted from
    645      b(condition) r, s, label
    646    into a series like:
    647      b(opposite condition) r, s, skip
    648      nextpc at
    649      addi at, at, 32767
    650      ...
    651      addi at, at, remainder
    652      jmp at
    653      skip:
    654 
    655    The compiler can do a better job, either by converting the branch
    656    directly into a JMP (going through the GOT for PIC) or by allocating
    657    a second register for the 32-bit displacement.
    658 
    659    For the -relax-all relaxation mode, the conversions are
    660      movhi at, %hi(symbol+offset)
    661      ori at, %lo(symbol+offset)
    662      jmp at
    663    and
    664      b(opposite condition), r, s, skip
    665      movhi at, %hi(symbol+offset)
    666      ori at, %lo(symbol+offset)
    667      jmp at
    668      skip:
    669    respectively.
    670 */
    671 
    672 /* Arbitrarily limit the number of addis we can insert; we need to be able
    673    to specify the maximum growth size for each frag that contains a
    674    relaxable branch.  There's no point in specifying a huge number here
    675    since that means the assembler needs to allocate that much extra
    676    memory for every branch, and almost no real code will ever need it.
    677    Plus, as already noted a better solution is to just use a jmp, or
    678    allocate a second register to hold a 32-bit displacement.
    679    FIXME:  Rather than making this a constant, it could be controlled by
    680    a command-line argument.  */
    681 #define RELAX_MAX_ADDI 32
    682 
    683 /* The fr_subtype field represents the target-specific relocation state.
    684    It has type relax_substateT (unsigned int).  We use it to track the
    685    number of addis necessary, plus a bit to track whether this is a
    686    conditional branch.
    687    Regardless of the smaller RELAX_MAX_ADDI limit, we reserve 16 bits
    688    in the fr_subtype to encode the number of addis so that the whole
    689    theoretically-valid range is representable.
    690    For the -relax-all mode, N = 0 represents an in-range branch and N = 1
    691    represents a branch that needs to be relaxed.  */
    692 #define UBRANCH (0 << 16)
    693 #define CBRANCH (1 << 16)
    694 #define IS_CBRANCH(SUBTYPE) ((SUBTYPE) & CBRANCH)
    695 #define IS_UBRANCH(SUBTYPE) (!IS_CBRANCH (SUBTYPE))
    696 #define UBRANCH_SUBTYPE(N) (UBRANCH | (N))
    697 #define CBRANCH_SUBTYPE(N) (CBRANCH | (N))
    698 #define SUBTYPE_ADDIS(SUBTYPE) ((SUBTYPE) & 0xffff)
    699 
    700 /* For the -relax-section mode, unconditional branches require 2 extra i
    701    nstructions besides the addis, conditional branches require 3.  */
    702 #define UBRANCH_ADDIS_TO_SIZE(N) (((N) + 2) * 4)
    703 #define CBRANCH_ADDIS_TO_SIZE(N) (((N) + 3) * 4)
    704 
    705 /* For the -relax-all mode, unconditional branches require 3 instructions
    706    and conditional branches require 4.  */
    707 #define UBRANCH_JUMP_SIZE 12
    708 #define CBRANCH_JUMP_SIZE 16
    709 
    710 /* Maximum sizes of relaxation sequences.  */
    711 #define UBRANCH_MAX_SIZE \
    712   (nios2_as_options.relax == relax_all		\
    713    ? UBRANCH_JUMP_SIZE				\
    714    : UBRANCH_ADDIS_TO_SIZE (RELAX_MAX_ADDI))
    715 #define CBRANCH_MAX_SIZE \
    716   (nios2_as_options.relax == relax_all		\
    717    ? CBRANCH_JUMP_SIZE				\
    718    : CBRANCH_ADDIS_TO_SIZE (RELAX_MAX_ADDI))
    719 
    720 /* Register number of AT, the assembler temporary.  */
    721 #define AT_REGNUM 1
    722 
    723 /* Determine how many bytes are required to represent the sequence
    724    indicated by SUBTYPE.  */
    725 static int
    726 nios2_relax_subtype_size (relax_substateT subtype)
    727 {
    728   int n = SUBTYPE_ADDIS (subtype);
    729   if (n == 0)
    730     /* Regular conditional/unconditional branch instruction.  */
    731     return 4;
    732   else if (nios2_as_options.relax == relax_all)
    733     return (IS_CBRANCH (subtype) ? CBRANCH_JUMP_SIZE : UBRANCH_JUMP_SIZE);
    734   else if (IS_CBRANCH (subtype))
    735     return CBRANCH_ADDIS_TO_SIZE (n);
    736   else
    737     return UBRANCH_ADDIS_TO_SIZE (n);
    738 }
    739 
    740 /* Estimate size of fragp before relaxation.
    741    This could also examine the offset in fragp and adjust
    742    fragp->fr_subtype, but we will do that in nios2_relax_frag anyway.  */
    743 int
    744 md_estimate_size_before_relax (fragS *fragp, segT segment ATTRIBUTE_UNUSED)
    745 {
    746   return nios2_relax_subtype_size (fragp->fr_subtype);
    747 }
    748 
    749 /* Implement md_relax_frag, returning the change in size of the frag.  */
    750 long
    751 nios2_relax_frag (segT segment, fragS *fragp, long stretch)
    752 {
    753   addressT target = fragp->fr_offset;
    754   relax_substateT subtype = fragp->fr_subtype;
    755   symbolS *symbolp = fragp->fr_symbol;
    756 
    757   if (symbolp)
    758     {
    759       fragS *sym_frag = symbol_get_frag (symbolp);
    760       offsetT offset;
    761       int n;
    762 
    763       target += S_GET_VALUE (symbolp);
    764 
    765       /* See comments in write.c:relax_frag about handling of stretch.  */
    766       if (stretch != 0
    767 	  && sym_frag->relax_marker != fragp->relax_marker)
    768 	{
    769 	  if (stretch < 0 || sym_frag->region == fragp->region)
    770 	    target += stretch;
    771 	  else if (target < fragp->fr_address)
    772 	    target = fragp->fr_next->fr_address + stretch;
    773 	}
    774 
    775       /* We subtract fr_var (4 for 32-bit insns) because all pc relative
    776 	 branches are from the next instruction.  */
    777       offset = target - fragp->fr_address - fragp->fr_fix - fragp->fr_var;
    778       if (offset >= -32768 && offset <= 32764)
    779 	/* Fits in PC-relative branch.  */
    780 	n = 0;
    781       else if (nios2_as_options.relax == relax_all)
    782 	/* Convert to jump.  */
    783 	n = 1;
    784       else if (nios2_as_options.relax == relax_section
    785 	       && S_GET_SEGMENT (symbolp) == segment
    786 	       && S_IS_DEFINED (symbolp))
    787 	/* Attempt a PC-relative relaxation on a branch to a defined
    788 	   symbol in the same segment.  */
    789 	{
    790 	  /* The relaxation for conditional branches is offset by 4
    791 	     bytes because we insert the inverted branch around the
    792 	     sequence.  */
    793 	  if (IS_CBRANCH (subtype))
    794 	    offset = offset - 4;
    795 	  if (offset > 0)
    796 	    n = offset / 32767 + 1;
    797 	  else
    798 	    n = offset / -32768 + 1;
    799 
    800 	  /* Bail out immediately if relaxation has failed.  If we try to
    801 	     defer the diagnostic to md_convert_frag, some pathological test
    802 	     cases (e.g. gcc/testsuite/gcc.c-torture/compile/20001226-1.c)
    803 	     apparently never converge.  By returning 0 here we could pretend
    804 	     to the caller that nothing has changed, but that leaves things
    805 	     in an inconsistent state when we get to md_convert_frag.  */
    806 	  if (n > RELAX_MAX_ADDI)
    807 	    {
    808 	      as_bad_where (fragp->fr_file, fragp->fr_line,
    809 			    _("branch offset out of range\n"));
    810 	      as_fatal (_("branch relaxation failed\n"));
    811 	    }
    812 	}
    813       else
    814 	/* We cannot handle this case, diagnose overflow later.  */
    815 	return 0;
    816 
    817       if (IS_CBRANCH (subtype))
    818 	fragp->fr_subtype = CBRANCH_SUBTYPE (n);
    819       else
    820 	fragp->fr_subtype = UBRANCH_SUBTYPE (n);
    821 
    822       return (nios2_relax_subtype_size (fragp->fr_subtype)
    823 	      - nios2_relax_subtype_size (subtype));
    824     }
    825 
    826   /* If we got here, it's probably an error.  */
    827   return 0;
    828 }
    829 
    830 
    831 /* Complete fragp using the data from the relaxation pass. */
    832 void
    833 md_convert_frag (bfd *headers ATTRIBUTE_UNUSED, segT segment ATTRIBUTE_UNUSED,
    834 		 fragS *fragp)
    835 {
    836   char *buffer = fragp->fr_literal + fragp->fr_fix;
    837   relax_substateT subtype = fragp->fr_subtype;
    838   int n = SUBTYPE_ADDIS (subtype);
    839   addressT target = fragp->fr_offset;
    840   symbolS *symbolp = fragp->fr_symbol;
    841   offsetT offset;
    842   unsigned int addend_mask, addi_mask;
    843   offsetT addend, remainder;
    844   int i;
    845 
    846   /* If we didn't or can't relax, this is a regular branch instruction.
    847      We just need to generate the fixup for the symbol and offset.  */
    848   if (n == 0)
    849     {
    850       fix_new (fragp, fragp->fr_fix, 4, fragp->fr_symbol, fragp->fr_offset, 1,
    851 	       BFD_RELOC_16_PCREL);
    852       fragp->fr_fix += 4;
    853       return;
    854     }
    855 
    856   /* Replace the cbranch at fr_fix with one that has the opposite condition
    857      in order to jump around the block of instructions we'll be adding.  */
    858   if (IS_CBRANCH (subtype))
    859     {
    860       unsigned int br_opcode;
    861       unsigned int old_op, new_op;
    862       int nbytes;
    863 
    864       /* Account for the nextpc and jmp in the pc-relative case, or the two
    865 	 load instructions and jump in the absolute case.  */
    866       if (nios2_as_options.relax == relax_section)
    867 	nbytes = (n + 2) * 4;
    868       else
    869 	nbytes = 12;
    870 
    871       br_opcode = md_chars_to_number (buffer, 4);
    872       old_op = GET_IW_R1_OP (br_opcode);
    873       switch (old_op)
    874 	{
    875 	case R1_OP_BEQ:
    876 	  new_op = R1_OP_BNE;
    877 	  break;
    878 	case R1_OP_BNE:
    879 	  new_op = R1_OP_BEQ;
    880 	  break;
    881 	case R1_OP_BGE:
    882 	  new_op = R1_OP_BLT;
    883 	  break;
    884 	case R1_OP_BGEU:
    885 	  new_op = R1_OP_BLTU;
    886 	  break;
    887 	case R1_OP_BLT:
    888 	  new_op = R1_OP_BGE;
    889 	  break;
    890 	case R1_OP_BLTU:
    891 	  new_op = R1_OP_BGEU;
    892 	  break;
    893 	default:
    894 	  as_bad_where (fragp->fr_file, fragp->fr_line,
    895 			_("expecting conditional branch for relaxation\n"));
    896 	  abort ();
    897 	}
    898 
    899       br_opcode = (br_opcode & ~IW_R1_OP_SHIFTED_MASK) | SET_IW_R1_OP (new_op);
    900       br_opcode = br_opcode | SET_IW_I_IMM16 (nbytes);
    901       md_number_to_chars (buffer, br_opcode, 4);
    902       fragp->fr_fix += 4;
    903       buffer += 4;
    904     }
    905 
    906   /* Load at for the PC-relative case.  */
    907   if (nios2_as_options.relax == relax_section)
    908     {
    909       /* Insert the nextpc instruction.  */
    910       md_number_to_chars (buffer,
    911 			  MATCH_R1_NEXTPC | SET_IW_R_C (AT_REGNUM), 4);
    912       fragp->fr_fix += 4;
    913       buffer += 4;
    914 
    915       /* We need to know whether the offset is positive or negative.  */
    916       target += S_GET_VALUE (symbolp);
    917       offset = target - fragp->fr_address - fragp->fr_fix;
    918       if (offset > 0)
    919 	addend = 32767;
    920       else
    921 	addend = -32768;
    922       addend_mask = SET_IW_I_IMM16 ((unsigned int)addend);
    923 
    924       /* Insert n-1 addi instructions.  */
    925       addi_mask = (MATCH_R1_ADDI
    926 		   | SET_IW_I_B (AT_REGNUM)
    927 		   | SET_IW_I_A (AT_REGNUM));
    928       for (i = 0; i < n - 1; i ++)
    929 	{
    930 	  md_number_to_chars (buffer, addi_mask | addend_mask, 4);
    931 	  fragp->fr_fix += 4;
    932 	  buffer += 4;
    933 	}
    934 
    935       /* Insert the last addi instruction to hold the remainder.  */
    936       remainder = offset - addend * (n - 1);
    937       gas_assert (remainder >= -32768 && remainder <= 32767);
    938       addend_mask = SET_IW_I_IMM16 ((unsigned int)remainder);
    939       md_number_to_chars (buffer, addi_mask | addend_mask, 4);
    940       fragp->fr_fix += 4;
    941       buffer += 4;
    942     }
    943 
    944   /* Load at for the absolute case.  */
    945   else
    946     {
    947       md_number_to_chars (buffer,
    948 			  (MATCH_R1_ORHI | SET_IW_I_B (AT_REGNUM)
    949 			   | SET_IW_I_A (0)),
    950 			  4);
    951       fix_new (fragp, fragp->fr_fix, 4, fragp->fr_symbol, fragp->fr_offset,
    952 	       0, BFD_RELOC_NIOS2_HI16);
    953       fragp->fr_fix += 4;
    954       buffer += 4;
    955       md_number_to_chars (buffer,
    956 			  (MATCH_R1_ORI | SET_IW_I_B (AT_REGNUM)
    957 			   | SET_IW_I_A (AT_REGNUM)),
    958 			  4);
    959       fix_new (fragp, fragp->fr_fix, 4, fragp->fr_symbol, fragp->fr_offset,
    960 	       0, BFD_RELOC_NIOS2_LO16);
    961       fragp->fr_fix += 4;
    962       buffer += 4;
    963     }
    964 
    965   /* Insert the jmp instruction.  */
    966   md_number_to_chars (buffer, MATCH_R1_JMP | SET_IW_R_A (AT_REGNUM), 4);
    967   fragp->fr_fix += 4;
    968   buffer += 4;
    969 }
    970 
    971 
    972 /** Fixups and overflow checking.  */
    974 
    975 /* Check a fixup for overflow. */
    976 static bfd_boolean
    977 nios2_check_overflow (valueT fixup, reloc_howto_type *howto)
    978 {
    979   /* Apply the rightshift before checking for overflow.  */
    980   fixup = ((signed)fixup) >> howto->rightshift;
    981 
    982   /* Check for overflow - return TRUE if overflow, FALSE if not.  */
    983   switch (howto->complain_on_overflow)
    984     {
    985     case complain_overflow_dont:
    986       break;
    987     case complain_overflow_bitfield:
    988       if ((fixup >> howto->bitsize) != 0
    989 	  && ((signed) fixup >> howto->bitsize) != -1)
    990 	return TRUE;
    991       break;
    992     case complain_overflow_signed:
    993       if ((fixup & 0x80000000) > 0)
    994 	{
    995 	  /* Check for negative overflow.  */
    996 	  if ((signed) fixup < ((signed) 0x80000000 >> howto->bitsize))
    997 	    return TRUE;
    998 	}
    999       else
   1000 	{
   1001 	  /* Check for positive overflow.  */
   1002 	  if (fixup >= ((unsigned) 1 << (howto->bitsize - 1)))
   1003 	    return TRUE;
   1004 	}
   1005       break;
   1006     case complain_overflow_unsigned:
   1007       if ((fixup >> howto->bitsize) != 0)
   1008 	return TRUE;
   1009       break;
   1010     default:
   1011       as_bad (_("error checking for overflow - broken assembler"));
   1012       break;
   1013     }
   1014   return FALSE;
   1015 }
   1016 
   1017 /* Emit diagnostic for fixup overflow.  */
   1018 static void
   1019 nios2_diagnose_overflow (valueT fixup, reloc_howto_type *howto,
   1020 			 fixS *fixP, valueT value)
   1021 {
   1022   if (fixP->fx_r_type == BFD_RELOC_8
   1023       || fixP->fx_r_type == BFD_RELOC_16
   1024       || fixP->fx_r_type == BFD_RELOC_32)
   1025     /* These relocs are against data, not instructions.  */
   1026     as_bad_where (fixP->fx_file, fixP->fx_line,
   1027 		  _("immediate value 0x%x truncated to 0x%x"),
   1028 		  (unsigned int) fixup,
   1029 		  (unsigned int) (~(~(valueT) 0 << howto->bitsize) & fixup));
   1030   else
   1031     {
   1032       /* What opcode is the instruction?  This will determine
   1033 	 whether we check for overflow in immediate values
   1034 	 and what error message we get.  */
   1035       const struct nios2_opcode *opcode;
   1036       enum overflow_type overflow_msg_type;
   1037       unsigned int range_min;
   1038       unsigned int range_max;
   1039       unsigned int address;
   1040 
   1041       opcode = nios2_find_opcode_hash (value, bfd_get_mach (stdoutput));
   1042       gas_assert (opcode);
   1043       gas_assert (fixP->fx_size == opcode->size);
   1044       overflow_msg_type = opcode->overflow_msg;
   1045       switch (overflow_msg_type)
   1046 	{
   1047 	case call_target_overflow:
   1048 	  range_min
   1049 	    = ((fixP->fx_frag->fr_address + fixP->fx_where) & 0xf0000000);
   1050 	  range_max = range_min + 0x0fffffff;
   1051 	  address = fixup | range_min;
   1052 
   1053 	  as_bad_where (fixP->fx_file, fixP->fx_line,
   1054 			_("call target address 0x%08x out of range 0x%08x to 0x%08x"),
   1055 			address, range_min, range_max);
   1056 	  break;
   1057 	case branch_target_overflow:
   1058 	  as_bad_where (fixP->fx_file, fixP->fx_line,
   1059 			_("branch offset %d out of range %d to %d"),
   1060 			(int)fixup, -32768, 32767);
   1061 	  break;
   1062 	case address_offset_overflow:
   1063 	  as_bad_where (fixP->fx_file, fixP->fx_line,
   1064 			_("%s offset %d out of range %d to %d"),
   1065 			opcode->name, (int)fixup, -32768, 32767);
   1066 	  break;
   1067 	case signed_immed16_overflow:
   1068 	  as_bad_where (fixP->fx_file, fixP->fx_line,
   1069 			_("immediate value %d out of range %d to %d"),
   1070 			(int)fixup, -32768, 32767);
   1071 	  break;
   1072 	case unsigned_immed16_overflow:
   1073 	  as_bad_where (fixP->fx_file, fixP->fx_line,
   1074 			_("immediate value %u out of range %u to %u"),
   1075 			(unsigned int)fixup, 0, 65535);
   1076 	  break;
   1077 	case unsigned_immed5_overflow:
   1078 	  as_bad_where (fixP->fx_file, fixP->fx_line,
   1079 			_("immediate value %u out of range %u to %u"),
   1080 			(unsigned int)fixup, 0, 31);
   1081 	  break;
   1082 	case custom_opcode_overflow:
   1083 	  as_bad_where (fixP->fx_file, fixP->fx_line,
   1084 			_("custom instruction opcode %u out of range %u to %u"),
   1085 			(unsigned int)fixup, 0, 255);
   1086 	  break;
   1087 	default:
   1088 	  as_bad_where (fixP->fx_file, fixP->fx_line,
   1089 			_("overflow in immediate argument"));
   1090 	  break;
   1091 	}
   1092     }
   1093 }
   1094 
   1095 /* Apply a fixup to the object file.  */
   1096 void
   1097 md_apply_fix (fixS *fixP, valueT *valP, segT seg ATTRIBUTE_UNUSED)
   1098 {
   1099   /* Assert that the fixup is one we can handle.  */
   1100   gas_assert (fixP != NULL && valP != NULL
   1101 	      && (fixP->fx_r_type == BFD_RELOC_8
   1102 		  || fixP->fx_r_type == BFD_RELOC_16
   1103 		  || fixP->fx_r_type == BFD_RELOC_32
   1104 		  || fixP->fx_r_type == BFD_RELOC_64
   1105 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_S16
   1106 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_U16
   1107 		  || fixP->fx_r_type == BFD_RELOC_16_PCREL
   1108 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_CALL26
   1109 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_IMM5
   1110 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_CACHE_OPX
   1111 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_IMM6
   1112 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_IMM8
   1113 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_HI16
   1114 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_LO16
   1115 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_HIADJ16
   1116 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_GPREL
   1117 		  || fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT
   1118 		  || fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY
   1119 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_UJMP
   1120 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_CJMP
   1121 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_CALLR
   1122 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_ALIGN
   1123 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_GOT16
   1124 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_CALL16
   1125 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_GOTOFF_LO
   1126 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_GOTOFF_HA
   1127 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_TLS_GD16
   1128 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_TLS_LDM16
   1129 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_TLS_LDO16
   1130 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_TLS_IE16
   1131 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_TLS_LE16
   1132 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_GOTOFF
   1133 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_TLS_DTPREL
   1134 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_CALL26_NOAT
   1135 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_GOT_LO
   1136 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_GOT_HA
   1137 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_CALL_LO
   1138 		  || fixP->fx_r_type == BFD_RELOC_NIOS2_CALL_HA
   1139 		  /* Add other relocs here as we generate them.  */
   1140 		  ));
   1141 
   1142   if (fixP->fx_r_type == BFD_RELOC_64)
   1143     {
   1144       /* We may reach here due to .8byte directives, but we never output
   1145 	 BFD_RELOC_64; it must be resolved.  */
   1146       if (fixP->fx_addsy != NULL)
   1147 	as_bad_where (fixP->fx_file, fixP->fx_line,
   1148 		      _("cannot create 64-bit relocation"));
   1149       else
   1150 	{
   1151 	  md_number_to_chars (fixP->fx_frag->fr_literal + fixP->fx_where,
   1152 			      *valP, 8);
   1153 	  fixP->fx_done = 1;
   1154 	}
   1155       return;
   1156     }
   1157 
   1158   /* The value passed in valP can be the value of a fully
   1159      resolved expression, or it can be the value of a partially
   1160      resolved expression.  In the former case, both fixP->fx_addsy
   1161      and fixP->fx_subsy are NULL, and fixP->fx_offset == *valP, and
   1162      we can fix up the instruction that fixP relates to.
   1163      In the latter case, one or both of fixP->fx_addsy and
   1164      fixP->fx_subsy are not NULL, and fixP->fx_offset may or may not
   1165      equal *valP.  We don't need to check for fixP->fx_subsy being null
   1166      because the generic part of the assembler generates an error if
   1167      it is not an absolute symbol.  */
   1168   if (fixP->fx_addsy != NULL)
   1169     /* Partially resolved expression.  */
   1170     {
   1171       fixP->fx_addnumber = fixP->fx_offset;
   1172       fixP->fx_done = 0;
   1173 
   1174       switch (fixP->fx_r_type)
   1175 	{
   1176 	case BFD_RELOC_NIOS2_TLS_GD16:
   1177 	case BFD_RELOC_NIOS2_TLS_LDM16:
   1178 	case BFD_RELOC_NIOS2_TLS_LDO16:
   1179 	case BFD_RELOC_NIOS2_TLS_IE16:
   1180 	case BFD_RELOC_NIOS2_TLS_LE16:
   1181 	case BFD_RELOC_NIOS2_TLS_DTPMOD:
   1182 	case BFD_RELOC_NIOS2_TLS_DTPREL:
   1183 	case BFD_RELOC_NIOS2_TLS_TPREL:
   1184 	  S_SET_THREAD_LOCAL (fixP->fx_addsy);
   1185 	  break;
   1186 	default:
   1187 	  break;
   1188 	}
   1189     }
   1190   else
   1191     /* Fully resolved fixup.  */
   1192     {
   1193       reloc_howto_type *howto
   1194 	= bfd_reloc_type_lookup (stdoutput, fixP->fx_r_type);
   1195 
   1196       if (howto == NULL)
   1197 	as_bad_where (fixP->fx_file, fixP->fx_line,
   1198 		      _("relocation is not supported"));
   1199       else
   1200 	{
   1201 	  valueT fixup = *valP;
   1202 	  valueT value;
   1203 	  char *buf;
   1204 
   1205 	  /* If this is a pc-relative relocation, we need to
   1206 	     subtract the current offset within the object file
   1207 	     FIXME : for some reason fixP->fx_pcrel isn't 1 when it should be
   1208 	     so I'm using the howto structure instead to determine this.  */
   1209 	  if (howto->pc_relative == 1)
   1210 	    fixup = fixup - (fixP->fx_frag->fr_address + fixP->fx_where
   1211 			     + fixP->fx_size);
   1212 
   1213 	  /* Get the instruction or data to be fixed up.  */
   1214 	  buf = fixP->fx_frag->fr_literal + fixP->fx_where;
   1215 	  value = md_chars_to_number (buf, fixP->fx_size);
   1216 
   1217 	  /* Check for overflow, emitting a diagnostic if necessary.  */
   1218 	  if (nios2_check_overflow (fixup, howto))
   1219 	    nios2_diagnose_overflow (fixup, howto, fixP, value);
   1220 
   1221 	  /* Apply the right shift.  */
   1222 	  fixup = ((signed)fixup) >> howto->rightshift;
   1223 
   1224 	  /* Truncate the fixup to right size.  */
   1225 	  switch (fixP->fx_r_type)
   1226 	    {
   1227 	    case BFD_RELOC_NIOS2_HI16:
   1228 	      fixup = (fixup >> 16) & 0xFFFF;
   1229 	      break;
   1230 	    case BFD_RELOC_NIOS2_LO16:
   1231 	      fixup = fixup & 0xFFFF;
   1232 	      break;
   1233 	    case BFD_RELOC_NIOS2_HIADJ16:
   1234 	      fixup = ((((fixup >> 16) & 0xFFFF) + ((fixup >> 15) & 0x01))
   1235 		       & 0xFFFF);
   1236 	      break;
   1237 	    default:
   1238 	      {
   1239 		int n = sizeof (fixup) * 8 - howto->bitsize;
   1240 		fixup = (fixup << n) >> n;
   1241 		break;
   1242 	      }
   1243 	    }
   1244 
   1245 	  /* Fix up the instruction.  */
   1246 	  value = (value & ~howto->dst_mask) | (fixup << howto->bitpos);
   1247 	  md_number_to_chars (buf, value, fixP->fx_size);
   1248 	}
   1249 
   1250       fixP->fx_done = 1;
   1251     }
   1252 
   1253   if (fixP->fx_r_type == BFD_RELOC_VTABLE_INHERIT)
   1254     {
   1255       fixP->fx_done = 0;
   1256       if (fixP->fx_addsy
   1257 	  && !S_IS_DEFINED (fixP->fx_addsy) && !S_IS_WEAK (fixP->fx_addsy))
   1258 	S_SET_WEAK (fixP->fx_addsy);
   1259     }
   1260   else if (fixP->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
   1261     fixP->fx_done = 0;
   1262 }
   1263 
   1264 
   1265 
   1266 /** Instruction parsing support. */
   1268 
   1269 /* General internal error routine.  */
   1270 
   1271 static void
   1272 bad_opcode (const struct nios2_opcode *op)
   1273 {
   1274   fprintf (stderr, _("internal error: broken opcode descriptor for `%s %s'\n"),
   1275 	   op->name, op->args);
   1276   as_fatal (_("Broken assembler.  No assembly attempted."));
   1277 }
   1278 
   1279 /* Special relocation directive strings.  */
   1280 
   1281 struct nios2_special_relocS
   1282 {
   1283   const char *string;
   1284   bfd_reloc_code_real_type reloc_type;
   1285 };
   1286 
   1287 /* This table is sorted so that prefix strings are listed after the longer
   1288    strings that include them -- e.g., %got after %got_hiadj, etc.  */
   1289 
   1290 struct nios2_special_relocS nios2_special_reloc[] = {
   1291   {"%hiadj", BFD_RELOC_NIOS2_HIADJ16},
   1292   {"%hi", BFD_RELOC_NIOS2_HI16},
   1293   {"%lo", BFD_RELOC_NIOS2_LO16},
   1294   {"%gprel", BFD_RELOC_NIOS2_GPREL},
   1295   {"%call_lo", BFD_RELOC_NIOS2_CALL_LO},
   1296   {"%call_hiadj", BFD_RELOC_NIOS2_CALL_HA},
   1297   {"%call", BFD_RELOC_NIOS2_CALL16},
   1298   {"%gotoff_lo", BFD_RELOC_NIOS2_GOTOFF_LO},
   1299   {"%gotoff_hiadj", BFD_RELOC_NIOS2_GOTOFF_HA},
   1300   {"%gotoff", BFD_RELOC_NIOS2_GOTOFF},
   1301   {"%got_hiadj", BFD_RELOC_NIOS2_GOT_HA},
   1302   {"%got_lo", BFD_RELOC_NIOS2_GOT_LO},
   1303   {"%got", BFD_RELOC_NIOS2_GOT16},
   1304   {"%tls_gd", BFD_RELOC_NIOS2_TLS_GD16},
   1305   {"%tls_ldm", BFD_RELOC_NIOS2_TLS_LDM16},
   1306   {"%tls_ldo", BFD_RELOC_NIOS2_TLS_LDO16},
   1307   {"%tls_ie", BFD_RELOC_NIOS2_TLS_IE16},
   1308   {"%tls_le", BFD_RELOC_NIOS2_TLS_LE16},
   1309 };
   1310 
   1311 #define NIOS2_NUM_SPECIAL_RELOCS \
   1312 	(sizeof(nios2_special_reloc)/sizeof(nios2_special_reloc[0]))
   1313 const int nios2_num_special_relocs = NIOS2_NUM_SPECIAL_RELOCS;
   1314 
   1315 /* Creates a new nios2_insn_relocS and returns a pointer to it.  */
   1316 static nios2_insn_relocS *
   1317 nios2_insn_reloc_new (bfd_reloc_code_real_type reloc_type, unsigned int pcrel)
   1318 {
   1319   nios2_insn_relocS *retval;
   1320   retval = (nios2_insn_relocS *) malloc (sizeof (nios2_insn_relocS));
   1321   if (retval == NULL)
   1322     {
   1323       as_bad (_("can't create relocation"));
   1324       abort ();
   1325     }
   1326 
   1327   /* Fill out the fields with default values.  */
   1328   retval->reloc_next = NULL;
   1329   retval->reloc_type = reloc_type;
   1330   retval->reloc_pcrel = pcrel;
   1331   return retval;
   1332 }
   1333 
   1334 /* Frees up memory previously allocated by nios2_insn_reloc_new().  */
   1335 /* FIXME:  this is never called; memory leak?  */
   1336 #if 0
   1337 static void
   1338 nios2_insn_reloc_destroy (nios2_insn_relocS *reloc)
   1339 {
   1340   gas_assert (reloc != NULL);
   1341   free (reloc);
   1342 }
   1343 #endif
   1344 
   1345 /* Look up a register name and validate it for the given regtype.
   1346    Return the register mapping or NULL on failure.  */
   1347 static struct nios2_reg *
   1348 nios2_parse_reg (const char *token, unsigned long regtype)
   1349 {
   1350   struct nios2_reg *reg = nios2_reg_lookup (token);
   1351 
   1352   if (reg == NULL)
   1353     {
   1354       as_bad (_("unknown register %s"), token);
   1355       return NULL;
   1356     }
   1357 
   1358   /* Matched a register, but is it the wrong type?  */
   1359   if (!(regtype & reg->regtype))
   1360     {
   1361       if (regtype & REG_CONTROL)
   1362 	as_bad (_("expecting control register"));
   1363       else if (reg->regtype & REG_CONTROL)
   1364 	as_bad (_("illegal use of control register"));
   1365       else if (reg->regtype & REG_COPROCESSOR)
   1366 	as_bad (_("illegal use of coprocessor register"));
   1367       else
   1368 	as_bad (_("invalid register %s"), token);
   1369       return NULL;
   1370     }
   1371 
   1372   /* Warn for explicit use of special registers.  */
   1373   if (reg->regtype & REG_NORMAL)
   1374     {
   1375       if (!nios2_as_options.noat && reg->index == 1)
   1376 	as_warn (_("Register at (r1) can sometimes be corrupted by "
   1377 		   "assembler optimizations.\n"
   1378 		   "Use .set noat to turn off those optimizations "
   1379 		   "(and this warning)."));
   1380       if (!nios2_as_options.nobreak && reg->index == 25)
   1381 	as_warn (_("The debugger will corrupt bt (r25).\n"
   1382 		   "If you don't need to debug this "
   1383 		   "code use .set nobreak to turn off this warning."));
   1384       if (!nios2_as_options.nobreak && reg->index == 30)
   1385 	as_warn (_("The debugger will corrupt sstatus/ba (r30).\n"
   1386 		   "If you don't need to debug this "
   1387 		   "code use .set nobreak to turn off this warning."));
   1388     }
   1389 
   1390   return reg;
   1391 }
   1392 
   1393 /* The various nios2_assemble_* functions call this
   1394    function to generate an expression from a string representing an expression.
   1395    It then tries to evaluate the expression, and if it can, returns its value.
   1396    If not, it creates a new nios2_insn_relocS and stores the expression and
   1397    reloc_type for future use.  */
   1398 static unsigned long
   1399 nios2_assemble_expression (const char *exprstr,
   1400 			   nios2_insn_infoS *insn,
   1401 			   bfd_reloc_code_real_type reloc_type,
   1402 			   unsigned int pcrel)
   1403 {
   1404   nios2_insn_relocS *reloc;
   1405   char *saved_line_ptr;
   1406   unsigned short value;
   1407   int i;
   1408 
   1409   gas_assert (exprstr != NULL);
   1410   gas_assert (insn != NULL);
   1411 
   1412   /* Check for relocation operators.
   1413      Change the relocation type and advance the ptr to the start of
   1414      the expression proper. */
   1415   for (i = 0; i < nios2_num_special_relocs; i++)
   1416     if (strstr (exprstr, nios2_special_reloc[i].string) != NULL)
   1417       {
   1418 	reloc_type = nios2_special_reloc[i].reloc_type;
   1419 	exprstr += strlen (nios2_special_reloc[i].string) + 1;
   1420 
   1421 	/* %lo and %hiadj have different meanings for PC-relative
   1422 	   expressions.  */
   1423 	if (pcrel)
   1424 	  {
   1425 	    if (reloc_type == BFD_RELOC_NIOS2_LO16)
   1426 	      reloc_type = BFD_RELOC_NIOS2_PCREL_LO;
   1427 	    if (reloc_type == BFD_RELOC_NIOS2_HIADJ16)
   1428 	      reloc_type = BFD_RELOC_NIOS2_PCREL_HA;
   1429 	  }
   1430 
   1431 	break;
   1432       }
   1433 
   1434   /* We potentially have a relocation.  */
   1435   reloc = nios2_insn_reloc_new (reloc_type, pcrel);
   1436   reloc->reloc_next = insn->insn_reloc;
   1437   insn->insn_reloc = reloc;
   1438 
   1439   /* Parse the expression string.  */
   1440   saved_line_ptr = input_line_pointer;
   1441   input_line_pointer = (char *) exprstr;
   1442   expression (&reloc->reloc_expression);
   1443   input_line_pointer = saved_line_ptr;
   1444 
   1445   /* This is redundant as the fixup will put this into
   1446      the instruction, but it is included here so that
   1447      self-test mode (-r) works.  */
   1448   value = 0;
   1449   if (nios2_mode == NIOS2_MODE_TEST
   1450       && reloc->reloc_expression.X_op == O_constant)
   1451     value = reloc->reloc_expression.X_add_number;
   1452 
   1453   return (unsigned long) value;
   1454 }
   1455 
   1456 
   1457 /* Argument assemble functions.  */
   1458 static void
   1459 nios2_assemble_arg_c (const char *token, nios2_insn_infoS *insn)
   1460 {
   1461   struct nios2_reg *reg = nios2_parse_reg (token, REG_CONTROL);
   1462   const struct nios2_opcode *op = insn->insn_nios2_opcode;
   1463 
   1464   if (reg == NULL)
   1465     return;
   1466 
   1467   switch (op->format)
   1468     {
   1469     case iw_r_type:
   1470       insn->insn_code |= SET_IW_R_IMM5 (reg->index);
   1471       break;
   1472     default:
   1473       bad_opcode (op);
   1474     }
   1475 }
   1476 
   1477 static void
   1478 nios2_assemble_arg_d (const char *token, nios2_insn_infoS *insn)
   1479 {
   1480   const struct nios2_opcode *op = insn->insn_nios2_opcode;
   1481   unsigned long regtype = REG_NORMAL;
   1482   struct nios2_reg *reg;
   1483 
   1484   if (op->format == iw_custom_type)
   1485     regtype |= REG_COPROCESSOR;
   1486   reg = nios2_parse_reg (token, regtype);
   1487   if (reg == NULL)
   1488     return;
   1489 
   1490   switch (op->format)
   1491     {
   1492     case iw_r_type:
   1493       insn->insn_code |= SET_IW_R_C (reg->index);
   1494       break;
   1495     case iw_custom_type:
   1496       insn->insn_code |= SET_IW_CUSTOM_C (reg->index);
   1497       if (reg->regtype & REG_COPROCESSOR)
   1498 	insn->insn_code |= SET_IW_CUSTOM_READC (0);
   1499       else
   1500 	insn->insn_code |= SET_IW_CUSTOM_READC (1);
   1501       break;
   1502     default:
   1503       bad_opcode (op);
   1504     }
   1505 }
   1506 
   1507 static void
   1508 nios2_assemble_arg_s (const char *token, nios2_insn_infoS *insn)
   1509 {
   1510   const struct nios2_opcode *op = insn->insn_nios2_opcode;
   1511   unsigned long regtype = REG_NORMAL;
   1512   struct nios2_reg *reg;
   1513 
   1514   if (op->format == iw_custom_type)
   1515     regtype |= REG_COPROCESSOR;
   1516   reg = nios2_parse_reg (token, regtype);
   1517   if (reg == NULL)
   1518     return;
   1519 
   1520   switch (op->format)
   1521     {
   1522     case iw_r_type:
   1523       insn->insn_code |= SET_IW_R_A (reg->index);
   1524       break;
   1525     case iw_i_type:
   1526       insn->insn_code |= SET_IW_I_A (reg->index);
   1527       break;
   1528     case iw_custom_type:
   1529       insn->insn_code |= SET_IW_CUSTOM_A (reg->index);
   1530       if (reg->regtype & REG_COPROCESSOR)
   1531 	insn->insn_code |= SET_IW_CUSTOM_READA (0);
   1532       else
   1533 	insn->insn_code |= SET_IW_CUSTOM_READA (1);
   1534       break;
   1535     default:
   1536       bad_opcode (op);
   1537     }
   1538 }
   1539 
   1540 static void
   1541 nios2_assemble_arg_t (const char *token, nios2_insn_infoS *insn)
   1542 {
   1543   const struct nios2_opcode *op = insn->insn_nios2_opcode;
   1544   unsigned long regtype = REG_NORMAL;
   1545   struct nios2_reg *reg;
   1546 
   1547   if (op->format == iw_custom_type)
   1548     regtype |= REG_COPROCESSOR;
   1549   reg = nios2_parse_reg (token, regtype);
   1550   if (reg == NULL)
   1551     return;
   1552 
   1553   switch (op->format)
   1554     {
   1555     case iw_r_type:
   1556       insn->insn_code |= SET_IW_R_B (reg->index);
   1557       break;
   1558     case iw_i_type:
   1559       insn->insn_code |= SET_IW_I_B (reg->index);
   1560       break;
   1561     case iw_custom_type:
   1562       insn->insn_code |= SET_IW_CUSTOM_B (reg->index);
   1563       if (reg->regtype & REG_COPROCESSOR)
   1564 	insn->insn_code |= SET_IW_CUSTOM_READB (0);
   1565       else
   1566 	insn->insn_code |= SET_IW_CUSTOM_READB (1);
   1567       break;
   1568     default:
   1569       bad_opcode (op);
   1570     }
   1571 }
   1572 
   1573 static void
   1574 nios2_assemble_arg_i (const char *token, nios2_insn_infoS *insn)
   1575 {
   1576   const struct nios2_opcode *op = insn->insn_nios2_opcode;
   1577   unsigned int val;
   1578 
   1579   switch (op->format)
   1580     {
   1581     case iw_i_type:
   1582       val = nios2_assemble_expression (token, insn,
   1583 				       BFD_RELOC_NIOS2_S16, 0);
   1584       insn->constant_bits |= SET_IW_I_IMM16 (val);
   1585       break;
   1586     default:
   1587       bad_opcode (op);
   1588     }
   1589 }
   1590 
   1591 static void
   1592 nios2_assemble_arg_u (const char *token, nios2_insn_infoS *insn)
   1593 {
   1594   const struct nios2_opcode *op = insn->insn_nios2_opcode;
   1595   unsigned int val;
   1596 
   1597   switch (op->format)
   1598     {
   1599     case iw_i_type:
   1600       val = nios2_assemble_expression (token, insn,
   1601 				       BFD_RELOC_NIOS2_U16, 0);
   1602       insn->constant_bits |= SET_IW_I_IMM16 (val);
   1603       break;
   1604     default:
   1605       bad_opcode (op);
   1606     }
   1607 }
   1608 
   1609 static void
   1610 nios2_assemble_arg_o (const char *token, nios2_insn_infoS *insn)
   1611 {
   1612   const struct nios2_opcode *op = insn->insn_nios2_opcode;
   1613   unsigned int val;
   1614 
   1615   switch (op->format)
   1616     {
   1617     case iw_i_type:
   1618       val = nios2_assemble_expression (token, insn,
   1619 				       BFD_RELOC_16_PCREL, 1);
   1620       insn->constant_bits |= SET_IW_I_IMM16 (val);
   1621       break;
   1622     default:
   1623       bad_opcode (op);
   1624     }
   1625 }
   1626 
   1627 static void
   1628 nios2_assemble_arg_j (const char *token, nios2_insn_infoS *insn)
   1629 {
   1630   const struct nios2_opcode *op = insn->insn_nios2_opcode;
   1631   unsigned int val;
   1632 
   1633   switch (op->format)
   1634     {
   1635     case iw_r_type:
   1636       val = nios2_assemble_expression (token, insn,
   1637 				       BFD_RELOC_NIOS2_IMM5, 0);
   1638       insn->constant_bits |= SET_IW_R_IMM5 (val);
   1639       break;
   1640     default:
   1641       bad_opcode (op);
   1642     }
   1643 }
   1644 
   1645 static void
   1646 nios2_assemble_arg_l (const char *token, nios2_insn_infoS *insn)
   1647 {
   1648   const struct nios2_opcode *op = insn->insn_nios2_opcode;
   1649   unsigned int val;
   1650 
   1651   switch (op->format)
   1652     {
   1653     case iw_custom_type:
   1654       val = nios2_assemble_expression (token, insn,
   1655 				       BFD_RELOC_NIOS2_IMM8, 0);
   1656       insn->constant_bits |= SET_IW_CUSTOM_N (val);
   1657       break;
   1658     default:
   1659       bad_opcode (op);
   1660     }
   1661 }
   1662 
   1663 static void
   1664 nios2_assemble_arg_m (const char *token, nios2_insn_infoS *insn)
   1665 {
   1666   const struct nios2_opcode *op = insn->insn_nios2_opcode;
   1667   unsigned int val;
   1668 
   1669   switch (op->format)
   1670     {
   1671     case iw_j_type:
   1672       val = nios2_assemble_expression (token, insn,
   1673 				       (nios2_as_options.noat
   1674 					? BFD_RELOC_NIOS2_CALL26_NOAT
   1675 					: BFD_RELOC_NIOS2_CALL26),
   1676 				       0);
   1677       insn->constant_bits |= SET_IW_J_IMM26 (val);
   1678       break;
   1679     default:
   1680       bad_opcode (op);
   1681     }
   1682 }
   1683 
   1684 static void
   1685 nios2_assemble_args (nios2_insn_infoS *insn)
   1686 {
   1687   const struct nios2_opcode *op = insn->insn_nios2_opcode;
   1688   const char *argptr;
   1689   unsigned int tokidx, ntok;
   1690 
   1691   /* Make sure there are enough arguments.  */
   1692   ntok = (op->pinfo & NIOS2_INSN_OPTARG) ? op->num_args - 1 : op->num_args;
   1693   for (tokidx = 1; tokidx <= ntok; tokidx++)
   1694     if (insn->insn_tokens[tokidx] == NULL)
   1695       {
   1696 	as_bad ("missing argument");
   1697 	return;
   1698       }
   1699 
   1700   for (argptr = op->args, tokidx = 1;
   1701        *argptr && insn->insn_tokens[tokidx];
   1702        argptr++)
   1703     switch (*argptr)
   1704       {
   1705       case ',':
   1706       case '(':
   1707       case ')':
   1708 	break;
   1709 
   1710       case 'c':
   1711 	nios2_assemble_arg_c (insn->insn_tokens[tokidx++], insn);
   1712 	break;
   1713 
   1714       case 'd':
   1715 	nios2_assemble_arg_d (insn->insn_tokens[tokidx++], insn);
   1716 	break;
   1717 
   1718       case 's':
   1719 	nios2_assemble_arg_s (insn->insn_tokens[tokidx++], insn);
   1720 	break;
   1721 
   1722       case 't':
   1723 	nios2_assemble_arg_t (insn->insn_tokens[tokidx++], insn);
   1724 	break;
   1725 
   1726       case 'i':
   1727 	nios2_assemble_arg_i (insn->insn_tokens[tokidx++], insn);
   1728 	break;
   1729 
   1730       case 'u':
   1731 	nios2_assemble_arg_u (insn->insn_tokens[tokidx++], insn);
   1732 	break;
   1733 
   1734       case 'o':
   1735 	nios2_assemble_arg_o (insn->insn_tokens[tokidx++], insn);
   1736 	break;
   1737 
   1738       case 'j':
   1739 	nios2_assemble_arg_j (insn->insn_tokens[tokidx++], insn);
   1740 	break;
   1741 
   1742       case 'l':
   1743 	nios2_assemble_arg_l (insn->insn_tokens[tokidx++], insn);
   1744 	break;
   1745 
   1746       case 'm':
   1747 	nios2_assemble_arg_m (insn->insn_tokens[tokidx++], insn);
   1748 	break;
   1749 
   1750       default:
   1751 	bad_opcode (op);
   1752 	break;
   1753       }
   1754 
   1755   /* Perform argument checking.  */
   1756   nios2_check_assembly (insn->insn_code | insn->constant_bits,
   1757 			insn->insn_tokens[tokidx]);
   1758 }
   1759 
   1760 
   1761 /* The function consume_arg takes a pointer into a string
   1762    of instruction tokens (args) and a pointer into a string
   1763    representing the expected sequence of tokens and separators.
   1764    It checks whether the first argument in argstr is of the
   1765    expected type, throwing an error if it is not, and returns
   1766    the pointer argstr.  */
   1767 static char *
   1768 nios2_consume_arg (char *argstr, const char *parsestr)
   1769 {
   1770   char *temp;
   1771 
   1772   switch (*parsestr)
   1773     {
   1774     case 'c':
   1775     case 'd':
   1776     case 's':
   1777     case 't':
   1778       break;
   1779 
   1780     case 'i':
   1781     case 'u':
   1782       if (*argstr == '%')
   1783 	{
   1784 	  if (nios2_special_relocation_p (argstr))
   1785 	    {
   1786 	      /* We zap the parentheses because we don't want them confused
   1787 		 with separators.  */
   1788 	      temp = strchr (argstr, '(');
   1789 	      if (temp != NULL)
   1790 		*temp = ' ';
   1791 	      temp = strchr (argstr, ')');
   1792 	      if (temp != NULL)
   1793 		*temp = ' ';
   1794 	    }
   1795 	  else
   1796 	    as_bad (_("badly formed expression near %s"), argstr);
   1797 	}
   1798       break;
   1799     case 'm':
   1800     case 'j':
   1801     case 'l':
   1802       /* We can't have %hi, %lo or %hiadj here.  */
   1803       if (*argstr == '%')
   1804 	as_bad (_("badly formed expression near %s"), argstr);
   1805       break;
   1806     case 'o':
   1807     case 'E':
   1808       break;
   1809     default:
   1810       BAD_CASE (*parsestr);
   1811       break;
   1812     }
   1813 
   1814   return argstr;
   1815 }
   1816 
   1817 /* The function consume_separator takes a pointer into a string
   1818    of instruction tokens (args) and a pointer into a string representing
   1819    the expected sequence of tokens and separators.  It finds the first
   1820    instance of the character pointed to by separator in argstr, and
   1821    returns a pointer to the next element of argstr, which is the
   1822    following token in the sequence.  */
   1823 static char *
   1824 nios2_consume_separator (char *argstr, const char *separator)
   1825 {
   1826   char *p;
   1827 
   1828   /* If we have a opcode reg, expr(reg) type instruction, and
   1829    * we are separating the expr from the (reg), we find the last
   1830    * (, just in case the expression has parentheses.  */
   1831 
   1832   if (*separator == '(')
   1833     p = strrchr (argstr, *separator);
   1834   else
   1835     p = strchr (argstr, *separator);
   1836 
   1837   if (p != NULL)
   1838     *p++ = 0;
   1839   return p;
   1840 }
   1841 
   1842 
   1843 /* The principal argument parsing function which takes a string argstr
   1844    representing the instruction arguments for insn, and extracts the argument
   1845    tokens matching parsestr into parsed_args.  */
   1846 static void
   1847 nios2_parse_args (nios2_insn_infoS *insn, char *argstr,
   1848 		  const char *parsestr, char **parsed_args)
   1849 {
   1850   char *p;
   1851   char *end = NULL;
   1852   int i;
   1853   p = argstr;
   1854   i = 0;
   1855   bfd_boolean terminate = FALSE;
   1856 
   1857   /* This rest of this function is it too fragile and it mostly works,
   1858      therefore special case this one.  */
   1859   if (*parsestr == 0 && argstr != 0)
   1860     {
   1861       as_bad (_("too many arguments"));
   1862       parsed_args[0] = NULL;
   1863       return;
   1864     }
   1865 
   1866   while (p != NULL && !terminate && i < NIOS2_MAX_INSN_TOKENS)
   1867     {
   1868       parsed_args[i] = nios2_consume_arg (p, parsestr);
   1869       ++parsestr;
   1870       while (*parsestr == '(' || *parsestr == ')' || *parsestr == ',')
   1871 	{
   1872 	  char *context = p;
   1873 	  p = nios2_consume_separator (p, parsestr);
   1874 	  /* Check for missing separators.  */
   1875 	  if (!p && !(insn->insn_nios2_opcode->pinfo & NIOS2_INSN_OPTARG))
   1876 	    {
   1877 	      as_bad (_("expecting %c near %s"), *parsestr, context);
   1878 	      break;
   1879 	    }
   1880 	  ++parsestr;
   1881 	}
   1882 
   1883       if (*parsestr == '\0')
   1884 	{
   1885 	  /* Check that the argument string has no trailing arguments.  */
   1886 	  end = strpbrk (p, ",");
   1887 	  if (end != NULL)
   1888 	    as_bad (_("too many arguments"));
   1889 	}
   1890 
   1891       if (*parsestr == '\0' || (p != NULL && *p == '\0'))
   1892 	terminate = TRUE;
   1893       ++i;
   1894     }
   1895 
   1896   parsed_args[i] = NULL;
   1897 }
   1898 
   1899 
   1900 
   1901 /** Support for pseudo-op parsing.  These are macro-like opcodes that
   1903     expand into real insns by suitable fiddling with the operands.  */
   1904 
   1905 /* Append the string modifier to the string contained in the argument at
   1906    parsed_args[ndx].  */
   1907 static void
   1908 nios2_modify_arg (char **parsed_args, const char *modifier,
   1909 		  int unused ATTRIBUTE_UNUSED, int ndx)
   1910 {
   1911   char *tmp = parsed_args[ndx];
   1912 
   1913   parsed_args[ndx]
   1914     = (char *) malloc (strlen (parsed_args[ndx]) + strlen (modifier) + 1);
   1915   strcpy (parsed_args[ndx], tmp);
   1916   strcat (parsed_args[ndx], modifier);
   1917 }
   1918 
   1919 /* Modify parsed_args[ndx] by negating that argument.  */
   1920 static void
   1921 nios2_negate_arg (char **parsed_args, const char *modifier ATTRIBUTE_UNUSED,
   1922 		  int unused ATTRIBUTE_UNUSED, int ndx)
   1923 {
   1924   char *tmp = parsed_args[ndx];
   1925 
   1926   parsed_args[ndx]
   1927     = (char *) malloc (strlen ("~(") + strlen (parsed_args[ndx]) +
   1928 		       strlen (")+1") + 1);
   1929 
   1930   strcpy (parsed_args[ndx], "~(");
   1931   strcat (parsed_args[ndx], tmp);
   1932   strcat (parsed_args[ndx], ")+1");
   1933 }
   1934 
   1935 /* The function nios2_swap_args swaps the pointers at indices index_1 and
   1936    index_2 in the array parsed_args[] - this is used for operand swapping
   1937    for comparison operations.  */
   1938 static void
   1939 nios2_swap_args (char **parsed_args, const char *unused ATTRIBUTE_UNUSED,
   1940 		 int index_1, int index_2)
   1941 {
   1942   char *tmp;
   1943   gas_assert (index_1 < NIOS2_MAX_INSN_TOKENS
   1944 	      && index_2 < NIOS2_MAX_INSN_TOKENS);
   1945   tmp = parsed_args[index_1];
   1946   parsed_args[index_1] = parsed_args[index_2];
   1947   parsed_args[index_2] = tmp;
   1948 }
   1949 
   1950 /* This function appends the string appnd to the array of strings in
   1951    parsed_args num times starting at index start in the array.  */
   1952 static void
   1953 nios2_append_arg (char **parsed_args, const char *appnd, int num,
   1954 		  int start)
   1955 {
   1956   int i, count;
   1957   char *tmp;
   1958 
   1959   gas_assert ((start + num) < NIOS2_MAX_INSN_TOKENS);
   1960 
   1961   if (nios2_mode == NIOS2_MODE_TEST)
   1962     tmp = parsed_args[start];
   1963   else
   1964     tmp = NULL;
   1965 
   1966   for (i = start, count = num; count > 0; ++i, --count)
   1967     parsed_args[i] = (char *) appnd;
   1968 
   1969   gas_assert (i == (start + num));
   1970   parsed_args[i] = tmp;
   1971   parsed_args[i + 1] = NULL;
   1972 }
   1973 
   1974 /* This function inserts the string insert num times in the array
   1975    parsed_args, starting at the index start.  */
   1976 static void
   1977 nios2_insert_arg (char **parsed_args, const char *insert, int num,
   1978 		  int start)
   1979 {
   1980   int i, count;
   1981 
   1982   gas_assert ((start + num) < NIOS2_MAX_INSN_TOKENS);
   1983 
   1984   /* Move the existing arguments up to create space.  */
   1985   for (i = NIOS2_MAX_INSN_TOKENS; i - num >= start; --i)
   1986     parsed_args[i] = parsed_args[i - num];
   1987 
   1988   for (i = start, count = num; count > 0; ++i, --count)
   1989     parsed_args[i] = (char *) insert;
   1990 }
   1991 
   1992 /* Cleanup function to free malloc'ed arg strings.  */
   1993 static void
   1994 nios2_free_arg (char **parsed_args, int num ATTRIBUTE_UNUSED, int start)
   1995 {
   1996   if (parsed_args[start])
   1997     {
   1998       free (parsed_args[start]);
   1999       parsed_args[start] = NULL;
   2000     }
   2001 }
   2002 
   2003 /* This function swaps the pseudo-op for a real op.  */
   2004 static nios2_ps_insn_infoS*
   2005 nios2_translate_pseudo_insn (nios2_insn_infoS *insn)
   2006 {
   2007 
   2008   nios2_ps_insn_infoS *ps_insn;
   2009 
   2010   /* Find which real insn the pseudo-op transates to and
   2011      switch the insn_info ptr to point to it.  */
   2012   ps_insn = nios2_ps_lookup (insn->insn_nios2_opcode->name);
   2013 
   2014   if (ps_insn != NULL)
   2015     {
   2016       insn->insn_nios2_opcode = nios2_opcode_lookup (ps_insn->insn);
   2017       insn->insn_tokens[0] = insn->insn_nios2_opcode->name;
   2018       /* Modify the args so they work with the real insn.  */
   2019       ps_insn->arg_modifer_func ((char **) insn->insn_tokens,
   2020 				 ps_insn->arg_modifier, ps_insn->num,
   2021 				 ps_insn->index);
   2022     }
   2023   else
   2024     /* we cannot recover from this.  */
   2025     as_fatal (_("unrecognized pseudo-instruction %s"),
   2026 	      ps_insn->pseudo_insn);
   2027   return ps_insn;
   2028 }
   2029 
   2030 /* Invoke the cleanup handler for pseudo-insn ps_insn on insn.  */
   2031 static void
   2032 nios2_cleanup_pseudo_insn (nios2_insn_infoS *insn,
   2033 			   nios2_ps_insn_infoS *ps_insn)
   2034 {
   2035   if (ps_insn->arg_cleanup_func)
   2036     (ps_insn->arg_cleanup_func) ((char **) insn->insn_tokens,
   2037 				 ps_insn->num, ps_insn->index);
   2038 }
   2039 
   2040 const nios2_ps_insn_infoS nios2_ps_insn_info_structs[] = {
   2041   /* pseudo-op, real-op, arg, arg_modifier_func, num, index, arg_cleanup_func */
   2042   {"mov", "add", nios2_append_arg, "zero", 1, 3, NULL},
   2043   {"movi", "addi", nios2_insert_arg, "zero", 1, 2, NULL},
   2044   {"movhi", "orhi", nios2_insert_arg, "zero", 1, 2, NULL},
   2045   {"movui", "ori", nios2_insert_arg, "zero", 1, 2, NULL},
   2046   {"movia", "orhi", nios2_insert_arg, "zero", 1, 2, NULL},
   2047   {"nop", "add", nios2_append_arg, "zero", 3, 1, NULL},
   2048   {"bgt", "blt", nios2_swap_args, "", 1, 2, NULL},
   2049   {"bgtu", "bltu", nios2_swap_args, "", 1, 2, NULL},
   2050   {"ble", "bge", nios2_swap_args, "", 1, 2, NULL},
   2051   {"bleu", "bgeu", nios2_swap_args, "", 1, 2, NULL},
   2052   {"cmpgt", "cmplt", nios2_swap_args, "", 2, 3, NULL},
   2053   {"cmpgtu", "cmpltu", nios2_swap_args, "", 2, 3, NULL},
   2054   {"cmple", "cmpge", nios2_swap_args, "", 2, 3, NULL},
   2055   {"cmpleu", "cmpgeu", nios2_swap_args, "", 2, 3, NULL},
   2056   {"cmpgti", "cmpgei", nios2_modify_arg, "+1", 0, 3, nios2_free_arg},
   2057   {"cmpgtui", "cmpgeui", nios2_modify_arg, "+1", 0, 3, nios2_free_arg},
   2058   {"cmplei", "cmplti", nios2_modify_arg, "+1", 0, 3, nios2_free_arg},
   2059   {"cmpleui", "cmpltui", nios2_modify_arg, "+1", 0, 3, nios2_free_arg},
   2060   {"subi", "addi", nios2_negate_arg, "", 0, 3, nios2_free_arg}
   2061   /* Add further pseudo-ops here.  */
   2062 };
   2063 
   2064 #define NIOS2_NUM_PSEUDO_INSNS \
   2065 	((sizeof(nios2_ps_insn_info_structs)/ \
   2066 	  sizeof(nios2_ps_insn_info_structs[0])))
   2067 const int nios2_num_ps_insn_info_structs = NIOS2_NUM_PSEUDO_INSNS;
   2068 
   2069 
   2070 /** Assembler output support.  */
   2072 
   2073 static int
   2074 can_evaluate_expr (nios2_insn_infoS *insn)
   2075 {
   2076   /* Remove this check for null and the invalid insn "ori r9, 1234" seg faults. */
   2077   if (!insn->insn_reloc)
   2078     /* ??? Ideally we should do something other than as_fatal here as we can
   2079        continue to assemble.
   2080        However this function (actually the output_* functions) should not
   2081        have been called in the first place once an illegal instruction had
   2082        been encountered.  */
   2083     as_fatal (_("Invalid instruction encountered, cannot recover. No assembly attempted."));
   2084 
   2085   if (insn->insn_reloc->reloc_expression.X_op == O_constant)
   2086     return 1;
   2087 
   2088   return 0;
   2089 }
   2090 
   2091 static int
   2092 get_expr_value (nios2_insn_infoS *insn)
   2093 {
   2094   int value = 0;
   2095 
   2096   if (insn->insn_reloc->reloc_expression.X_op == O_constant)
   2097     value = insn->insn_reloc->reloc_expression.X_add_number;
   2098   return value;
   2099 }
   2100 
   2101 /* Output a normal instruction.  */
   2102 static void
   2103 output_insn (nios2_insn_infoS *insn)
   2104 {
   2105   char *f;
   2106   nios2_insn_relocS *reloc;
   2107   f = frag_more (insn->insn_nios2_opcode->size);
   2108   /* This allocates enough space for the instruction
   2109      and puts it in the current frag.  */
   2110   md_number_to_chars (f, insn->insn_code, insn->insn_nios2_opcode->size);
   2111   /* Emit debug info.  */
   2112   dwarf2_emit_insn (insn->insn_nios2_opcode->size);
   2113   /* Create any fixups to be acted on later.  */
   2114 
   2115   for (reloc = insn->insn_reloc; reloc != NULL; reloc = reloc->reloc_next)
   2116     fix_new_exp (frag_now, f - frag_now->fr_literal,
   2117 		 insn->insn_nios2_opcode->size,
   2118 		 &reloc->reloc_expression, reloc->reloc_pcrel,
   2119 		 reloc->reloc_type);
   2120 }
   2121 
   2122 /* Output an unconditional branch.  */
   2123 static void
   2124 output_ubranch (nios2_insn_infoS *insn)
   2125 {
   2126   nios2_insn_relocS *reloc = insn->insn_reloc;
   2127 
   2128   /* If the reloc is NULL, there was an error assembling the branch.  */
   2129   if (reloc != NULL)
   2130     {
   2131       symbolS *symp = reloc->reloc_expression.X_add_symbol;
   2132       offsetT offset = reloc->reloc_expression.X_add_number;
   2133       char *f;
   2134 
   2135       /* Tag dwarf2 debug info to the address at the start of the insn.
   2136 	 We must do it before frag_var() below closes off the frag.  */
   2137       dwarf2_emit_insn (0);
   2138 
   2139       /* We create a machine dependent frag which can grow
   2140 	 to accommodate the largest possible instruction sequence
   2141 	 this may generate.  */
   2142       f = frag_var (rs_machine_dependent,
   2143 		    UBRANCH_MAX_SIZE, insn->insn_nios2_opcode->size,
   2144 		    UBRANCH_SUBTYPE (0), symp, offset, NULL);
   2145 
   2146       md_number_to_chars (f, insn->insn_code, insn->insn_nios2_opcode->size);
   2147 
   2148       /* We leave fixup generation to md_convert_frag.  */
   2149     }
   2150 }
   2151 
   2152 /* Output a conditional branch.  */
   2153 static void
   2154 output_cbranch (nios2_insn_infoS *insn)
   2155 {
   2156   nios2_insn_relocS *reloc = insn->insn_reloc;
   2157 
   2158   /* If the reloc is NULL, there was an error assembling the branch.  */
   2159   if (reloc != NULL)
   2160     {
   2161       symbolS *symp = reloc->reloc_expression.X_add_symbol;
   2162       offsetT offset = reloc->reloc_expression.X_add_number;
   2163       char *f;
   2164 
   2165       /* Tag dwarf2 debug info to the address at the start of the insn.
   2166 	 We must do it before frag_var() below closes off the frag.  */
   2167       dwarf2_emit_insn (0);
   2168 
   2169       /* We create a machine dependent frag which can grow
   2170 	 to accommodate the largest possible instruction sequence
   2171 	 this may generate.  */
   2172       f = frag_var (rs_machine_dependent,
   2173 		    CBRANCH_MAX_SIZE, insn->insn_nios2_opcode->size,
   2174 		    CBRANCH_SUBTYPE (0), symp, offset, NULL);
   2175 
   2176       md_number_to_chars (f, insn->insn_code, insn->insn_nios2_opcode->size);
   2177 
   2178       /* We leave fixup generation to md_convert_frag.  */
   2179     }
   2180 }
   2181 
   2182 /* Output a call sequence.  Since calls are not pc-relative for NIOS2,
   2183    but are page-relative, we cannot tell at any stage in assembly
   2184    whether a call will be out of range since a section may be linked
   2185    at any address.  So if we are relaxing, we convert all call instructions
   2186    to long call sequences, and rely on the linker to relax them back to
   2187    short calls.  */
   2188 static void
   2189 output_call (nios2_insn_infoS *insn)
   2190 {
   2191   /* This allocates enough space for the instruction
   2192      and puts it in the current frag.  */
   2193   char *f = frag_more (12);
   2194   nios2_insn_relocS *reloc = insn->insn_reloc;
   2195 
   2196   md_number_to_chars (f,
   2197 		      (MATCH_R1_ORHI | SET_IW_I_B (AT_REGNUM)
   2198 		       | SET_IW_I_A (0)),
   2199 		      4);
   2200   dwarf2_emit_insn (4);
   2201   fix_new_exp (frag_now, f - frag_now->fr_literal, 4,
   2202 	       &reloc->reloc_expression, 0, BFD_RELOC_NIOS2_HI16);
   2203   md_number_to_chars (f + 4,
   2204 		      (MATCH_R1_ORI | SET_IW_I_B (AT_REGNUM)
   2205 		       | SET_IW_I_A (AT_REGNUM)),
   2206 		      4);
   2207   dwarf2_emit_insn (4);
   2208   fix_new_exp (frag_now, f - frag_now->fr_literal + 4, 4,
   2209 	       &reloc->reloc_expression, 0, BFD_RELOC_NIOS2_LO16);
   2210   md_number_to_chars (f + 8, MATCH_R1_CALLR | SET_IW_R_A (AT_REGNUM), 4);
   2211   dwarf2_emit_insn (4);
   2212 }
   2213 
   2214 /* Output an addi - will silently convert to
   2215    orhi if rA = r0 and (expr & 0xffff0000) == 0.  */
   2216 static void
   2217 output_addi (nios2_insn_infoS *insn)
   2218 {
   2219   if (can_evaluate_expr (insn))
   2220     {
   2221       int expr_val = get_expr_value (insn);
   2222       unsigned int rega = GET_IW_I_A (insn->insn_code);
   2223       unsigned int regb = GET_IW_I_B (insn->insn_code);
   2224 
   2225       if (rega == 0
   2226 	  && (expr_val & 0xffff) == 0
   2227 	  && expr_val != 0)
   2228 	{
   2229 	  /* We really want a movhi (orhi) here.  */
   2230 	  insn->insn_code
   2231 	    = MATCH_R1_ORHI | SET_IW_I_A (rega) | SET_IW_I_B (regb);
   2232 	  insn->insn_reloc->reloc_expression.X_add_number
   2233 	    = (expr_val >> 16) & 0xffff;
   2234 	  insn->insn_reloc->reloc_type = BFD_RELOC_NIOS2_U16;
   2235 	}
   2236     }
   2237 
   2238   /* Output an instruction.  */
   2239   output_insn (insn);
   2240 }
   2241 
   2242 static void
   2243 output_andi (nios2_insn_infoS *insn)
   2244 {
   2245   if (can_evaluate_expr (insn))
   2246     {
   2247       int expr_val = get_expr_value (insn);
   2248       if (expr_val != 0 && (expr_val & 0xffff) == 0)
   2249 	{
   2250 	  unsigned int rega = GET_IW_I_A (insn->insn_code);
   2251 	  unsigned int regb = GET_IW_I_B (insn->insn_code);
   2252 
   2253 	  /* We really want an andhi here.  */
   2254 	  insn->insn_code
   2255 	    = MATCH_R1_ANDHI | SET_IW_I_A (rega) | SET_IW_I_B (regb);
   2256 	  insn->insn_reloc->reloc_expression.X_add_number
   2257 	    = (expr_val >> 16) & 0xffff;
   2258 	  insn->insn_reloc->reloc_type = BFD_RELOC_NIOS2_U16;
   2259 	}
   2260     }
   2261 
   2262   /* Output an instruction.  */
   2263   output_insn (insn);
   2264 }
   2265 
   2266 static void
   2267 output_ori (nios2_insn_infoS *insn)
   2268 {
   2269   if (can_evaluate_expr (insn))
   2270     {
   2271       int expr_val = get_expr_value (insn);
   2272       if (expr_val != 0 && (expr_val & 0xffff) == 0)
   2273 	{
   2274 	  unsigned int rega = GET_IW_I_A (insn->insn_code);
   2275 	  unsigned int regb = GET_IW_I_B (insn->insn_code);
   2276 
   2277 	  /* We really want a movhi (orhi) here.  */
   2278 	  insn->insn_code
   2279 	    = MATCH_R1_ORHI | SET_IW_I_A (rega) | SET_IW_I_B (regb);
   2280 	  insn->insn_reloc->reloc_expression.X_add_number
   2281 	    = (expr_val >> 16) & 0xffff;
   2282 	  insn->insn_reloc->reloc_type = BFD_RELOC_NIOS2_U16;
   2283 	}
   2284     }
   2285 
   2286   /* Output an instruction.  */
   2287   output_insn (insn);
   2288 }
   2289 
   2290 static void
   2291 output_xori (nios2_insn_infoS *insn)
   2292 {
   2293   if (can_evaluate_expr (insn))
   2294     {
   2295       int expr_val = get_expr_value (insn);
   2296       if (expr_val != 0 && (expr_val & 0xffff) == 0)
   2297 	{
   2298 	  unsigned int rega = GET_IW_I_A (insn->insn_code);
   2299 	  unsigned int regb = GET_IW_I_B (insn->insn_code);
   2300 
   2301 	  /* We really want an xorhi here.  */
   2302 	  insn->insn_code
   2303 	    = MATCH_R1_XORHI | SET_IW_I_A (rega) | SET_IW_I_B (regb);
   2304 	  insn->insn_reloc->reloc_expression.X_add_number
   2305 	    = (expr_val >> 16) & 0xffff;
   2306 	  insn->insn_reloc->reloc_type = BFD_RELOC_NIOS2_U16;
   2307 	}
   2308     }
   2309 
   2310   /* Output an instruction.  */
   2311   output_insn (insn);
   2312 }
   2313 
   2314 
   2315 /* Output a movhi/addi pair for the movia pseudo-op.  */
   2316 static void
   2317 output_movia (nios2_insn_infoS *insn)
   2318 {
   2319   /* This allocates enough space for the instruction
   2320      and puts it in the current frag.  */
   2321   char *f = frag_more (8);
   2322   nios2_insn_relocS *reloc = insn->insn_reloc;
   2323   unsigned long reg_index = GET_IW_I_B (insn->insn_code);
   2324 
   2325   /* If the reloc is NULL, there was an error assembling the movia.  */
   2326   if (reloc != NULL)
   2327     {
   2328       md_number_to_chars (f, insn->insn_code, 4);
   2329       dwarf2_emit_insn (4);
   2330       fix_new (frag_now, f - frag_now->fr_literal, 4,
   2331 	       reloc->reloc_expression.X_add_symbol,
   2332 	       reloc->reloc_expression.X_add_number, 0,
   2333 	       BFD_RELOC_NIOS2_HIADJ16);
   2334       md_number_to_chars (f + 4,
   2335 			  (MATCH_R1_ADDI | SET_IW_I_A (reg_index)
   2336 			   | SET_IW_I_B (reg_index)),
   2337 			  4);
   2338       dwarf2_emit_insn (4);
   2339       fix_new (frag_now, f + 4 - frag_now->fr_literal, 4,
   2340 	       reloc->reloc_expression.X_add_symbol,
   2341 	       reloc->reloc_expression.X_add_number, 0, BFD_RELOC_NIOS2_LO16);
   2342     }
   2343 }
   2344 
   2345 
   2346 
   2347 /** External interfaces.  */
   2349 
   2350 /* The following functions are called by machine-independent parts of
   2351    the assembler. */
   2352 int
   2353 md_parse_option (int c, char *arg ATTRIBUTE_UNUSED)
   2354 {
   2355   switch (c)
   2356     {
   2357     case 'r':
   2358       /* Hidden option for self-test mode.  */
   2359       nios2_mode = NIOS2_MODE_TEST;
   2360       break;
   2361     case OPTION_RELAX_ALL:
   2362       nios2_as_options.relax = relax_all;
   2363       break;
   2364     case OPTION_NORELAX:
   2365       nios2_as_options.relax = relax_none;
   2366       break;
   2367     case OPTION_RELAX_SECTION:
   2368       nios2_as_options.relax = relax_section;
   2369       break;
   2370     case OPTION_EB:
   2371       target_big_endian = 1;
   2372       break;
   2373     case OPTION_EL:
   2374       target_big_endian = 0;
   2375       break;
   2376     default:
   2377       return 0;
   2378       break;
   2379     }
   2380 
   2381   return 1;
   2382 }
   2383 
   2384 /* Implement TARGET_FORMAT.  We can choose to be big-endian or
   2385    little-endian at runtime based on a switch.  */
   2386 const char *
   2387 nios2_target_format (void)
   2388 {
   2389   return target_big_endian ? "elf32-bignios2" : "elf32-littlenios2";
   2390 }
   2391 
   2392 /* Machine-dependent usage message. */
   2393 void
   2394 md_show_usage (FILE *stream)
   2395 {
   2396   fprintf (stream, "	    NIOS2 options:\n"
   2397 	   "  -relax-all	    replace all branch and call "
   2398 	   "instructions with jmp and callr sequences\n"
   2399 	   "  -relax-section	    replace identified out of range "
   2400 	   "branches with jmp sequences (default)\n"
   2401 	   "  -no-relax		    do not replace any branches or calls\n"
   2402 	   "  -EB		    force big-endian byte ordering\n"
   2403 	   "  -EL		    force little-endian byte ordering\n");
   2404 }
   2405 
   2406 /* This function is called once, at assembler startup time.
   2407    It should set up all the tables, etc. that the MD part of the
   2408    assembler will need. */
   2409 void
   2410 md_begin (void)
   2411 {
   2412   int i;
   2413   const char *inserted;
   2414 
   2415   /* Create and fill a hashtable for the Nios II opcodes, registers and
   2416      arguments.  */
   2417   nios2_opcode_hash = hash_new ();
   2418   nios2_reg_hash = hash_new ();
   2419   nios2_ps_hash = hash_new ();
   2420 
   2421   for (i = 0; i < nios2_num_opcodes; ++i)
   2422     {
   2423       inserted
   2424 	= hash_insert (nios2_opcode_hash, nios2_opcodes[i].name,
   2425 		       (PTR) & nios2_opcodes[i]);
   2426       if (inserted != NULL)
   2427 	{
   2428 	  fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
   2429 		   nios2_opcodes[i].name, inserted);
   2430 	  /* Probably a memory allocation problem?  Give up now.  */
   2431 	  as_fatal (_("Broken assembler.  No assembly attempted."));
   2432 	}
   2433     }
   2434 
   2435   for (i = 0; i < nios2_num_regs; ++i)
   2436     {
   2437       inserted
   2438 	= hash_insert (nios2_reg_hash, nios2_regs[i].name,
   2439 		       (PTR) & nios2_regs[i]);
   2440       if (inserted != NULL)
   2441 	{
   2442 	  fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
   2443 		   nios2_regs[i].name, inserted);
   2444 	  /* Probably a memory allocation problem?  Give up now.  */
   2445 	  as_fatal (_("Broken assembler.  No assembly attempted."));
   2446 	}
   2447 
   2448     }
   2449 
   2450   for (i = 0; i < nios2_num_ps_insn_info_structs; ++i)
   2451     {
   2452       inserted
   2453 	= hash_insert (nios2_ps_hash, nios2_ps_insn_info_structs[i].pseudo_insn,
   2454 		       (PTR) & nios2_ps_insn_info_structs[i]);
   2455       if (inserted != NULL)
   2456 	{
   2457 	  fprintf (stderr, _("internal error: can't hash `%s': %s\n"),
   2458 		   nios2_ps_insn_info_structs[i].pseudo_insn, inserted);
   2459 	  /* Probably a memory allocation problem?  Give up now.  */
   2460 	  as_fatal (_("Broken assembler.  No assembly attempted."));
   2461 	}
   2462     }
   2463 
   2464   /* Assembler option defaults.  */
   2465   nios2_as_options.noat = FALSE;
   2466   nios2_as_options.nobreak = FALSE;
   2467 
   2468   /* Debug information is incompatible with relaxation.  */
   2469   if (debug_type != DEBUG_UNSPECIFIED)
   2470     nios2_as_options.relax = relax_none;
   2471 
   2472   /* Initialize the alignment data.  */
   2473   nios2_current_align_seg = now_seg;
   2474   nios2_last_label = NULL;
   2475   nios2_current_align = 0;
   2476 }
   2477 
   2478 
   2479 /* Assembles a single line of Nios II assembly language.  */
   2480 void
   2481 md_assemble (char *op_str)
   2482 {
   2483   char *argstr;
   2484   char *op_strdup = NULL;
   2485   unsigned long saved_pinfo = 0;
   2486   nios2_insn_infoS thisinsn;
   2487   nios2_insn_infoS *insn = &thisinsn;
   2488 
   2489   /* Make sure we are aligned on a 4-byte boundary.  */
   2490   if (nios2_current_align < 2)
   2491     nios2_align (2, NULL, nios2_last_label);
   2492   else if (nios2_current_align > 2)
   2493     nios2_current_align = 2;
   2494   nios2_last_label = NULL;
   2495 
   2496   /* We don't want to clobber to op_str
   2497      because we want to be able to use it in messages.  */
   2498   op_strdup = strdup (op_str);
   2499   insn->insn_tokens[0] = strtok (op_strdup, " ");
   2500   argstr = strtok (NULL, "");
   2501 
   2502   /* Assemble the opcode.  */
   2503   insn->insn_nios2_opcode = nios2_opcode_lookup (insn->insn_tokens[0]);
   2504   insn->insn_reloc = NULL;
   2505 
   2506   if (insn->insn_nios2_opcode != NULL)
   2507     {
   2508       nios2_ps_insn_infoS *ps_insn = NULL;
   2509       /* Set the opcode for the instruction.  */
   2510       insn->insn_code = insn->insn_nios2_opcode->match;
   2511       insn->constant_bits = 0;
   2512 
   2513       /* Parse the arguments pointed to by argstr.  */
   2514       if (nios2_mode == NIOS2_MODE_ASSEMBLE)
   2515 	nios2_parse_args (insn, argstr, insn->insn_nios2_opcode->args,
   2516 			  (char **) &insn->insn_tokens[1]);
   2517       else
   2518 	nios2_parse_args (insn, argstr, insn->insn_nios2_opcode->args_test,
   2519 			  (char **) &insn->insn_tokens[1]);
   2520 
   2521       /* We need to preserve the MOVIA macro as this is clobbered by
   2522 	 translate_pseudo_insn.  */
   2523       if (insn->insn_nios2_opcode->pinfo == NIOS2_INSN_MACRO_MOVIA)
   2524 	saved_pinfo = NIOS2_INSN_MACRO_MOVIA;
   2525       /* If the instruction is an pseudo-instruction, we want to replace it
   2526 	 with its real equivalent, and then continue.  */
   2527       if ((insn->insn_nios2_opcode->pinfo & NIOS2_INSN_MACRO)
   2528 	  == NIOS2_INSN_MACRO)
   2529 	ps_insn = nios2_translate_pseudo_insn (insn);
   2530 
   2531       /* Assemble the parsed arguments into the instruction word.  */
   2532       nios2_assemble_args (insn);
   2533 
   2534       /* Handle relaxation and other transformations.  */
   2535       if (nios2_as_options.relax != relax_none
   2536 	  && !nios2_as_options.noat
   2537 	  && insn->insn_nios2_opcode->pinfo & NIOS2_INSN_UBRANCH)
   2538 	output_ubranch (insn);
   2539       else if (nios2_as_options.relax != relax_none
   2540 	       && !nios2_as_options.noat
   2541 	       && insn->insn_nios2_opcode->pinfo & NIOS2_INSN_CBRANCH)
   2542 	output_cbranch (insn);
   2543       else if (nios2_as_options.relax == relax_all
   2544 	       && !nios2_as_options.noat
   2545 	       && insn->insn_nios2_opcode->pinfo & NIOS2_INSN_CALL
   2546 	       && insn->insn_reloc
   2547 	       && ((insn->insn_reloc->reloc_type
   2548 		    == BFD_RELOC_NIOS2_CALL26)
   2549 		   || (insn->insn_reloc->reloc_type
   2550 		       == BFD_RELOC_NIOS2_CALL26_NOAT)))
   2551 	output_call (insn);
   2552       else if (insn->insn_nios2_opcode->pinfo & NIOS2_INSN_ANDI)
   2553 	output_andi (insn);
   2554       else if (insn->insn_nios2_opcode->pinfo & NIOS2_INSN_ORI)
   2555 	output_ori (insn);
   2556       else if (insn->insn_nios2_opcode->pinfo & NIOS2_INSN_XORI)
   2557 	output_xori (insn);
   2558       else if (insn->insn_nios2_opcode->pinfo & NIOS2_INSN_ADDI)
   2559 	output_addi (insn);
   2560       else if (saved_pinfo == NIOS2_INSN_MACRO_MOVIA)
   2561 	output_movia (insn);
   2562       else
   2563 	output_insn (insn);
   2564       if (ps_insn)
   2565 	nios2_cleanup_pseudo_insn (insn, ps_insn);
   2566     }
   2567   else
   2568     /* Unrecognised instruction - error.  */
   2569     as_bad (_("unrecognised instruction %s"), insn->insn_tokens[0]);
   2570 
   2571   /* Don't leak memory.  */
   2572   free (op_strdup);
   2573 }
   2574 
   2575 /* Round up section size.  */
   2576 valueT
   2577 md_section_align (asection *seg ATTRIBUTE_UNUSED, valueT size)
   2578 {
   2579   /* I think byte alignment is fine here.  */
   2580   return size;
   2581 }
   2582 
   2583 /* Implement TC_FORCE_RELOCATION.  */
   2584 int
   2585 nios2_force_relocation (fixS *fixp)
   2586 {
   2587   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
   2588       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY
   2589       || fixp->fx_r_type == BFD_RELOC_NIOS2_ALIGN)
   2590     return 1;
   2591 
   2592   return generic_force_reloc (fixp);
   2593 }
   2594 
   2595 /* Implement tc_fix_adjustable.  */
   2596 int
   2597 nios2_fix_adjustable (fixS *fixp)
   2598 {
   2599   if (fixp->fx_addsy == NULL)
   2600     return 1;
   2601 
   2602 #ifdef OBJ_ELF
   2603   /* Prevent all adjustments to global symbols.  */
   2604   if (OUTPUT_FLAVOR == bfd_target_elf_flavour
   2605       && (S_IS_EXTERNAL (fixp->fx_addsy) || S_IS_WEAK (fixp->fx_addsy)))
   2606     return 0;
   2607 #endif
   2608   if (fixp->fx_r_type == BFD_RELOC_VTABLE_INHERIT
   2609       || fixp->fx_r_type == BFD_RELOC_VTABLE_ENTRY)
   2610     return 0;
   2611 
   2612   /* Preserve relocations against symbols with function type.  */
   2613   if (symbol_get_bfdsym (fixp->fx_addsy)->flags & BSF_FUNCTION)
   2614     return 0;
   2615 
   2616   /* Don't allow symbols to be discarded on GOT related relocs.  */
   2617   if (fixp->fx_r_type == BFD_RELOC_NIOS2_GOT16
   2618       || fixp->fx_r_type == BFD_RELOC_NIOS2_CALL16
   2619       || fixp->fx_r_type == BFD_RELOC_NIOS2_GOTOFF_LO
   2620       || fixp->fx_r_type == BFD_RELOC_NIOS2_GOTOFF_HA
   2621       || fixp->fx_r_type == BFD_RELOC_NIOS2_TLS_GD16
   2622       || fixp->fx_r_type == BFD_RELOC_NIOS2_TLS_LDM16
   2623       || fixp->fx_r_type == BFD_RELOC_NIOS2_TLS_LDO16
   2624       || fixp->fx_r_type == BFD_RELOC_NIOS2_TLS_IE16
   2625       || fixp->fx_r_type == BFD_RELOC_NIOS2_TLS_LE16
   2626       || fixp->fx_r_type == BFD_RELOC_NIOS2_TLS_DTPMOD
   2627       || fixp->fx_r_type == BFD_RELOC_NIOS2_TLS_DTPREL
   2628       || fixp->fx_r_type == BFD_RELOC_NIOS2_TLS_TPREL
   2629       || fixp->fx_r_type == BFD_RELOC_NIOS2_GOTOFF
   2630       || fixp->fx_r_type == BFD_RELOC_NIOS2_GOT_LO
   2631       || fixp->fx_r_type == BFD_RELOC_NIOS2_GOT_HA
   2632       || fixp->fx_r_type == BFD_RELOC_NIOS2_CALL_LO
   2633       || fixp->fx_r_type == BFD_RELOC_NIOS2_CALL_HA
   2634       )
   2635     return 0;
   2636 
   2637   return 1;
   2638 }
   2639 
   2640 /* Implement tc_frob_symbol.  This is called in adjust_reloc_syms;
   2641    it is used to remove *ABS* references from the symbol table.  */
   2642 int
   2643 nios2_frob_symbol (symbolS *symp)
   2644 {
   2645   if ((OUTPUT_FLAVOR == bfd_target_elf_flavour
   2646        && symp == section_symbol (absolute_section))
   2647       || !S_IS_DEFINED (symp))
   2648     return 1;
   2649   else
   2650     return 0;
   2651 }
   2652 
   2653 /* The function tc_gen_reloc creates a relocation structure for the
   2654    fixup fixp, and returns a pointer to it.  This structure is passed
   2655    to bfd_install_relocation so that it can be written to the object
   2656    file for linking.  */
   2657 arelent *
   2658 tc_gen_reloc (asection *section ATTRIBUTE_UNUSED, fixS *fixp)
   2659 {
   2660   arelent *reloc = (arelent *) xmalloc (sizeof (arelent));
   2661   reloc->sym_ptr_ptr = (asymbol **) xmalloc (sizeof (asymbol *));
   2662   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
   2663 
   2664   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
   2665   reloc->addend = fixp->fx_offset;  /* fixp->fx_addnumber; */
   2666 
   2667   if (fixp->fx_pcrel)
   2668     {
   2669       switch (fixp->fx_r_type)
   2670 	{
   2671 	case BFD_RELOC_16:
   2672 	  fixp->fx_r_type = BFD_RELOC_16_PCREL;
   2673 	  break;
   2674 	case BFD_RELOC_NIOS2_LO16:
   2675 	  fixp->fx_r_type = BFD_RELOC_NIOS2_PCREL_LO;
   2676 	  break;
   2677 	case BFD_RELOC_NIOS2_HIADJ16:
   2678 	  fixp->fx_r_type = BFD_RELOC_NIOS2_PCREL_HA;
   2679 	  break;
   2680 	default:
   2681 	  break;
   2682 	}
   2683     }
   2684 
   2685   reloc->howto = bfd_reloc_type_lookup (stdoutput, fixp->fx_r_type);
   2686   if (reloc->howto == NULL)
   2687     {
   2688       as_bad_where (fixp->fx_file, fixp->fx_line,
   2689 		    _("can't represent relocation type %s"),
   2690 		    bfd_get_reloc_code_name (fixp->fx_r_type));
   2691 
   2692       /* Set howto to a garbage value so that we can keep going.  */
   2693       reloc->howto = bfd_reloc_type_lookup (stdoutput, BFD_RELOC_32);
   2694       gas_assert (reloc->howto != NULL);
   2695     }
   2696   return reloc;
   2697 }
   2698 
   2699 long
   2700 md_pcrel_from (fixS *fixP ATTRIBUTE_UNUSED)
   2701 {
   2702   return 0;
   2703 }
   2704 
   2705 /* Called just before the assembler exits.  */
   2706 void
   2707 md_end ()
   2708 {
   2709   /* FIXME - not yet implemented */
   2710 }
   2711 
   2712 /* Under ELF we need to default _GLOBAL_OFFSET_TABLE.
   2713    Otherwise we have no need to default values of symbols.  */
   2714 symbolS *
   2715 md_undefined_symbol (char *name ATTRIBUTE_UNUSED)
   2716 {
   2717 #ifdef OBJ_ELF
   2718   if (name[0] == '_' && name[1] == 'G'
   2719       && strcmp (name, GLOBAL_OFFSET_TABLE_NAME) == 0)
   2720     {
   2721       if (!GOT_symbol)
   2722 	{
   2723 	  if (symbol_find (name))
   2724 	    as_bad ("GOT already in the symbol table");
   2725 
   2726 	  GOT_symbol = symbol_new (name, undefined_section,
   2727 				   (valueT) 0, &zero_address_frag);
   2728 	}
   2729 
   2730       return GOT_symbol;
   2731     }
   2732 #endif
   2733 
   2734   return 0;
   2735 }
   2736 
   2737 /* Implement tc_frob_label.  */
   2738 void
   2739 nios2_frob_label (symbolS *lab)
   2740 {
   2741   /* Emit dwarf information.  */
   2742   dwarf2_emit_label (lab);
   2743 
   2744   /* Update the label's address with the current output pointer.  */
   2745   symbol_set_frag (lab, frag_now);
   2746   S_SET_VALUE (lab, (valueT) frag_now_fix ());
   2747 
   2748   /* Record this label for future adjustment after we find out what
   2749      kind of data it references, and the required alignment therewith.  */
   2750   nios2_last_label = lab;
   2751 }
   2752 
   2753 /* Implement md_cons_align.  */
   2754 void
   2755 nios2_cons_align (int size)
   2756 {
   2757   int log_size = 0;
   2758   const char *pfill = NULL;
   2759 
   2760   while ((size >>= 1) != 0)
   2761     ++log_size;
   2762 
   2763   if (subseg_text_p (now_seg))
   2764     pfill = (const char *) &nop;
   2765   else
   2766     pfill = NULL;
   2767 
   2768   if (nios2_auto_align_on)
   2769     nios2_align (log_size, pfill, NULL);
   2770 
   2771   nios2_last_label = NULL;
   2772 }
   2773 
   2774 /* Map 's' to SHF_NIOS2_GPREL.  */
   2775 /* This is from the Alpha code tc-alpha.c.  */
   2776 int
   2777 nios2_elf_section_letter (int letter, char **ptr_msg)
   2778 {
   2779   if (letter == 's')
   2780     return SHF_NIOS2_GPREL;
   2781 
   2782   *ptr_msg = _("Bad .section directive: want a,s,w,x,M,S,G,T in string");
   2783   return -1;
   2784 }
   2785 
   2786 /* Map SHF_ALPHA_GPREL to SEC_SMALL_DATA.  */
   2787 /* This is from the Alpha code tc-alpha.c.  */
   2788 flagword
   2789 nios2_elf_section_flags (flagword flags, int attr, int type ATTRIBUTE_UNUSED)
   2790 {
   2791   if (attr & SHF_NIOS2_GPREL)
   2792     flags |= SEC_SMALL_DATA;
   2793   return flags;
   2794 }
   2795 
   2796 /* Implement TC_PARSE_CONS_EXPRESSION to handle %tls_ldo(...) */
   2797 bfd_reloc_code_real_type
   2798 nios2_cons (expressionS *exp, int size)
   2799 {
   2800   bfd_reloc_code_real_type nios2_tls_ldo_reloc = BFD_RELOC_NONE;
   2801 
   2802   SKIP_WHITESPACE ();
   2803   if (input_line_pointer[0] == '%')
   2804     {
   2805       if (strprefix (input_line_pointer + 1, "tls_ldo"))
   2806 	{
   2807 	  if (size != 4)
   2808 	    as_bad (_("Illegal operands: %%tls_ldo in %d-byte data field"),
   2809 		    size);
   2810 	  else
   2811 	    {
   2812 	      input_line_pointer += 8;
   2813 	      nios2_tls_ldo_reloc = BFD_RELOC_NIOS2_TLS_DTPREL;
   2814 	    }
   2815 	}
   2816       if (nios2_tls_ldo_reloc != BFD_RELOC_NONE)
   2817 	{
   2818 	  SKIP_WHITESPACE ();
   2819 	  if (input_line_pointer[0] != '(')
   2820 	    as_bad (_("Illegal operands: %%tls_ldo requires arguments in ()"));
   2821 	  else
   2822 	    {
   2823 	      int c;
   2824 	      char *end = ++input_line_pointer;
   2825 	      int npar = 0;
   2826 
   2827 	      for (c = *end; !is_end_of_line[c]; end++, c = *end)
   2828 		if (c == '(')
   2829 		  npar++;
   2830 		else if (c == ')')
   2831 		  {
   2832 		    if (!npar)
   2833 		      break;
   2834 		    npar--;
   2835 		  }
   2836 
   2837 	      if (c != ')')
   2838 		as_bad (_("Illegal operands: %%tls_ldo requires arguments in ()"));
   2839 	      else
   2840 		{
   2841 		  *end = '\0';
   2842 		  expression (exp);
   2843 		  *end = c;
   2844 		  if (input_line_pointer != end)
   2845 		    as_bad (_("Illegal operands: %%tls_ldo requires arguments in ()"));
   2846 		  else
   2847 		    {
   2848 		      input_line_pointer++;
   2849 		      SKIP_WHITESPACE ();
   2850 		      c = *input_line_pointer;
   2851 		      if (! is_end_of_line[c] && c != ',')
   2852 			as_bad (_("Illegal operands: garbage after %%tls_ldo()"));
   2853 		    }
   2854 		}
   2855 	    }
   2856 	}
   2857     }
   2858   if (nios2_tls_ldo_reloc == BFD_RELOC_NONE)
   2859     expression (exp);
   2860   return nios2_tls_ldo_reloc;
   2861 }
   2862 
   2863 /* Implement HANDLE_ALIGN.  */
   2864 void
   2865 nios2_handle_align (fragS *fragp)
   2866 {
   2867   /* If we are expecting to relax in the linker, then we must output a
   2868      relocation to tell the linker we are aligning code.  */
   2869   if (nios2_as_options.relax == relax_all
   2870       && (fragp->fr_type == rs_align || fragp->fr_type == rs_align_code)
   2871       && fragp->fr_address + fragp->fr_fix > 0
   2872       && fragp->fr_offset > 1
   2873       && now_seg != bss_section)
   2874     fix_new (fragp, fragp->fr_fix, 0, &abs_symbol, fragp->fr_offset, 0,
   2875 	     BFD_RELOC_NIOS2_ALIGN);
   2876 }
   2877 
   2878 /* Implement tc_regname_to_dw2regnum, to convert REGNAME to a DWARF-2
   2879    register number.  */
   2880 int
   2881 nios2_regname_to_dw2regnum (char *regname)
   2882 {
   2883   struct nios2_reg *r = nios2_reg_lookup (regname);
   2884   if (r == NULL)
   2885     return -1;
   2886   return r->index;
   2887 }
   2888 
   2889 /* Implement tc_cfi_frame_initial_instructions, to initialize the DWARF-2
   2890    unwind information for this procedure.  */
   2891 void
   2892 nios2_frame_initial_instructions (void)
   2893 {
   2894   cfi_add_CFA_def_cfa (27, 0);
   2895 }
   2896