]> Git Repo - binutils.git/blob - gas/config/tc-aarch64.c
Add support for AArch64 system register names IP0, IP1, FP and LR.
[binutils.git] / gas / config / tc-aarch64.c
1 /* tc-aarch64.c -- Assemble for the AArch64 ISA
2
3    Copyright (C) 2009-2017 Free Software Foundation, Inc.
4    Contributed by ARM Ltd.
5
6    This file is part of GAS.
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 of the license, or
11    (at your option) 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 this program; see the file COPYING3. If not,
20    see <http://www.gnu.org/licenses/>.  */
21
22 #include "as.h"
23 #include <limits.h>
24 #include <stdarg.h>
25 #include "bfd_stdint.h"
26 #define  NO_RELOC 0
27 #include "safe-ctype.h"
28 #include "subsegs.h"
29 #include "obstack.h"
30
31 #ifdef OBJ_ELF
32 #include "elf/aarch64.h"
33 #include "dw2gencfi.h"
34 #endif
35
36 #include "dwarf2dbg.h"
37
38 /* Types of processor to assemble for.  */
39 #ifndef CPU_DEFAULT
40 #define CPU_DEFAULT AARCH64_ARCH_V8
41 #endif
42
43 #define streq(a, b)           (strcmp (a, b) == 0)
44
45 #define END_OF_INSN '\0'
46
47 static aarch64_feature_set cpu_variant;
48
49 /* Variables that we set while parsing command-line options.  Once all
50    options have been read we re-process these values to set the real
51    assembly flags.  */
52 static const aarch64_feature_set *mcpu_cpu_opt = NULL;
53 static const aarch64_feature_set *march_cpu_opt = NULL;
54
55 /* Constants for known architecture features.  */
56 static const aarch64_feature_set cpu_default = CPU_DEFAULT;
57
58 #ifdef OBJ_ELF
59 /* Pre-defined "_GLOBAL_OFFSET_TABLE_"  */
60 static symbolS *GOT_symbol;
61
62 /* Which ABI to use.  */
63 enum aarch64_abi_type
64 {
65   AARCH64_ABI_NONE = 0,
66   AARCH64_ABI_LP64 = 1,
67   AARCH64_ABI_ILP32 = 2
68 };
69
70 #ifndef DEFAULT_ARCH
71 #define DEFAULT_ARCH "aarch64"
72 #endif
73
74 /* DEFAULT_ARCH is initialized in gas/configure.tgt.  */
75 static const char *default_arch = DEFAULT_ARCH;
76
77 /* AArch64 ABI for the output file.  */
78 static enum aarch64_abi_type aarch64_abi = AARCH64_ABI_NONE;
79
80 /* When non-zero, program to a 32-bit model, in which the C data types
81    int, long and all pointer types are 32-bit objects (ILP32); or to a
82    64-bit model, in which the C int type is 32-bits but the C long type
83    and all pointer types are 64-bit objects (LP64).  */
84 #define ilp32_p         (aarch64_abi == AARCH64_ABI_ILP32)
85 #endif
86
87 enum vector_el_type
88 {
89   NT_invtype = -1,
90   NT_b,
91   NT_h,
92   NT_s,
93   NT_d,
94   NT_q,
95   NT_zero,
96   NT_merge
97 };
98
99 /* Bits for DEFINED field in vector_type_el.  */
100 #define NTA_HASTYPE     1
101 #define NTA_HASINDEX    2
102 #define NTA_HASVARWIDTH 4
103
104 struct vector_type_el
105 {
106   enum vector_el_type type;
107   unsigned char defined;
108   unsigned width;
109   int64_t index;
110 };
111
112 #define FIXUP_F_HAS_EXPLICIT_SHIFT      0x00000001
113
114 struct reloc
115 {
116   bfd_reloc_code_real_type type;
117   expressionS exp;
118   int pc_rel;
119   enum aarch64_opnd opnd;
120   uint32_t flags;
121   unsigned need_libopcodes_p : 1;
122 };
123
124 struct aarch64_instruction
125 {
126   /* libopcodes structure for instruction intermediate representation.  */
127   aarch64_inst base;
128   /* Record assembly errors found during the parsing.  */
129   struct
130     {
131       enum aarch64_operand_error_kind kind;
132       const char *error;
133     } parsing_error;
134   /* The condition that appears in the assembly line.  */
135   int cond;
136   /* Relocation information (including the GAS internal fixup).  */
137   struct reloc reloc;
138   /* Need to generate an immediate in the literal pool.  */
139   unsigned gen_lit_pool : 1;
140 };
141
142 typedef struct aarch64_instruction aarch64_instruction;
143
144 static aarch64_instruction inst;
145
146 static bfd_boolean parse_operands (char *, const aarch64_opcode *);
147 static bfd_boolean programmer_friendly_fixup (aarch64_instruction *);
148
149 /* Diagnostics inline function utilities.
150
151    These are lightweight utilities which should only be called by parse_operands
152    and other parsers.  GAS processes each assembly line by parsing it against
153    instruction template(s), in the case of multiple templates (for the same
154    mnemonic name), those templates are tried one by one until one succeeds or
155    all fail.  An assembly line may fail a few templates before being
156    successfully parsed; an error saved here in most cases is not a user error
157    but an error indicating the current template is not the right template.
158    Therefore it is very important that errors can be saved at a low cost during
159    the parsing; we don't want to slow down the whole parsing by recording
160    non-user errors in detail.
161
162    Remember that the objective is to help GAS pick up the most appropriate
163    error message in the case of multiple templates, e.g. FMOV which has 8
164    templates.  */
165
166 static inline void
167 clear_error (void)
168 {
169   inst.parsing_error.kind = AARCH64_OPDE_NIL;
170   inst.parsing_error.error = NULL;
171 }
172
173 static inline bfd_boolean
174 error_p (void)
175 {
176   return inst.parsing_error.kind != AARCH64_OPDE_NIL;
177 }
178
179 static inline const char *
180 get_error_message (void)
181 {
182   return inst.parsing_error.error;
183 }
184
185 static inline enum aarch64_operand_error_kind
186 get_error_kind (void)
187 {
188   return inst.parsing_error.kind;
189 }
190
191 static inline void
192 set_error (enum aarch64_operand_error_kind kind, const char *error)
193 {
194   inst.parsing_error.kind = kind;
195   inst.parsing_error.error = error;
196 }
197
198 static inline void
199 set_recoverable_error (const char *error)
200 {
201   set_error (AARCH64_OPDE_RECOVERABLE, error);
202 }
203
204 /* Use the DESC field of the corresponding aarch64_operand entry to compose
205    the error message.  */
206 static inline void
207 set_default_error (void)
208 {
209   set_error (AARCH64_OPDE_SYNTAX_ERROR, NULL);
210 }
211
212 static inline void
213 set_syntax_error (const char *error)
214 {
215   set_error (AARCH64_OPDE_SYNTAX_ERROR, error);
216 }
217
218 static inline void
219 set_first_syntax_error (const char *error)
220 {
221   if (! error_p ())
222     set_error (AARCH64_OPDE_SYNTAX_ERROR, error);
223 }
224
225 static inline void
226 set_fatal_syntax_error (const char *error)
227 {
228   set_error (AARCH64_OPDE_FATAL_SYNTAX_ERROR, error);
229 }
230 \f
231 /* Number of littlenums required to hold an extended precision number.  */
232 #define MAX_LITTLENUMS 6
233
234 /* Return value for certain parsers when the parsing fails; those parsers
235    return the information of the parsed result, e.g. register number, on
236    success.  */
237 #define PARSE_FAIL -1
238
239 /* This is an invalid condition code that means no conditional field is
240    present. */
241 #define COND_ALWAYS 0x10
242
243 typedef struct
244 {
245   const char *template;
246   unsigned long value;
247 } asm_barrier_opt;
248
249 typedef struct
250 {
251   const char *template;
252   uint32_t value;
253 } asm_nzcv;
254
255 struct reloc_entry
256 {
257   char *name;
258   bfd_reloc_code_real_type reloc;
259 };
260
261 /* Macros to define the register types and masks for the purpose
262    of parsing.  */
263
264 #undef AARCH64_REG_TYPES
265 #define AARCH64_REG_TYPES       \
266   BASIC_REG_TYPE(R_32)  /* w[0-30] */   \
267   BASIC_REG_TYPE(R_64)  /* x[0-30] */   \
268   BASIC_REG_TYPE(SP_32) /* wsp     */   \
269   BASIC_REG_TYPE(SP_64) /* sp      */   \
270   BASIC_REG_TYPE(Z_32)  /* wzr     */   \
271   BASIC_REG_TYPE(Z_64)  /* xzr     */   \
272   BASIC_REG_TYPE(FP_B)  /* b[0-31] *//* NOTE: keep FP_[BHSDQ] consecutive! */\
273   BASIC_REG_TYPE(FP_H)  /* h[0-31] */   \
274   BASIC_REG_TYPE(FP_S)  /* s[0-31] */   \
275   BASIC_REG_TYPE(FP_D)  /* d[0-31] */   \
276   BASIC_REG_TYPE(FP_Q)  /* q[0-31] */   \
277   BASIC_REG_TYPE(VN)    /* v[0-31] */   \
278   BASIC_REG_TYPE(ZN)    /* z[0-31] */   \
279   BASIC_REG_TYPE(PN)    /* p[0-15] */   \
280   /* Typecheck: any 64-bit int reg         (inc SP exc XZR).  */        \
281   MULTI_REG_TYPE(R64_SP, REG_TYPE(R_64) | REG_TYPE(SP_64))              \
282   /* Typecheck: same, plus SVE registers.  */                           \
283   MULTI_REG_TYPE(SVE_BASE, REG_TYPE(R_64) | REG_TYPE(SP_64)             \
284                  | REG_TYPE(ZN))                                        \
285   /* Typecheck: x[0-30], w[0-30] or [xw]zr.  */                         \
286   MULTI_REG_TYPE(R_Z, REG_TYPE(R_32) | REG_TYPE(R_64)                   \
287                  | REG_TYPE(Z_32) | REG_TYPE(Z_64))                     \
288   /* Typecheck: same, plus SVE registers.  */                           \
289   MULTI_REG_TYPE(SVE_OFFSET, REG_TYPE(R_32) | REG_TYPE(R_64)            \
290                  | REG_TYPE(Z_32) | REG_TYPE(Z_64)                      \
291                  | REG_TYPE(ZN))                                        \
292   /* Typecheck: x[0-30], w[0-30] or {w}sp.  */                          \
293   MULTI_REG_TYPE(R_SP, REG_TYPE(R_32) | REG_TYPE(R_64)                  \
294                  | REG_TYPE(SP_32) | REG_TYPE(SP_64))                   \
295   /* Typecheck: any int                    (inc {W}SP inc [WX]ZR).  */  \
296   MULTI_REG_TYPE(R_Z_SP, REG_TYPE(R_32) | REG_TYPE(R_64)                \
297                  | REG_TYPE(SP_32) | REG_TYPE(SP_64)                    \
298                  | REG_TYPE(Z_32) | REG_TYPE(Z_64))                     \
299   /* Typecheck: any [BHSDQ]P FP.  */                                    \
300   MULTI_REG_TYPE(BHSDQ, REG_TYPE(FP_B) | REG_TYPE(FP_H)                 \
301                  | REG_TYPE(FP_S) | REG_TYPE(FP_D) | REG_TYPE(FP_Q))    \
302   /* Typecheck: any int or [BHSDQ]P FP or V reg (exc SP inc [WX]ZR).  */ \
303   MULTI_REG_TYPE(R_Z_BHSDQ_V, REG_TYPE(R_32) | REG_TYPE(R_64)           \
304                  | REG_TYPE(Z_32) | REG_TYPE(Z_64) | REG_TYPE(VN)       \
305                  | REG_TYPE(FP_B) | REG_TYPE(FP_H)                      \
306                  | REG_TYPE(FP_S) | REG_TYPE(FP_D) | REG_TYPE(FP_Q))    \
307   /* Typecheck: as above, but also Zn and Pn.  This should only be      \
308      used for SVE instructions, since Zn and Pn are valid symbols       \
309      in other contexts.  */                                             \
310   MULTI_REG_TYPE(R_Z_BHSDQ_VZP, REG_TYPE(R_32) | REG_TYPE(R_64)         \
311                  | REG_TYPE(Z_32) | REG_TYPE(Z_64) | REG_TYPE(VN)       \
312                  | REG_TYPE(FP_B) | REG_TYPE(FP_H)                      \
313                  | REG_TYPE(FP_S) | REG_TYPE(FP_D) | REG_TYPE(FP_Q)     \
314                  | REG_TYPE(ZN) | REG_TYPE(PN))                         \
315   /* Any integer register; used for error messages only.  */            \
316   MULTI_REG_TYPE(R_N, REG_TYPE(R_32) | REG_TYPE(R_64)                   \
317                  | REG_TYPE(SP_32) | REG_TYPE(SP_64)                    \
318                  | REG_TYPE(Z_32) | REG_TYPE(Z_64))                     \
319   /* Pseudo type to mark the end of the enumerator sequence.  */        \
320   BASIC_REG_TYPE(MAX)
321
322 #undef BASIC_REG_TYPE
323 #define BASIC_REG_TYPE(T)       REG_TYPE_##T,
324 #undef MULTI_REG_TYPE
325 #define MULTI_REG_TYPE(T,V)     BASIC_REG_TYPE(T)
326
327 /* Register type enumerators.  */
328 typedef enum aarch64_reg_type_
329 {
330   /* A list of REG_TYPE_*.  */
331   AARCH64_REG_TYPES
332 } aarch64_reg_type;
333
334 #undef BASIC_REG_TYPE
335 #define BASIC_REG_TYPE(T)       1 << REG_TYPE_##T,
336 #undef REG_TYPE
337 #define REG_TYPE(T)             (1 << REG_TYPE_##T)
338 #undef MULTI_REG_TYPE
339 #define MULTI_REG_TYPE(T,V)     V,
340
341 /* Structure for a hash table entry for a register.  */
342 typedef struct
343 {
344   const char *name;
345   unsigned char number;
346   ENUM_BITFIELD (aarch64_reg_type_) type : 8;
347   unsigned char builtin;
348 } reg_entry;
349
350 /* Values indexed by aarch64_reg_type to assist the type checking.  */
351 static const unsigned reg_type_masks[] =
352 {
353   AARCH64_REG_TYPES
354 };
355
356 #undef BASIC_REG_TYPE
357 #undef REG_TYPE
358 #undef MULTI_REG_TYPE
359 #undef AARCH64_REG_TYPES
360
361 /* Diagnostics used when we don't get a register of the expected type.
362    Note:  this has to synchronized with aarch64_reg_type definitions
363    above.  */
364 static const char *
365 get_reg_expected_msg (aarch64_reg_type reg_type)
366 {
367   const char *msg;
368
369   switch (reg_type)
370     {
371     case REG_TYPE_R_32:
372       msg = N_("integer 32-bit register expected");
373       break;
374     case REG_TYPE_R_64:
375       msg = N_("integer 64-bit register expected");
376       break;
377     case REG_TYPE_R_N:
378       msg = N_("integer register expected");
379       break;
380     case REG_TYPE_R64_SP:
381       msg = N_("64-bit integer or SP register expected");
382       break;
383     case REG_TYPE_SVE_BASE:
384       msg = N_("base register expected");
385       break;
386     case REG_TYPE_R_Z:
387       msg = N_("integer or zero register expected");
388       break;
389     case REG_TYPE_SVE_OFFSET:
390       msg = N_("offset register expected");
391       break;
392     case REG_TYPE_R_SP:
393       msg = N_("integer or SP register expected");
394       break;
395     case REG_TYPE_R_Z_SP:
396       msg = N_("integer, zero or SP register expected");
397       break;
398     case REG_TYPE_FP_B:
399       msg = N_("8-bit SIMD scalar register expected");
400       break;
401     case REG_TYPE_FP_H:
402       msg = N_("16-bit SIMD scalar or floating-point half precision "
403                "register expected");
404       break;
405     case REG_TYPE_FP_S:
406       msg = N_("32-bit SIMD scalar or floating-point single precision "
407                "register expected");
408       break;
409     case REG_TYPE_FP_D:
410       msg = N_("64-bit SIMD scalar or floating-point double precision "
411                "register expected");
412       break;
413     case REG_TYPE_FP_Q:
414       msg = N_("128-bit SIMD scalar or floating-point quad precision "
415                "register expected");
416       break;
417     case REG_TYPE_R_Z_BHSDQ_V:
418     case REG_TYPE_R_Z_BHSDQ_VZP:
419       msg = N_("register expected");
420       break;
421     case REG_TYPE_BHSDQ:        /* any [BHSDQ]P FP  */
422       msg = N_("SIMD scalar or floating-point register expected");
423       break;
424     case REG_TYPE_VN:           /* any V reg  */
425       msg = N_("vector register expected");
426       break;
427     case REG_TYPE_ZN:
428       msg = N_("SVE vector register expected");
429       break;
430     case REG_TYPE_PN:
431       msg = N_("SVE predicate register expected");
432       break;
433     default:
434       as_fatal (_("invalid register type %d"), reg_type);
435     }
436   return msg;
437 }
438
439 /* Some well known registers that we refer to directly elsewhere.  */
440 #define REG_SP  31
441
442 /* Instructions take 4 bytes in the object file.  */
443 #define INSN_SIZE       4
444
445 static struct hash_control *aarch64_ops_hsh;
446 static struct hash_control *aarch64_cond_hsh;
447 static struct hash_control *aarch64_shift_hsh;
448 static struct hash_control *aarch64_sys_regs_hsh;
449 static struct hash_control *aarch64_pstatefield_hsh;
450 static struct hash_control *aarch64_sys_regs_ic_hsh;
451 static struct hash_control *aarch64_sys_regs_dc_hsh;
452 static struct hash_control *aarch64_sys_regs_at_hsh;
453 static struct hash_control *aarch64_sys_regs_tlbi_hsh;
454 static struct hash_control *aarch64_reg_hsh;
455 static struct hash_control *aarch64_barrier_opt_hsh;
456 static struct hash_control *aarch64_nzcv_hsh;
457 static struct hash_control *aarch64_pldop_hsh;
458 static struct hash_control *aarch64_hint_opt_hsh;
459
460 /* Stuff needed to resolve the label ambiguity
461    As:
462      ...
463      label:   <insn>
464    may differ from:
465      ...
466      label:
467               <insn>  */
468
469 static symbolS *last_label_seen;
470
471 /* Literal pool structure.  Held on a per-section
472    and per-sub-section basis.  */
473
474 #define MAX_LITERAL_POOL_SIZE 1024
475 typedef struct literal_expression
476 {
477   expressionS exp;
478   /* If exp.op == O_big then this bignum holds a copy of the global bignum value.  */
479   LITTLENUM_TYPE * bignum;
480 } literal_expression;
481
482 typedef struct literal_pool
483 {
484   literal_expression literals[MAX_LITERAL_POOL_SIZE];
485   unsigned int next_free_entry;
486   unsigned int id;
487   symbolS *symbol;
488   segT section;
489   subsegT sub_section;
490   int size;
491   struct literal_pool *next;
492 } literal_pool;
493
494 /* Pointer to a linked list of literal pools.  */
495 static literal_pool *list_of_pools = NULL;
496 \f
497 /* Pure syntax.  */
498
499 /* This array holds the chars that always start a comment.  If the
500    pre-processor is disabled, these aren't very useful.  */
501 const char comment_chars[] = "";
502
503 /* This array holds the chars that only start a comment at the beginning of
504    a line.  If the line seems to have the form '# 123 filename'
505    .line and .file directives will appear in the pre-processed output.  */
506 /* Note that input_file.c hand checks for '#' at the beginning of the
507    first line of the input file.  This is because the compiler outputs
508    #NO_APP at the beginning of its output.  */
509 /* Also note that comments like this one will always work.  */
510 const char line_comment_chars[] = "#";
511
512 const char line_separator_chars[] = ";";
513
514 /* Chars that can be used to separate mant
515    from exp in floating point numbers.  */
516 const char EXP_CHARS[] = "eE";
517
518 /* Chars that mean this number is a floating point constant.  */
519 /* As in 0f12.456  */
520 /* or    0d1.2345e12  */
521
522 const char FLT_CHARS[] = "rRsSfFdDxXeEpP";
523
524 /* Prefix character that indicates the start of an immediate value.  */
525 #define is_immediate_prefix(C) ((C) == '#')
526
527 /* Separator character handling.  */
528
529 #define skip_whitespace(str)  do { if (*(str) == ' ') ++(str); } while (0)
530
531 static inline bfd_boolean
532 skip_past_char (char **str, char c)
533 {
534   if (**str == c)
535     {
536       (*str)++;
537       return TRUE;
538     }
539   else
540     return FALSE;
541 }
542
543 #define skip_past_comma(str) skip_past_char (str, ',')
544
545 /* Arithmetic expressions (possibly involving symbols).  */
546
547 static bfd_boolean in_my_get_expression_p = FALSE;
548
549 /* Third argument to my_get_expression.  */
550 #define GE_NO_PREFIX 0
551 #define GE_OPT_PREFIX 1
552
553 /* Return TRUE if the string pointed by *STR is successfully parsed
554    as an valid expression; *EP will be filled with the information of
555    such an expression.  Otherwise return FALSE.  */
556
557 static bfd_boolean
558 my_get_expression (expressionS * ep, char **str, int prefix_mode,
559                    int reject_absent)
560 {
561   char *save_in;
562   segT seg;
563   int prefix_present_p = 0;
564
565   switch (prefix_mode)
566     {
567     case GE_NO_PREFIX:
568       break;
569     case GE_OPT_PREFIX:
570       if (is_immediate_prefix (**str))
571         {
572           (*str)++;
573           prefix_present_p = 1;
574         }
575       break;
576     default:
577       abort ();
578     }
579
580   memset (ep, 0, sizeof (expressionS));
581
582   save_in = input_line_pointer;
583   input_line_pointer = *str;
584   in_my_get_expression_p = TRUE;
585   seg = expression (ep);
586   in_my_get_expression_p = FALSE;
587
588   if (ep->X_op == O_illegal || (reject_absent && ep->X_op == O_absent))
589     {
590       /* We found a bad expression in md_operand().  */
591       *str = input_line_pointer;
592       input_line_pointer = save_in;
593       if (prefix_present_p && ! error_p ())
594         set_fatal_syntax_error (_("bad expression"));
595       else
596         set_first_syntax_error (_("bad expression"));
597       return FALSE;
598     }
599
600 #ifdef OBJ_AOUT
601   if (seg != absolute_section
602       && seg != text_section
603       && seg != data_section
604       && seg != bss_section && seg != undefined_section)
605     {
606       set_syntax_error (_("bad segment"));
607       *str = input_line_pointer;
608       input_line_pointer = save_in;
609       return FALSE;
610     }
611 #else
612   (void) seg;
613 #endif
614
615   *str = input_line_pointer;
616   input_line_pointer = save_in;
617   return TRUE;
618 }
619
620 /* Turn a string in input_line_pointer into a floating point constant
621    of type TYPE, and store the appropriate bytes in *LITP.  The number
622    of LITTLENUMS emitted is stored in *SIZEP.  An error message is
623    returned, or NULL on OK.  */
624
625 const char *
626 md_atof (int type, char *litP, int *sizeP)
627 {
628   return ieee_md_atof (type, litP, sizeP, target_big_endian);
629 }
630
631 /* We handle all bad expressions here, so that we can report the faulty
632    instruction in the error message.  */
633 void
634 md_operand (expressionS * exp)
635 {
636   if (in_my_get_expression_p)
637     exp->X_op = O_illegal;
638 }
639
640 /* Immediate values.  */
641
642 /* Errors may be set multiple times during parsing or bit encoding
643    (particularly in the Neon bits), but usually the earliest error which is set
644    will be the most meaningful. Avoid overwriting it with later (cascading)
645    errors by calling this function.  */
646
647 static void
648 first_error (const char *error)
649 {
650   if (! error_p ())
651     set_syntax_error (error);
652 }
653
654 /* Similar to first_error, but this function accepts formatted error
655    message.  */
656 static void
657 first_error_fmt (const char *format, ...)
658 {
659   va_list args;
660   enum
661   { size = 100 };
662   /* N.B. this single buffer will not cause error messages for different
663      instructions to pollute each other; this is because at the end of
664      processing of each assembly line, error message if any will be
665      collected by as_bad.  */
666   static char buffer[size];
667
668   if (! error_p ())
669     {
670       int ret ATTRIBUTE_UNUSED;
671       va_start (args, format);
672       ret = vsnprintf (buffer, size, format, args);
673       know (ret <= size - 1 && ret >= 0);
674       va_end (args);
675       set_syntax_error (buffer);
676     }
677 }
678
679 /* Register parsing.  */
680
681 /* Generic register parser which is called by other specialized
682    register parsers.
683    CCP points to what should be the beginning of a register name.
684    If it is indeed a valid register name, advance CCP over it and
685    return the reg_entry structure; otherwise return NULL.
686    It does not issue diagnostics.  */
687
688 static reg_entry *
689 parse_reg (char **ccp)
690 {
691   char *start = *ccp;
692   char *p;
693   reg_entry *reg;
694
695 #ifdef REGISTER_PREFIX
696   if (*start != REGISTER_PREFIX)
697     return NULL;
698   start++;
699 #endif
700
701   p = start;
702   if (!ISALPHA (*p) || !is_name_beginner (*p))
703     return NULL;
704
705   do
706     p++;
707   while (ISALPHA (*p) || ISDIGIT (*p) || *p == '_');
708
709   reg = (reg_entry *) hash_find_n (aarch64_reg_hsh, start, p - start);
710
711   if (!reg)
712     return NULL;
713
714   *ccp = p;
715   return reg;
716 }
717
718 /* Return TRUE if REG->TYPE is a valid type of TYPE; otherwise
719    return FALSE.  */
720 static bfd_boolean
721 aarch64_check_reg_type (const reg_entry *reg, aarch64_reg_type type)
722 {
723   return (reg_type_masks[type] & (1 << reg->type)) != 0;
724 }
725
726 /* Try to parse a base or offset register.  Allow SVE base and offset
727    registers if REG_TYPE includes SVE registers.  Return the register
728    entry on success, setting *QUALIFIER to the register qualifier.
729    Return null otherwise.
730
731    Note that this function does not issue any diagnostics.  */
732
733 static const reg_entry *
734 aarch64_addr_reg_parse (char **ccp, aarch64_reg_type reg_type,
735                         aarch64_opnd_qualifier_t *qualifier)
736 {
737   char *str = *ccp;
738   const reg_entry *reg = parse_reg (&str);
739
740   if (reg == NULL)
741     return NULL;
742
743   switch (reg->type)
744     {
745     case REG_TYPE_R_32:
746     case REG_TYPE_SP_32:
747     case REG_TYPE_Z_32:
748       *qualifier = AARCH64_OPND_QLF_W;
749       break;
750
751     case REG_TYPE_R_64:
752     case REG_TYPE_SP_64:
753     case REG_TYPE_Z_64:
754       *qualifier = AARCH64_OPND_QLF_X;
755       break;
756
757     case REG_TYPE_ZN:
758       if ((reg_type_masks[reg_type] & (1 << REG_TYPE_ZN)) == 0
759           || str[0] != '.')
760         return NULL;
761       switch (TOLOWER (str[1]))
762         {
763         case 's':
764           *qualifier = AARCH64_OPND_QLF_S_S;
765           break;
766         case 'd':
767           *qualifier = AARCH64_OPND_QLF_S_D;
768           break;
769         default:
770           return NULL;
771         }
772       str += 2;
773       break;
774
775     default:
776       return NULL;
777     }
778
779   *ccp = str;
780
781   return reg;
782 }
783
784 /* Try to parse a base or offset register.  Return the register entry
785    on success, setting *QUALIFIER to the register qualifier.  Return null
786    otherwise.
787
788    Note that this function does not issue any diagnostics.  */
789
790 static const reg_entry *
791 aarch64_reg_parse_32_64 (char **ccp, aarch64_opnd_qualifier_t *qualifier)
792 {
793   return aarch64_addr_reg_parse (ccp, REG_TYPE_R_Z_SP, qualifier);
794 }
795
796 /* Parse the qualifier of a vector register or vector element of type
797    REG_TYPE.  Fill in *PARSED_TYPE and return TRUE if the parsing
798    succeeds; otherwise return FALSE.
799
800    Accept only one occurrence of:
801    8b 16b 2h 4h 8h 2s 4s 1d 2d
802    b h s d q  */
803 static bfd_boolean
804 parse_vector_type_for_operand (aarch64_reg_type reg_type,
805                                struct vector_type_el *parsed_type, char **str)
806 {
807   char *ptr = *str;
808   unsigned width;
809   unsigned element_size;
810   enum vector_el_type type;
811
812   /* skip '.' */
813   gas_assert (*ptr == '.');
814   ptr++;
815
816   if (reg_type == REG_TYPE_ZN || reg_type == REG_TYPE_PN || !ISDIGIT (*ptr))
817     {
818       width = 0;
819       goto elt_size;
820     }
821   width = strtoul (ptr, &ptr, 10);
822   if (width != 1 && width != 2 && width != 4 && width != 8 && width != 16)
823     {
824       first_error_fmt (_("bad size %d in vector width specifier"), width);
825       return FALSE;
826     }
827
828 elt_size:
829   switch (TOLOWER (*ptr))
830     {
831     case 'b':
832       type = NT_b;
833       element_size = 8;
834       break;
835     case 'h':
836       type = NT_h;
837       element_size = 16;
838       break;
839     case 's':
840       type = NT_s;
841       element_size = 32;
842       break;
843     case 'd':
844       type = NT_d;
845       element_size = 64;
846       break;
847     case 'q':
848       if (reg_type == REG_TYPE_ZN || width == 1)
849         {
850           type = NT_q;
851           element_size = 128;
852           break;
853         }
854       /* fall through.  */
855     default:
856       if (*ptr != '\0')
857         first_error_fmt (_("unexpected character `%c' in element size"), *ptr);
858       else
859         first_error (_("missing element size"));
860       return FALSE;
861     }
862   if (width != 0 && width * element_size != 64 && width * element_size != 128
863       && !(width == 2 && element_size == 16))
864     {
865       first_error_fmt (_
866                        ("invalid element size %d and vector size combination %c"),
867                        width, *ptr);
868       return FALSE;
869     }
870   ptr++;
871
872   parsed_type->type = type;
873   parsed_type->width = width;
874
875   *str = ptr;
876
877   return TRUE;
878 }
879
880 /* *STR contains an SVE zero/merge predication suffix.  Parse it into
881    *PARSED_TYPE and point *STR at the end of the suffix.  */
882
883 static bfd_boolean
884 parse_predication_for_operand (struct vector_type_el *parsed_type, char **str)
885 {
886   char *ptr = *str;
887
888   /* Skip '/'.  */
889   gas_assert (*ptr == '/');
890   ptr++;
891   switch (TOLOWER (*ptr))
892     {
893     case 'z':
894       parsed_type->type = NT_zero;
895       break;
896     case 'm':
897       parsed_type->type = NT_merge;
898       break;
899     default:
900       if (*ptr != '\0' && *ptr != ',')
901         first_error_fmt (_("unexpected character `%c' in predication type"),
902                          *ptr);
903       else
904         first_error (_("missing predication type"));
905       return FALSE;
906     }
907   parsed_type->width = 0;
908   *str = ptr + 1;
909   return TRUE;
910 }
911
912 /* Parse a register of the type TYPE.
913
914    Return PARSE_FAIL if the string pointed by *CCP is not a valid register
915    name or the parsed register is not of TYPE.
916
917    Otherwise return the register number, and optionally fill in the actual
918    type of the register in *RTYPE when multiple alternatives were given, and
919    return the register shape and element index information in *TYPEINFO.
920
921    IN_REG_LIST should be set with TRUE if the caller is parsing a register
922    list.  */
923
924 static int
925 parse_typed_reg (char **ccp, aarch64_reg_type type, aarch64_reg_type *rtype,
926                  struct vector_type_el *typeinfo, bfd_boolean in_reg_list)
927 {
928   char *str = *ccp;
929   const reg_entry *reg = parse_reg (&str);
930   struct vector_type_el atype;
931   struct vector_type_el parsetype;
932   bfd_boolean is_typed_vecreg = FALSE;
933
934   atype.defined = 0;
935   atype.type = NT_invtype;
936   atype.width = -1;
937   atype.index = 0;
938
939   if (reg == NULL)
940     {
941       if (typeinfo)
942         *typeinfo = atype;
943       set_default_error ();
944       return PARSE_FAIL;
945     }
946
947   if (! aarch64_check_reg_type (reg, type))
948     {
949       DEBUG_TRACE ("reg type check failed");
950       set_default_error ();
951       return PARSE_FAIL;
952     }
953   type = reg->type;
954
955   if ((type == REG_TYPE_VN || type == REG_TYPE_ZN || type == REG_TYPE_PN)
956       && (*str == '.' || (type == REG_TYPE_PN && *str == '/')))
957     {
958       if (*str == '.')
959         {
960           if (!parse_vector_type_for_operand (type, &parsetype, &str))
961             return PARSE_FAIL;
962         }
963       else
964         {
965           if (!parse_predication_for_operand (&parsetype, &str))
966             return PARSE_FAIL;
967         }
968
969       /* Register if of the form Vn.[bhsdq].  */
970       is_typed_vecreg = TRUE;
971
972       if (type == REG_TYPE_ZN || type == REG_TYPE_PN)
973         {
974           /* The width is always variable; we don't allow an integer width
975              to be specified.  */
976           gas_assert (parsetype.width == 0);
977           atype.defined |= NTA_HASVARWIDTH | NTA_HASTYPE;
978         }
979       else if (parsetype.width == 0)
980         /* Expect index. In the new scheme we cannot have
981            Vn.[bhsdq] represent a scalar. Therefore any
982            Vn.[bhsdq] should have an index following it.
983            Except in reglists of course.  */
984         atype.defined |= NTA_HASINDEX;
985       else
986         atype.defined |= NTA_HASTYPE;
987
988       atype.type = parsetype.type;
989       atype.width = parsetype.width;
990     }
991
992   if (skip_past_char (&str, '['))
993     {
994       expressionS exp;
995
996       /* Reject Sn[index] syntax.  */
997       if (!is_typed_vecreg)
998         {
999           first_error (_("this type of register can't be indexed"));
1000           return PARSE_FAIL;
1001         }
1002
1003       if (in_reg_list)
1004         {
1005           first_error (_("index not allowed inside register list"));
1006           return PARSE_FAIL;
1007         }
1008
1009       atype.defined |= NTA_HASINDEX;
1010
1011       my_get_expression (&exp, &str, GE_NO_PREFIX, 1);
1012
1013       if (exp.X_op != O_constant)
1014         {
1015           first_error (_("constant expression required"));
1016           return PARSE_FAIL;
1017         }
1018
1019       if (! skip_past_char (&str, ']'))
1020         return PARSE_FAIL;
1021
1022       atype.index = exp.X_add_number;
1023     }
1024   else if (!in_reg_list && (atype.defined & NTA_HASINDEX) != 0)
1025     {
1026       /* Indexed vector register expected.  */
1027       first_error (_("indexed vector register expected"));
1028       return PARSE_FAIL;
1029     }
1030
1031   /* A vector reg Vn should be typed or indexed.  */
1032   if (type == REG_TYPE_VN && atype.defined == 0)
1033     {
1034       first_error (_("invalid use of vector register"));
1035     }
1036
1037   if (typeinfo)
1038     *typeinfo = atype;
1039
1040   if (rtype)
1041     *rtype = type;
1042
1043   *ccp = str;
1044
1045   return reg->number;
1046 }
1047
1048 /* Parse register.
1049
1050    Return the register number on success; return PARSE_FAIL otherwise.
1051
1052    If RTYPE is not NULL, return in *RTYPE the (possibly restricted) type of
1053    the register (e.g. NEON double or quad reg when either has been requested).
1054
1055    If this is a NEON vector register with additional type information, fill
1056    in the struct pointed to by VECTYPE (if non-NULL).
1057
1058    This parser does not handle register list.  */
1059
1060 static int
1061 aarch64_reg_parse (char **ccp, aarch64_reg_type type,
1062                    aarch64_reg_type *rtype, struct vector_type_el *vectype)
1063 {
1064   struct vector_type_el atype;
1065   char *str = *ccp;
1066   int reg = parse_typed_reg (&str, type, rtype, &atype,
1067                              /*in_reg_list= */ FALSE);
1068
1069   if (reg == PARSE_FAIL)
1070     return PARSE_FAIL;
1071
1072   if (vectype)
1073     *vectype = atype;
1074
1075   *ccp = str;
1076
1077   return reg;
1078 }
1079
1080 static inline bfd_boolean
1081 eq_vector_type_el (struct vector_type_el e1, struct vector_type_el e2)
1082 {
1083   return
1084     e1.type == e2.type
1085     && e1.defined == e2.defined
1086     && e1.width == e2.width && e1.index == e2.index;
1087 }
1088
1089 /* This function parses a list of vector registers of type TYPE.
1090    On success, it returns the parsed register list information in the
1091    following encoded format:
1092
1093    bit   18-22   |   13-17   |   7-11    |    2-6    |   0-1
1094        4th regno | 3rd regno | 2nd regno | 1st regno | num_of_reg
1095
1096    The information of the register shape and/or index is returned in
1097    *VECTYPE.
1098
1099    It returns PARSE_FAIL if the register list is invalid.
1100
1101    The list contains one to four registers.
1102    Each register can be one of:
1103    <Vt>.<T>[<index>]
1104    <Vt>.<T>
1105    All <T> should be identical.
1106    All <index> should be identical.
1107    There are restrictions on <Vt> numbers which are checked later
1108    (by reg_list_valid_p).  */
1109
1110 static int
1111 parse_vector_reg_list (char **ccp, aarch64_reg_type type,
1112                        struct vector_type_el *vectype)
1113 {
1114   char *str = *ccp;
1115   int nb_regs;
1116   struct vector_type_el typeinfo, typeinfo_first;
1117   int val, val_range;
1118   int in_range;
1119   int ret_val;
1120   int i;
1121   bfd_boolean error = FALSE;
1122   bfd_boolean expect_index = FALSE;
1123
1124   if (*str != '{')
1125     {
1126       set_syntax_error (_("expecting {"));
1127       return PARSE_FAIL;
1128     }
1129   str++;
1130
1131   nb_regs = 0;
1132   typeinfo_first.defined = 0;
1133   typeinfo_first.type = NT_invtype;
1134   typeinfo_first.width = -1;
1135   typeinfo_first.index = 0;
1136   ret_val = 0;
1137   val = -1;
1138   val_range = -1;
1139   in_range = 0;
1140   do
1141     {
1142       if (in_range)
1143         {
1144           str++;                /* skip over '-' */
1145           val_range = val;
1146         }
1147       val = parse_typed_reg (&str, type, NULL, &typeinfo,
1148                              /*in_reg_list= */ TRUE);
1149       if (val == PARSE_FAIL)
1150         {
1151           set_first_syntax_error (_("invalid vector register in list"));
1152           error = TRUE;
1153           continue;
1154         }
1155       /* reject [bhsd]n */
1156       if (type == REG_TYPE_VN && typeinfo.defined == 0)
1157         {
1158           set_first_syntax_error (_("invalid scalar register in list"));
1159           error = TRUE;
1160           continue;
1161         }
1162
1163       if (typeinfo.defined & NTA_HASINDEX)
1164         expect_index = TRUE;
1165
1166       if (in_range)
1167         {
1168           if (val < val_range)
1169             {
1170               set_first_syntax_error
1171                 (_("invalid range in vector register list"));
1172               error = TRUE;
1173             }
1174           val_range++;
1175         }
1176       else
1177         {
1178           val_range = val;
1179           if (nb_regs == 0)
1180             typeinfo_first = typeinfo;
1181           else if (! eq_vector_type_el (typeinfo_first, typeinfo))
1182             {
1183               set_first_syntax_error
1184                 (_("type mismatch in vector register list"));
1185               error = TRUE;
1186             }
1187         }
1188       if (! error)
1189         for (i = val_range; i <= val; i++)
1190           {
1191             ret_val |= i << (5 * nb_regs);
1192             nb_regs++;
1193           }
1194       in_range = 0;
1195     }
1196   while (skip_past_comma (&str) || (in_range = 1, *str == '-'));
1197
1198   skip_whitespace (str);
1199   if (*str != '}')
1200     {
1201       set_first_syntax_error (_("end of vector register list not found"));
1202       error = TRUE;
1203     }
1204   str++;
1205
1206   skip_whitespace (str);
1207
1208   if (expect_index)
1209     {
1210       if (skip_past_char (&str, '['))
1211         {
1212           expressionS exp;
1213
1214           my_get_expression (&exp, &str, GE_NO_PREFIX, 1);
1215           if (exp.X_op != O_constant)
1216             {
1217               set_first_syntax_error (_("constant expression required."));
1218               error = TRUE;
1219             }
1220           if (! skip_past_char (&str, ']'))
1221             error = TRUE;
1222           else
1223             typeinfo_first.index = exp.X_add_number;
1224         }
1225       else
1226         {
1227           set_first_syntax_error (_("expected index"));
1228           error = TRUE;
1229         }
1230     }
1231
1232   if (nb_regs > 4)
1233     {
1234       set_first_syntax_error (_("too many registers in vector register list"));
1235       error = TRUE;
1236     }
1237   else if (nb_regs == 0)
1238     {
1239       set_first_syntax_error (_("empty vector register list"));
1240       error = TRUE;
1241     }
1242
1243   *ccp = str;
1244   if (! error)
1245     *vectype = typeinfo_first;
1246
1247   return error ? PARSE_FAIL : (ret_val << 2) | (nb_regs - 1);
1248 }
1249
1250 /* Directives: register aliases.  */
1251
1252 static reg_entry *
1253 insert_reg_alias (char *str, int number, aarch64_reg_type type)
1254 {
1255   reg_entry *new;
1256   const char *name;
1257
1258   if ((new = hash_find (aarch64_reg_hsh, str)) != 0)
1259     {
1260       if (new->builtin)
1261         as_warn (_("ignoring attempt to redefine built-in register '%s'"),
1262                  str);
1263
1264       /* Only warn about a redefinition if it's not defined as the
1265          same register.  */
1266       else if (new->number != number || new->type != type)
1267         as_warn (_("ignoring redefinition of register alias '%s'"), str);
1268
1269       return NULL;
1270     }
1271
1272   name = xstrdup (str);
1273   new = XNEW (reg_entry);
1274
1275   new->name = name;
1276   new->number = number;
1277   new->type = type;
1278   new->builtin = FALSE;
1279
1280   if (hash_insert (aarch64_reg_hsh, name, (void *) new))
1281     abort ();
1282
1283   return new;
1284 }
1285
1286 /* Look for the .req directive.  This is of the form:
1287
1288         new_register_name .req existing_register_name
1289
1290    If we find one, or if it looks sufficiently like one that we want to
1291    handle any error here, return TRUE.  Otherwise return FALSE.  */
1292
1293 static bfd_boolean
1294 create_register_alias (char *newname, char *p)
1295 {
1296   const reg_entry *old;
1297   char *oldname, *nbuf;
1298   size_t nlen;
1299
1300   /* The input scrubber ensures that whitespace after the mnemonic is
1301      collapsed to single spaces.  */
1302   oldname = p;
1303   if (strncmp (oldname, " .req ", 6) != 0)
1304     return FALSE;
1305
1306   oldname += 6;
1307   if (*oldname == '\0')
1308     return FALSE;
1309
1310   old = hash_find (aarch64_reg_hsh, oldname);
1311   if (!old)
1312     {
1313       as_warn (_("unknown register '%s' -- .req ignored"), oldname);
1314       return TRUE;
1315     }
1316
1317   /* If TC_CASE_SENSITIVE is defined, then newname already points to
1318      the desired alias name, and p points to its end.  If not, then
1319      the desired alias name is in the global original_case_string.  */
1320 #ifdef TC_CASE_SENSITIVE
1321   nlen = p - newname;
1322 #else
1323   newname = original_case_string;
1324   nlen = strlen (newname);
1325 #endif
1326
1327   nbuf = xmemdup0 (newname, nlen);
1328
1329   /* Create aliases under the new name as stated; an all-lowercase
1330      version of the new name; and an all-uppercase version of the new
1331      name.  */
1332   if (insert_reg_alias (nbuf, old->number, old->type) != NULL)
1333     {
1334       for (p = nbuf; *p; p++)
1335         *p = TOUPPER (*p);
1336
1337       if (strncmp (nbuf, newname, nlen))
1338         {
1339           /* If this attempt to create an additional alias fails, do not bother
1340              trying to create the all-lower case alias.  We will fail and issue
1341              a second, duplicate error message.  This situation arises when the
1342              programmer does something like:
1343              foo .req r0
1344              Foo .req r1
1345              The second .req creates the "Foo" alias but then fails to create
1346              the artificial FOO alias because it has already been created by the
1347              first .req.  */
1348           if (insert_reg_alias (nbuf, old->number, old->type) == NULL)
1349             {
1350               free (nbuf);
1351               return TRUE;
1352             }
1353         }
1354
1355       for (p = nbuf; *p; p++)
1356         *p = TOLOWER (*p);
1357
1358       if (strncmp (nbuf, newname, nlen))
1359         insert_reg_alias (nbuf, old->number, old->type);
1360     }
1361
1362   free (nbuf);
1363   return TRUE;
1364 }
1365
1366 /* Should never be called, as .req goes between the alias and the
1367    register name, not at the beginning of the line.  */
1368 static void
1369 s_req (int a ATTRIBUTE_UNUSED)
1370 {
1371   as_bad (_("invalid syntax for .req directive"));
1372 }
1373
1374 /* The .unreq directive deletes an alias which was previously defined
1375    by .req.  For example:
1376
1377        my_alias .req r11
1378        .unreq my_alias    */
1379
1380 static void
1381 s_unreq (int a ATTRIBUTE_UNUSED)
1382 {
1383   char *name;
1384   char saved_char;
1385
1386   name = input_line_pointer;
1387
1388   while (*input_line_pointer != 0
1389          && *input_line_pointer != ' ' && *input_line_pointer != '\n')
1390     ++input_line_pointer;
1391
1392   saved_char = *input_line_pointer;
1393   *input_line_pointer = 0;
1394
1395   if (!*name)
1396     as_bad (_("invalid syntax for .unreq directive"));
1397   else
1398     {
1399       reg_entry *reg = hash_find (aarch64_reg_hsh, name);
1400
1401       if (!reg)
1402         as_bad (_("unknown register alias '%s'"), name);
1403       else if (reg->builtin)
1404         as_warn (_("ignoring attempt to undefine built-in register '%s'"),
1405                  name);
1406       else
1407         {
1408           char *p;
1409           char *nbuf;
1410
1411           hash_delete (aarch64_reg_hsh, name, FALSE);
1412           free ((char *) reg->name);
1413           free (reg);
1414
1415           /* Also locate the all upper case and all lower case versions.
1416              Do not complain if we cannot find one or the other as it
1417              was probably deleted above.  */
1418
1419           nbuf = strdup (name);
1420           for (p = nbuf; *p; p++)
1421             *p = TOUPPER (*p);
1422           reg = hash_find (aarch64_reg_hsh, nbuf);
1423           if (reg)
1424             {
1425               hash_delete (aarch64_reg_hsh, nbuf, FALSE);
1426               free ((char *) reg->name);
1427               free (reg);
1428             }
1429
1430           for (p = nbuf; *p; p++)
1431             *p = TOLOWER (*p);
1432           reg = hash_find (aarch64_reg_hsh, nbuf);
1433           if (reg)
1434             {
1435               hash_delete (aarch64_reg_hsh, nbuf, FALSE);
1436               free ((char *) reg->name);
1437               free (reg);
1438             }
1439
1440           free (nbuf);
1441         }
1442     }
1443
1444   *input_line_pointer = saved_char;
1445   demand_empty_rest_of_line ();
1446 }
1447
1448 /* Directives: Instruction set selection.  */
1449
1450 #ifdef OBJ_ELF
1451 /* This code is to handle mapping symbols as defined in the ARM AArch64 ELF
1452    spec.  (See "Mapping symbols", section 4.5.4, ARM AAELF64 version 0.05).
1453    Note that previously, $a and $t has type STT_FUNC (BSF_OBJECT flag),
1454    and $d has type STT_OBJECT (BSF_OBJECT flag). Now all three are untyped.  */
1455
1456 /* Create a new mapping symbol for the transition to STATE.  */
1457
1458 static void
1459 make_mapping_symbol (enum mstate state, valueT value, fragS * frag)
1460 {
1461   symbolS *symbolP;
1462   const char *symname;
1463   int type;
1464
1465   switch (state)
1466     {
1467     case MAP_DATA:
1468       symname = "$d";
1469       type = BSF_NO_FLAGS;
1470       break;
1471     case MAP_INSN:
1472       symname = "$x";
1473       type = BSF_NO_FLAGS;
1474       break;
1475     default:
1476       abort ();
1477     }
1478
1479   symbolP = symbol_new (symname, now_seg, value, frag);
1480   symbol_get_bfdsym (symbolP)->flags |= type | BSF_LOCAL;
1481
1482   /* Save the mapping symbols for future reference.  Also check that
1483      we do not place two mapping symbols at the same offset within a
1484      frag.  We'll handle overlap between frags in
1485      check_mapping_symbols.
1486
1487      If .fill or other data filling directive generates zero sized data,
1488      the mapping symbol for the following code will have the same value
1489      as the one generated for the data filling directive.  In this case,
1490      we replace the old symbol with the new one at the same address.  */
1491   if (value == 0)
1492     {
1493       if (frag->tc_frag_data.first_map != NULL)
1494         {
1495           know (S_GET_VALUE (frag->tc_frag_data.first_map) == 0);
1496           symbol_remove (frag->tc_frag_data.first_map, &symbol_rootP,
1497                          &symbol_lastP);
1498         }
1499       frag->tc_frag_data.first_map = symbolP;
1500     }
1501   if (frag->tc_frag_data.last_map != NULL)
1502     {
1503       know (S_GET_VALUE (frag->tc_frag_data.last_map) <=
1504             S_GET_VALUE (symbolP));
1505       if (S_GET_VALUE (frag->tc_frag_data.last_map) == S_GET_VALUE (symbolP))
1506         symbol_remove (frag->tc_frag_data.last_map, &symbol_rootP,
1507                        &symbol_lastP);
1508     }
1509   frag->tc_frag_data.last_map = symbolP;
1510 }
1511
1512 /* We must sometimes convert a region marked as code to data during
1513    code alignment, if an odd number of bytes have to be padded.  The
1514    code mapping symbol is pushed to an aligned address.  */
1515
1516 static void
1517 insert_data_mapping_symbol (enum mstate state,
1518                             valueT value, fragS * frag, offsetT bytes)
1519 {
1520   /* If there was already a mapping symbol, remove it.  */
1521   if (frag->tc_frag_data.last_map != NULL
1522       && S_GET_VALUE (frag->tc_frag_data.last_map) ==
1523       frag->fr_address + value)
1524     {
1525       symbolS *symp = frag->tc_frag_data.last_map;
1526
1527       if (value == 0)
1528         {
1529           know (frag->tc_frag_data.first_map == symp);
1530           frag->tc_frag_data.first_map = NULL;
1531         }
1532       frag->tc_frag_data.last_map = NULL;
1533       symbol_remove (symp, &symbol_rootP, &symbol_lastP);
1534     }
1535
1536   make_mapping_symbol (MAP_DATA, value, frag);
1537   make_mapping_symbol (state, value + bytes, frag);
1538 }
1539
1540 static void mapping_state_2 (enum mstate state, int max_chars);
1541
1542 /* Set the mapping state to STATE.  Only call this when about to
1543    emit some STATE bytes to the file.  */
1544
1545 void
1546 mapping_state (enum mstate state)
1547 {
1548   enum mstate mapstate = seg_info (now_seg)->tc_segment_info_data.mapstate;
1549
1550   if (state == MAP_INSN)
1551     /* AArch64 instructions require 4-byte alignment.  When emitting
1552        instructions into any section, record the appropriate section
1553        alignment.  */
1554     record_alignment (now_seg, 2);
1555
1556   if (mapstate == state)
1557     /* The mapping symbol has already been emitted.
1558        There is nothing else to do.  */
1559     return;
1560
1561 #define TRANSITION(from, to) (mapstate == (from) && state == (to))
1562   if (TRANSITION (MAP_UNDEFINED, MAP_DATA) && !subseg_text_p (now_seg))
1563     /* Emit MAP_DATA within executable section in order.  Otherwise, it will be
1564        evaluated later in the next else.  */
1565     return;
1566   else if (TRANSITION (MAP_UNDEFINED, MAP_INSN))
1567     {
1568       /* Only add the symbol if the offset is > 0:
1569          if we're at the first frag, check it's size > 0;
1570          if we're not at the first frag, then for sure
1571          the offset is > 0.  */
1572       struct frag *const frag_first = seg_info (now_seg)->frchainP->frch_root;
1573       const int add_symbol = (frag_now != frag_first)
1574         || (frag_now_fix () > 0);
1575
1576       if (add_symbol)
1577         make_mapping_symbol (MAP_DATA, (valueT) 0, frag_first);
1578     }
1579 #undef TRANSITION
1580
1581   mapping_state_2 (state, 0);
1582 }
1583
1584 /* Same as mapping_state, but MAX_CHARS bytes have already been
1585    allocated.  Put the mapping symbol that far back.  */
1586
1587 static void
1588 mapping_state_2 (enum mstate state, int max_chars)
1589 {
1590   enum mstate mapstate = seg_info (now_seg)->tc_segment_info_data.mapstate;
1591
1592   if (!SEG_NORMAL (now_seg))
1593     return;
1594
1595   if (mapstate == state)
1596     /* The mapping symbol has already been emitted.
1597        There is nothing else to do.  */
1598     return;
1599
1600   seg_info (now_seg)->tc_segment_info_data.mapstate = state;
1601   make_mapping_symbol (state, (valueT) frag_now_fix () - max_chars, frag_now);
1602 }
1603 #else
1604 #define mapping_state(x)        /* nothing */
1605 #define mapping_state_2(x, y)   /* nothing */
1606 #endif
1607
1608 /* Directives: sectioning and alignment.  */
1609
1610 static void
1611 s_bss (int ignore ATTRIBUTE_UNUSED)
1612 {
1613   /* We don't support putting frags in the BSS segment, we fake it by
1614      marking in_bss, then looking at s_skip for clues.  */
1615   subseg_set (bss_section, 0);
1616   demand_empty_rest_of_line ();
1617   mapping_state (MAP_DATA);
1618 }
1619
1620 static void
1621 s_even (int ignore ATTRIBUTE_UNUSED)
1622 {
1623   /* Never make frag if expect extra pass.  */
1624   if (!need_pass_2)
1625     frag_align (1, 0, 0);
1626
1627   record_alignment (now_seg, 1);
1628
1629   demand_empty_rest_of_line ();
1630 }
1631
1632 /* Directives: Literal pools.  */
1633
1634 static literal_pool *
1635 find_literal_pool (int size)
1636 {
1637   literal_pool *pool;
1638
1639   for (pool = list_of_pools; pool != NULL; pool = pool->next)
1640     {
1641       if (pool->section == now_seg
1642           && pool->sub_section == now_subseg && pool->size == size)
1643         break;
1644     }
1645
1646   return pool;
1647 }
1648
1649 static literal_pool *
1650 find_or_make_literal_pool (int size)
1651 {
1652   /* Next literal pool ID number.  */
1653   static unsigned int latest_pool_num = 1;
1654   literal_pool *pool;
1655
1656   pool = find_literal_pool (size);
1657
1658   if (pool == NULL)
1659     {
1660       /* Create a new pool.  */
1661       pool = XNEW (literal_pool);
1662       if (!pool)
1663         return NULL;
1664
1665       /* Currently we always put the literal pool in the current text
1666          section.  If we were generating "small" model code where we
1667          knew that all code and initialised data was within 1MB then
1668          we could output literals to mergeable, read-only data
1669          sections. */
1670
1671       pool->next_free_entry = 0;
1672       pool->section = now_seg;
1673       pool->sub_section = now_subseg;
1674       pool->size = size;
1675       pool->next = list_of_pools;
1676       pool->symbol = NULL;
1677
1678       /* Add it to the list.  */
1679       list_of_pools = pool;
1680     }
1681
1682   /* New pools, and emptied pools, will have a NULL symbol.  */
1683   if (pool->symbol == NULL)
1684     {
1685       pool->symbol = symbol_create (FAKE_LABEL_NAME, undefined_section,
1686                                     (valueT) 0, &zero_address_frag);
1687       pool->id = latest_pool_num++;
1688     }
1689
1690   /* Done.  */
1691   return pool;
1692 }
1693
1694 /* Add the literal of size SIZE in *EXP to the relevant literal pool.
1695    Return TRUE on success, otherwise return FALSE.  */
1696 static bfd_boolean
1697 add_to_lit_pool (expressionS *exp, int size)
1698 {
1699   literal_pool *pool;
1700   unsigned int entry;
1701
1702   pool = find_or_make_literal_pool (size);
1703
1704   /* Check if this literal value is already in the pool.  */
1705   for (entry = 0; entry < pool->next_free_entry; entry++)
1706     {
1707       expressionS * litexp = & pool->literals[entry].exp;
1708
1709       if ((litexp->X_op == exp->X_op)
1710           && (exp->X_op == O_constant)
1711           && (litexp->X_add_number == exp->X_add_number)
1712           && (litexp->X_unsigned == exp->X_unsigned))
1713         break;
1714
1715       if ((litexp->X_op == exp->X_op)
1716           && (exp->X_op == O_symbol)
1717           && (litexp->X_add_number == exp->X_add_number)
1718           && (litexp->X_add_symbol == exp->X_add_symbol)
1719           && (litexp->X_op_symbol == exp->X_op_symbol))
1720         break;
1721     }
1722
1723   /* Do we need to create a new entry?  */
1724   if (entry == pool->next_free_entry)
1725     {
1726       if (entry >= MAX_LITERAL_POOL_SIZE)
1727         {
1728           set_syntax_error (_("literal pool overflow"));
1729           return FALSE;
1730         }
1731
1732       pool->literals[entry].exp = *exp;
1733       pool->next_free_entry += 1;
1734       if (exp->X_op == O_big)
1735         {
1736           /* PR 16688: Bignums are held in a single global array.  We must
1737              copy and preserve that value now, before it is overwritten.  */
1738           pool->literals[entry].bignum = XNEWVEC (LITTLENUM_TYPE,
1739                                                   exp->X_add_number);
1740           memcpy (pool->literals[entry].bignum, generic_bignum,
1741                   CHARS_PER_LITTLENUM * exp->X_add_number);
1742         }
1743       else
1744         pool->literals[entry].bignum = NULL;
1745     }
1746
1747   exp->X_op = O_symbol;
1748   exp->X_add_number = ((int) entry) * size;
1749   exp->X_add_symbol = pool->symbol;
1750
1751   return TRUE;
1752 }
1753
1754 /* Can't use symbol_new here, so have to create a symbol and then at
1755    a later date assign it a value. That's what these functions do.  */
1756
1757 static void
1758 symbol_locate (symbolS * symbolP,
1759                const char *name,/* It is copied, the caller can modify.  */
1760                segT segment,    /* Segment identifier (SEG_<something>).  */
1761                valueT valu,     /* Symbol value.  */
1762                fragS * frag)    /* Associated fragment.  */
1763 {
1764   size_t name_length;
1765   char *preserved_copy_of_name;
1766
1767   name_length = strlen (name) + 1;      /* +1 for \0.  */
1768   obstack_grow (&notes, name, name_length);
1769   preserved_copy_of_name = obstack_finish (&notes);
1770
1771 #ifdef tc_canonicalize_symbol_name
1772   preserved_copy_of_name =
1773     tc_canonicalize_symbol_name (preserved_copy_of_name);
1774 #endif
1775
1776   S_SET_NAME (symbolP, preserved_copy_of_name);
1777
1778   S_SET_SEGMENT (symbolP, segment);
1779   S_SET_VALUE (symbolP, valu);
1780   symbol_clear_list_pointers (symbolP);
1781
1782   symbol_set_frag (symbolP, frag);
1783
1784   /* Link to end of symbol chain.  */
1785   {
1786     extern int symbol_table_frozen;
1787
1788     if (symbol_table_frozen)
1789       abort ();
1790   }
1791
1792   symbol_append (symbolP, symbol_lastP, &symbol_rootP, &symbol_lastP);
1793
1794   obj_symbol_new_hook (symbolP);
1795
1796 #ifdef tc_symbol_new_hook
1797   tc_symbol_new_hook (symbolP);
1798 #endif
1799
1800 #ifdef DEBUG_SYMS
1801   verify_symbol_chain (symbol_rootP, symbol_lastP);
1802 #endif /* DEBUG_SYMS  */
1803 }
1804
1805
1806 static void
1807 s_ltorg (int ignored ATTRIBUTE_UNUSED)
1808 {
1809   unsigned int entry;
1810   literal_pool *pool;
1811   char sym_name[20];
1812   int align;
1813
1814   for (align = 2; align <= 4; align++)
1815     {
1816       int size = 1 << align;
1817
1818       pool = find_literal_pool (size);
1819       if (pool == NULL || pool->symbol == NULL || pool->next_free_entry == 0)
1820         continue;
1821
1822       /* Align pool as you have word accesses.
1823          Only make a frag if we have to.  */
1824       if (!need_pass_2)
1825         frag_align (align, 0, 0);
1826
1827       mapping_state (MAP_DATA);
1828
1829       record_alignment (now_seg, align);
1830
1831       sprintf (sym_name, "$$lit_\002%x", pool->id);
1832
1833       symbol_locate (pool->symbol, sym_name, now_seg,
1834                      (valueT) frag_now_fix (), frag_now);
1835       symbol_table_insert (pool->symbol);
1836
1837       for (entry = 0; entry < pool->next_free_entry; entry++)
1838         {
1839           expressionS * exp = & pool->literals[entry].exp;
1840
1841           if (exp->X_op == O_big)
1842             {
1843               /* PR 16688: Restore the global bignum value.  */
1844               gas_assert (pool->literals[entry].bignum != NULL);
1845               memcpy (generic_bignum, pool->literals[entry].bignum,
1846                       CHARS_PER_LITTLENUM * exp->X_add_number);
1847             }
1848
1849           /* First output the expression in the instruction to the pool.  */
1850           emit_expr (exp, size);        /* .word|.xword  */
1851
1852           if (exp->X_op == O_big)
1853             {
1854               free (pool->literals[entry].bignum);
1855               pool->literals[entry].bignum = NULL;
1856             }
1857         }
1858
1859       /* Mark the pool as empty.  */
1860       pool->next_free_entry = 0;
1861       pool->symbol = NULL;
1862     }
1863 }
1864
1865 #ifdef OBJ_ELF
1866 /* Forward declarations for functions below, in the MD interface
1867    section.  */
1868 static fixS *fix_new_aarch64 (fragS *, int, short, expressionS *, int, int);
1869 static struct reloc_table_entry * find_reloc_table_entry (char **);
1870
1871 /* Directives: Data.  */
1872 /* N.B. the support for relocation suffix in this directive needs to be
1873    implemented properly.  */
1874
1875 static void
1876 s_aarch64_elf_cons (int nbytes)
1877 {
1878   expressionS exp;
1879
1880 #ifdef md_flush_pending_output
1881   md_flush_pending_output ();
1882 #endif
1883
1884   if (is_it_end_of_statement ())
1885     {
1886       demand_empty_rest_of_line ();
1887       return;
1888     }
1889
1890 #ifdef md_cons_align
1891   md_cons_align (nbytes);
1892 #endif
1893
1894   mapping_state (MAP_DATA);
1895   do
1896     {
1897       struct reloc_table_entry *reloc;
1898
1899       expression (&exp);
1900
1901       if (exp.X_op != O_symbol)
1902         emit_expr (&exp, (unsigned int) nbytes);
1903       else
1904         {
1905           skip_past_char (&input_line_pointer, '#');
1906           if (skip_past_char (&input_line_pointer, ':'))
1907             {
1908               reloc = find_reloc_table_entry (&input_line_pointer);
1909               if (reloc == NULL)
1910                 as_bad (_("unrecognized relocation suffix"));
1911               else
1912                 as_bad (_("unimplemented relocation suffix"));
1913               ignore_rest_of_line ();
1914               return;
1915             }
1916           else
1917             emit_expr (&exp, (unsigned int) nbytes);
1918         }
1919     }
1920   while (*input_line_pointer++ == ',');
1921
1922   /* Put terminator back into stream.  */
1923   input_line_pointer--;
1924   demand_empty_rest_of_line ();
1925 }
1926
1927 #endif /* OBJ_ELF */
1928
1929 /* Output a 32-bit word, but mark as an instruction.  */
1930
1931 static void
1932 s_aarch64_inst (int ignored ATTRIBUTE_UNUSED)
1933 {
1934   expressionS exp;
1935
1936 #ifdef md_flush_pending_output
1937   md_flush_pending_output ();
1938 #endif
1939
1940   if (is_it_end_of_statement ())
1941     {
1942       demand_empty_rest_of_line ();
1943       return;
1944     }
1945
1946   /* Sections are assumed to start aligned. In executable section, there is no
1947      MAP_DATA symbol pending. So we only align the address during
1948      MAP_DATA --> MAP_INSN transition.
1949      For other sections, this is not guaranteed.  */
1950   enum mstate mapstate = seg_info (now_seg)->tc_segment_info_data.mapstate;
1951   if (!need_pass_2 && subseg_text_p (now_seg) && mapstate == MAP_DATA)
1952     frag_align_code (2, 0);
1953
1954 #ifdef OBJ_ELF
1955   mapping_state (MAP_INSN);
1956 #endif
1957
1958   do
1959     {
1960       expression (&exp);
1961       if (exp.X_op != O_constant)
1962         {
1963           as_bad (_("constant expression required"));
1964           ignore_rest_of_line ();
1965           return;
1966         }
1967
1968       if (target_big_endian)
1969         {
1970           unsigned int val = exp.X_add_number;
1971           exp.X_add_number = SWAP_32 (val);
1972         }
1973       emit_expr (&exp, 4);
1974     }
1975   while (*input_line_pointer++ == ',');
1976
1977   /* Put terminator back into stream.  */
1978   input_line_pointer--;
1979   demand_empty_rest_of_line ();
1980 }
1981
1982 #ifdef OBJ_ELF
1983 /* Emit BFD_RELOC_AARCH64_TLSDESC_ADD on the next ADD instruction.  */
1984
1985 static void
1986 s_tlsdescadd (int ignored ATTRIBUTE_UNUSED)
1987 {
1988   expressionS exp;
1989
1990   expression (&exp);
1991   frag_grow (4);
1992   fix_new_aarch64 (frag_now, frag_more (0) - frag_now->fr_literal, 4, &exp, 0,
1993                    BFD_RELOC_AARCH64_TLSDESC_ADD);
1994
1995   demand_empty_rest_of_line ();
1996 }
1997
1998 /* Emit BFD_RELOC_AARCH64_TLSDESC_CALL on the next BLR instruction.  */
1999
2000 static void
2001 s_tlsdesccall (int ignored ATTRIBUTE_UNUSED)
2002 {
2003   expressionS exp;
2004
2005   /* Since we're just labelling the code, there's no need to define a
2006      mapping symbol.  */
2007   expression (&exp);
2008   /* Make sure there is enough room in this frag for the following
2009      blr.  This trick only works if the blr follows immediately after
2010      the .tlsdesc directive.  */
2011   frag_grow (4);
2012   fix_new_aarch64 (frag_now, frag_more (0) - frag_now->fr_literal, 4, &exp, 0,
2013                    BFD_RELOC_AARCH64_TLSDESC_CALL);
2014
2015   demand_empty_rest_of_line ();
2016 }
2017
2018 /* Emit BFD_RELOC_AARCH64_TLSDESC_LDR on the next LDR instruction.  */
2019
2020 static void
2021 s_tlsdescldr (int ignored ATTRIBUTE_UNUSED)
2022 {
2023   expressionS exp;
2024
2025   expression (&exp);
2026   frag_grow (4);
2027   fix_new_aarch64 (frag_now, frag_more (0) - frag_now->fr_literal, 4, &exp, 0,
2028                    BFD_RELOC_AARCH64_TLSDESC_LDR);
2029
2030   demand_empty_rest_of_line ();
2031 }
2032 #endif  /* OBJ_ELF */
2033
2034 static void s_aarch64_arch (int);
2035 static void s_aarch64_cpu (int);
2036 static void s_aarch64_arch_extension (int);
2037
2038 /* This table describes all the machine specific pseudo-ops the assembler
2039    has to support.  The fields are:
2040      pseudo-op name without dot
2041      function to call to execute this pseudo-op
2042      Integer arg to pass to the function.  */
2043
2044 const pseudo_typeS md_pseudo_table[] = {
2045   /* Never called because '.req' does not start a line.  */
2046   {"req", s_req, 0},
2047   {"unreq", s_unreq, 0},
2048   {"bss", s_bss, 0},
2049   {"even", s_even, 0},
2050   {"ltorg", s_ltorg, 0},
2051   {"pool", s_ltorg, 0},
2052   {"cpu", s_aarch64_cpu, 0},
2053   {"arch", s_aarch64_arch, 0},
2054   {"arch_extension", s_aarch64_arch_extension, 0},
2055   {"inst", s_aarch64_inst, 0},
2056 #ifdef OBJ_ELF
2057   {"tlsdescadd", s_tlsdescadd, 0},
2058   {"tlsdesccall", s_tlsdesccall, 0},
2059   {"tlsdescldr", s_tlsdescldr, 0},
2060   {"word", s_aarch64_elf_cons, 4},
2061   {"long", s_aarch64_elf_cons, 4},
2062   {"xword", s_aarch64_elf_cons, 8},
2063   {"dword", s_aarch64_elf_cons, 8},
2064 #endif
2065   {0, 0, 0}
2066 };
2067 \f
2068
2069 /* Check whether STR points to a register name followed by a comma or the
2070    end of line; REG_TYPE indicates which register types are checked
2071    against.  Return TRUE if STR is such a register name; otherwise return
2072    FALSE.  The function does not intend to produce any diagnostics, but since
2073    the register parser aarch64_reg_parse, which is called by this function,
2074    does produce diagnostics, we call clear_error to clear any diagnostics
2075    that may be generated by aarch64_reg_parse.
2076    Also, the function returns FALSE directly if there is any user error
2077    present at the function entry.  This prevents the existing diagnostics
2078    state from being spoiled.
2079    The function currently serves parse_constant_immediate and
2080    parse_big_immediate only.  */
2081 static bfd_boolean
2082 reg_name_p (char *str, aarch64_reg_type reg_type)
2083 {
2084   int reg;
2085
2086   /* Prevent the diagnostics state from being spoiled.  */
2087   if (error_p ())
2088     return FALSE;
2089
2090   reg = aarch64_reg_parse (&str, reg_type, NULL, NULL);
2091
2092   /* Clear the parsing error that may be set by the reg parser.  */
2093   clear_error ();
2094
2095   if (reg == PARSE_FAIL)
2096     return FALSE;
2097
2098   skip_whitespace (str);
2099   if (*str == ',' || is_end_of_line[(unsigned int) *str])
2100     return TRUE;
2101
2102   return FALSE;
2103 }
2104
2105 /* Parser functions used exclusively in instruction operands.  */
2106
2107 /* Parse an immediate expression which may not be constant.
2108
2109    To prevent the expression parser from pushing a register name
2110    into the symbol table as an undefined symbol, firstly a check is
2111    done to find out whether STR is a register of type REG_TYPE followed
2112    by a comma or the end of line.  Return FALSE if STR is such a string.  */
2113
2114 static bfd_boolean
2115 parse_immediate_expression (char **str, expressionS *exp,
2116                             aarch64_reg_type reg_type)
2117 {
2118   if (reg_name_p (*str, reg_type))
2119     {
2120       set_recoverable_error (_("immediate operand required"));
2121       return FALSE;
2122     }
2123
2124   my_get_expression (exp, str, GE_OPT_PREFIX, 1);
2125
2126   if (exp->X_op == O_absent)
2127     {
2128       set_fatal_syntax_error (_("missing immediate expression"));
2129       return FALSE;
2130     }
2131
2132   return TRUE;
2133 }
2134
2135 /* Constant immediate-value read function for use in insn parsing.
2136    STR points to the beginning of the immediate (with the optional
2137    leading #); *VAL receives the value.  REG_TYPE says which register
2138    names should be treated as registers rather than as symbolic immediates.
2139
2140    Return TRUE on success; otherwise return FALSE.  */
2141
2142 static bfd_boolean
2143 parse_constant_immediate (char **str, int64_t *val, aarch64_reg_type reg_type)
2144 {
2145   expressionS exp;
2146
2147   if (! parse_immediate_expression (str, &exp, reg_type))
2148     return FALSE;
2149
2150   if (exp.X_op != O_constant)
2151     {
2152       set_syntax_error (_("constant expression required"));
2153       return FALSE;
2154     }
2155
2156   *val = exp.X_add_number;
2157   return TRUE;
2158 }
2159
2160 static uint32_t
2161 encode_imm_float_bits (uint32_t imm)
2162 {
2163   return ((imm >> 19) & 0x7f)   /* b[25:19] -> b[6:0] */
2164     | ((imm >> (31 - 7)) & 0x80);       /* b[31]    -> b[7]   */
2165 }
2166
2167 /* Return TRUE if the single-precision floating-point value encoded in IMM
2168    can be expressed in the AArch64 8-bit signed floating-point format with
2169    3-bit exponent and normalized 4 bits of precision; in other words, the
2170    floating-point value must be expressable as
2171      (+/-) n / 16 * power (2, r)
2172    where n and r are integers such that 16 <= n <=31 and -3 <= r <= 4.  */
2173
2174 static bfd_boolean
2175 aarch64_imm_float_p (uint32_t imm)
2176 {
2177   /* If a single-precision floating-point value has the following bit
2178      pattern, it can be expressed in the AArch64 8-bit floating-point
2179      format:
2180
2181      3 32222222 2221111111111
2182      1 09876543 21098765432109876543210
2183      n Eeeeeexx xxxx0000000000000000000
2184
2185      where n, e and each x are either 0 or 1 independently, with
2186      E == ~ e.  */
2187
2188   uint32_t pattern;
2189
2190   /* Prepare the pattern for 'Eeeeee'.  */
2191   if (((imm >> 30) & 0x1) == 0)
2192     pattern = 0x3e000000;
2193   else
2194     pattern = 0x40000000;
2195
2196   return (imm & 0x7ffff) == 0           /* lower 19 bits are 0.  */
2197     && ((imm & 0x7e000000) == pattern); /* bits 25 - 29 == ~ bit 30.  */
2198 }
2199
2200 /* Return TRUE if the IEEE double value encoded in IMM can be expressed
2201    as an IEEE float without any loss of precision.  Store the value in
2202    *FPWORD if so.  */
2203
2204 static bfd_boolean
2205 can_convert_double_to_float (uint64_t imm, uint32_t *fpword)
2206 {
2207   /* If a double-precision floating-point value has the following bit
2208      pattern, it can be expressed in a float:
2209
2210      6 66655555555 5544 44444444 33333333 33222222 22221111 111111
2211      3 21098765432 1098 76543210 98765432 10987654 32109876 54321098 76543210
2212      n E~~~eeeeeee ssss ssssssss ssssssss SSS00000 00000000 00000000 00000000
2213
2214        ----------------------------->     nEeeeeee esssssss ssssssss sssssSSS
2215          if Eeee_eeee != 1111_1111
2216
2217      where n, e, s and S are either 0 or 1 independently and where ~ is the
2218      inverse of E.  */
2219
2220   uint32_t pattern;
2221   uint32_t high32 = imm >> 32;
2222   uint32_t low32 = imm;
2223
2224   /* Lower 29 bits need to be 0s.  */
2225   if ((imm & 0x1fffffff) != 0)
2226     return FALSE;
2227
2228   /* Prepare the pattern for 'Eeeeeeeee'.  */
2229   if (((high32 >> 30) & 0x1) == 0)
2230     pattern = 0x38000000;
2231   else
2232     pattern = 0x40000000;
2233
2234   /* Check E~~~.  */
2235   if ((high32 & 0x78000000) != pattern)
2236     return FALSE;
2237
2238   /* Check Eeee_eeee != 1111_1111.  */
2239   if ((high32 & 0x7ff00000) == 0x47f00000)
2240     return FALSE;
2241
2242   *fpword = ((high32 & 0xc0000000)              /* 1 n bit and 1 E bit.  */
2243              | ((high32 << 3) & 0x3ffffff8)     /* 7 e and 20 s bits.  */
2244              | (low32 >> 29));                  /* 3 S bits.  */
2245   return TRUE;
2246 }
2247
2248 /* Return true if we should treat OPERAND as a double-precision
2249    floating-point operand rather than a single-precision one.  */
2250 static bfd_boolean
2251 double_precision_operand_p (const aarch64_opnd_info *operand)
2252 {
2253   /* Check for unsuffixed SVE registers, which are allowed
2254      for LDR and STR but not in instructions that require an
2255      immediate.  We get better error messages if we arbitrarily
2256      pick one size, parse the immediate normally, and then
2257      report the match failure in the normal way.  */
2258   return (operand->qualifier == AARCH64_OPND_QLF_NIL
2259           || aarch64_get_qualifier_esize (operand->qualifier) == 8);
2260 }
2261
2262 /* Parse a floating-point immediate.  Return TRUE on success and return the
2263    value in *IMMED in the format of IEEE754 single-precision encoding.
2264    *CCP points to the start of the string; DP_P is TRUE when the immediate
2265    is expected to be in double-precision (N.B. this only matters when
2266    hexadecimal representation is involved).  REG_TYPE says which register
2267    names should be treated as registers rather than as symbolic immediates.
2268
2269    This routine accepts any IEEE float; it is up to the callers to reject
2270    invalid ones.  */
2271
2272 static bfd_boolean
2273 parse_aarch64_imm_float (char **ccp, int *immed, bfd_boolean dp_p,
2274                          aarch64_reg_type reg_type)
2275 {
2276   char *str = *ccp;
2277   char *fpnum;
2278   LITTLENUM_TYPE words[MAX_LITTLENUMS];
2279   int found_fpchar = 0;
2280   int64_t val = 0;
2281   unsigned fpword = 0;
2282   bfd_boolean hex_p = FALSE;
2283
2284   skip_past_char (&str, '#');
2285
2286   fpnum = str;
2287   skip_whitespace (fpnum);
2288
2289   if (strncmp (fpnum, "0x", 2) == 0)
2290     {
2291       /* Support the hexadecimal representation of the IEEE754 encoding.
2292          Double-precision is expected when DP_P is TRUE, otherwise the
2293          representation should be in single-precision.  */
2294       if (! parse_constant_immediate (&str, &val, reg_type))
2295         goto invalid_fp;
2296
2297       if (dp_p)
2298         {
2299           if (!can_convert_double_to_float (val, &fpword))
2300             goto invalid_fp;
2301         }
2302       else if ((uint64_t) val > 0xffffffff)
2303         goto invalid_fp;
2304       else
2305         fpword = val;
2306
2307       hex_p = TRUE;
2308     }
2309   else
2310     {
2311       if (reg_name_p (str, reg_type))
2312         {
2313           set_recoverable_error (_("immediate operand required"));
2314           return FALSE;
2315         }
2316
2317       /* We must not accidentally parse an integer as a floating-point number.
2318          Make sure that the value we parse is not an integer by checking for
2319          special characters '.' or 'e'.  */
2320       for (; *fpnum != '\0' && *fpnum != ' ' && *fpnum != '\n'; fpnum++)
2321         if (*fpnum == '.' || *fpnum == 'e' || *fpnum == 'E')
2322           {
2323             found_fpchar = 1;
2324             break;
2325           }
2326
2327       if (!found_fpchar)
2328         return FALSE;
2329     }
2330
2331   if (! hex_p)
2332     {
2333       int i;
2334
2335       if ((str = atof_ieee (str, 's', words)) == NULL)
2336         goto invalid_fp;
2337
2338       /* Our FP word must be 32 bits (single-precision FP).  */
2339       for (i = 0; i < 32 / LITTLENUM_NUMBER_OF_BITS; i++)
2340         {
2341           fpword <<= LITTLENUM_NUMBER_OF_BITS;
2342           fpword |= words[i];
2343         }
2344     }
2345
2346   *immed = fpword;
2347   *ccp = str;
2348   return TRUE;
2349
2350 invalid_fp:
2351   set_fatal_syntax_error (_("invalid floating-point constant"));
2352   return FALSE;
2353 }
2354
2355 /* Less-generic immediate-value read function with the possibility of loading
2356    a big (64-bit) immediate, as required by AdvSIMD Modified immediate
2357    instructions.
2358
2359    To prevent the expression parser from pushing a register name into the
2360    symbol table as an undefined symbol, a check is firstly done to find
2361    out whether STR is a register of type REG_TYPE followed by a comma or
2362    the end of line.  Return FALSE if STR is such a register.  */
2363
2364 static bfd_boolean
2365 parse_big_immediate (char **str, int64_t *imm, aarch64_reg_type reg_type)
2366 {
2367   char *ptr = *str;
2368
2369   if (reg_name_p (ptr, reg_type))
2370     {
2371       set_syntax_error (_("immediate operand required"));
2372       return FALSE;
2373     }
2374
2375   my_get_expression (&inst.reloc.exp, &ptr, GE_OPT_PREFIX, 1);
2376
2377   if (inst.reloc.exp.X_op == O_constant)
2378     *imm = inst.reloc.exp.X_add_number;
2379
2380   *str = ptr;
2381
2382   return TRUE;
2383 }
2384
2385 /* Set operand IDX of the *INSTR that needs a GAS internal fixup.
2386    if NEED_LIBOPCODES is non-zero, the fixup will need
2387    assistance from the libopcodes.   */
2388
2389 static inline void
2390 aarch64_set_gas_internal_fixup (struct reloc *reloc,
2391                                 const aarch64_opnd_info *operand,
2392                                 int need_libopcodes_p)
2393 {
2394   reloc->type = BFD_RELOC_AARCH64_GAS_INTERNAL_FIXUP;
2395   reloc->opnd = operand->type;
2396   if (need_libopcodes_p)
2397     reloc->need_libopcodes_p = 1;
2398 };
2399
2400 /* Return TRUE if the instruction needs to be fixed up later internally by
2401    the GAS; otherwise return FALSE.  */
2402
2403 static inline bfd_boolean
2404 aarch64_gas_internal_fixup_p (void)
2405 {
2406   return inst.reloc.type == BFD_RELOC_AARCH64_GAS_INTERNAL_FIXUP;
2407 }
2408
2409 /* Assign the immediate value to the relevant field in *OPERAND if
2410    RELOC->EXP is a constant expression; otherwise, flag that *OPERAND
2411    needs an internal fixup in a later stage.
2412    ADDR_OFF_P determines whether it is the field ADDR.OFFSET.IMM or
2413    IMM.VALUE that may get assigned with the constant.  */
2414 static inline void
2415 assign_imm_if_const_or_fixup_later (struct reloc *reloc,
2416                                     aarch64_opnd_info *operand,
2417                                     int addr_off_p,
2418                                     int need_libopcodes_p,
2419                                     int skip_p)
2420 {
2421   if (reloc->exp.X_op == O_constant)
2422     {
2423       if (addr_off_p)
2424         operand->addr.offset.imm = reloc->exp.X_add_number;
2425       else
2426         operand->imm.value = reloc->exp.X_add_number;
2427       reloc->type = BFD_RELOC_UNUSED;
2428     }
2429   else
2430     {
2431       aarch64_set_gas_internal_fixup (reloc, operand, need_libopcodes_p);
2432       /* Tell libopcodes to ignore this operand or not.  This is helpful
2433          when one of the operands needs to be fixed up later but we need
2434          libopcodes to check the other operands.  */
2435       operand->skip = skip_p;
2436     }
2437 }
2438
2439 /* Relocation modifiers.  Each entry in the table contains the textual
2440    name for the relocation which may be placed before a symbol used as
2441    a load/store offset, or add immediate. It must be surrounded by a
2442    leading and trailing colon, for example:
2443
2444         ldr     x0, [x1, #:rello:varsym]
2445         add     x0, x1, #:rello:varsym  */
2446
2447 struct reloc_table_entry
2448 {
2449   const char *name;
2450   int pc_rel;
2451   bfd_reloc_code_real_type adr_type;
2452   bfd_reloc_code_real_type adrp_type;
2453   bfd_reloc_code_real_type movw_type;
2454   bfd_reloc_code_real_type add_type;
2455   bfd_reloc_code_real_type ldst_type;
2456   bfd_reloc_code_real_type ld_literal_type;
2457 };
2458
2459 static struct reloc_table_entry reloc_table[] = {
2460   /* Low 12 bits of absolute address: ADD/i and LDR/STR */
2461   {"lo12", 0,
2462    0,                           /* adr_type */
2463    0,
2464    0,
2465    BFD_RELOC_AARCH64_ADD_LO12,
2466    BFD_RELOC_AARCH64_LDST_LO12,
2467    0},
2468
2469   /* Higher 21 bits of pc-relative page offset: ADRP */
2470   {"pg_hi21", 1,
2471    0,                           /* adr_type */
2472    BFD_RELOC_AARCH64_ADR_HI21_PCREL,
2473    0,
2474    0,
2475    0,
2476    0},
2477
2478   /* Higher 21 bits of pc-relative page offset: ADRP, no check */
2479   {"pg_hi21_nc", 1,
2480    0,                           /* adr_type */
2481    BFD_RELOC_AARCH64_ADR_HI21_NC_PCREL,
2482    0,
2483    0,
2484    0,
2485    0},
2486
2487   /* Most significant bits 0-15 of unsigned address/value: MOVZ */
2488   {"abs_g0", 0,
2489    0,                           /* adr_type */
2490    0,
2491    BFD_RELOC_AARCH64_MOVW_G0,
2492    0,
2493    0,
2494    0},
2495
2496   /* Most significant bits 0-15 of signed address/value: MOVN/Z */
2497   {"abs_g0_s", 0,
2498    0,                           /* adr_type */
2499    0,
2500    BFD_RELOC_AARCH64_MOVW_G0_S,
2501    0,
2502    0,
2503    0},
2504
2505   /* Less significant bits 0-15 of address/value: MOVK, no check */
2506   {"abs_g0_nc", 0,
2507    0,                           /* adr_type */
2508    0,
2509    BFD_RELOC_AARCH64_MOVW_G0_NC,
2510    0,
2511    0,
2512    0},
2513
2514   /* Most significant bits 16-31 of unsigned address/value: MOVZ */
2515   {"abs_g1", 0,
2516    0,                           /* adr_type */
2517    0,
2518    BFD_RELOC_AARCH64_MOVW_G1,
2519    0,
2520    0,
2521    0},
2522
2523   /* Most significant bits 16-31 of signed address/value: MOVN/Z */
2524   {"abs_g1_s", 0,
2525    0,                           /* adr_type */
2526    0,
2527    BFD_RELOC_AARCH64_MOVW_G1_S,
2528    0,
2529    0,
2530    0},
2531
2532   /* Less significant bits 16-31 of address/value: MOVK, no check */
2533   {"abs_g1_nc", 0,
2534    0,                           /* adr_type */
2535    0,
2536    BFD_RELOC_AARCH64_MOVW_G1_NC,
2537    0,
2538    0,
2539    0},
2540
2541   /* Most significant bits 32-47 of unsigned address/value: MOVZ */
2542   {"abs_g2", 0,
2543    0,                           /* adr_type */
2544    0,
2545    BFD_RELOC_AARCH64_MOVW_G2,
2546    0,
2547    0,
2548    0},
2549
2550   /* Most significant bits 32-47 of signed address/value: MOVN/Z */
2551   {"abs_g2_s", 0,
2552    0,                           /* adr_type */
2553    0,
2554    BFD_RELOC_AARCH64_MOVW_G2_S,
2555    0,
2556    0,
2557    0},
2558
2559   /* Less significant bits 32-47 of address/value: MOVK, no check */
2560   {"abs_g2_nc", 0,
2561    0,                           /* adr_type */
2562    0,
2563    BFD_RELOC_AARCH64_MOVW_G2_NC,
2564    0,
2565    0,
2566    0},
2567
2568   /* Most significant bits 48-63 of signed/unsigned address/value: MOVZ */
2569   {"abs_g3", 0,
2570    0,                           /* adr_type */
2571    0,
2572    BFD_RELOC_AARCH64_MOVW_G3,
2573    0,
2574    0,
2575    0},
2576
2577   /* Get to the page containing GOT entry for a symbol.  */
2578   {"got", 1,
2579    0,                           /* adr_type */
2580    BFD_RELOC_AARCH64_ADR_GOT_PAGE,
2581    0,
2582    0,
2583    0,
2584    BFD_RELOC_AARCH64_GOT_LD_PREL19},
2585
2586   /* 12 bit offset into the page containing GOT entry for that symbol.  */
2587   {"got_lo12", 0,
2588    0,                           /* adr_type */
2589    0,
2590    0,
2591    0,
2592    BFD_RELOC_AARCH64_LD_GOT_LO12_NC,
2593    0},
2594
2595   /* 0-15 bits of address/value: MOVk, no check.  */
2596   {"gotoff_g0_nc", 0,
2597    0,                           /* adr_type */
2598    0,
2599    BFD_RELOC_AARCH64_MOVW_GOTOFF_G0_NC,
2600    0,
2601    0,
2602    0},
2603
2604   /* Most significant bits 16-31 of address/value: MOVZ.  */
2605   {"gotoff_g1", 0,
2606    0,                           /* adr_type */
2607    0,
2608    BFD_RELOC_AARCH64_MOVW_GOTOFF_G1,
2609    0,
2610    0,
2611    0},
2612
2613   /* 15 bit offset into the page containing GOT entry for that symbol.  */
2614   {"gotoff_lo15", 0,
2615    0,                           /* adr_type */
2616    0,
2617    0,
2618    0,
2619    BFD_RELOC_AARCH64_LD64_GOTOFF_LO15,
2620    0},
2621
2622   /* Get to the page containing GOT TLS entry for a symbol */
2623   {"gottprel_g0_nc", 0,
2624    0,                           /* adr_type */
2625    0,
2626    BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC,
2627    0,
2628    0,
2629    0},
2630
2631   /* Get to the page containing GOT TLS entry for a symbol */
2632   {"gottprel_g1", 0,
2633    0,                           /* adr_type */
2634    0,
2635    BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G1,
2636    0,
2637    0,
2638    0},
2639
2640   /* Get to the page containing GOT TLS entry for a symbol */
2641   {"tlsgd", 0,
2642    BFD_RELOC_AARCH64_TLSGD_ADR_PREL21, /* adr_type */
2643    BFD_RELOC_AARCH64_TLSGD_ADR_PAGE21,
2644    0,
2645    0,
2646    0,
2647    0},
2648
2649   /* 12 bit offset into the page containing GOT TLS entry for a symbol */
2650   {"tlsgd_lo12", 0,
2651    0,                           /* adr_type */
2652    0,
2653    0,
2654    BFD_RELOC_AARCH64_TLSGD_ADD_LO12_NC,
2655    0,
2656    0},
2657
2658   /* Lower 16 bits address/value: MOVk.  */
2659   {"tlsgd_g0_nc", 0,
2660    0,                           /* adr_type */
2661    0,
2662    BFD_RELOC_AARCH64_TLSGD_MOVW_G0_NC,
2663    0,
2664    0,
2665    0},
2666
2667   /* Most significant bits 16-31 of address/value: MOVZ.  */
2668   {"tlsgd_g1", 0,
2669    0,                           /* adr_type */
2670    0,
2671    BFD_RELOC_AARCH64_TLSGD_MOVW_G1,
2672    0,
2673    0,
2674    0},
2675
2676   /* Get to the page containing GOT TLS entry for a symbol */
2677   {"tlsdesc", 0,
2678    BFD_RELOC_AARCH64_TLSDESC_ADR_PREL21, /* adr_type */
2679    BFD_RELOC_AARCH64_TLSDESC_ADR_PAGE21,
2680    0,
2681    0,
2682    0,
2683    BFD_RELOC_AARCH64_TLSDESC_LD_PREL19},
2684
2685   /* 12 bit offset into the page containing GOT TLS entry for a symbol */
2686   {"tlsdesc_lo12", 0,
2687    0,                           /* adr_type */
2688    0,
2689    0,
2690    BFD_RELOC_AARCH64_TLSDESC_ADD_LO12,
2691    BFD_RELOC_AARCH64_TLSDESC_LD_LO12_NC,
2692    0},
2693
2694   /* Get to the page containing GOT TLS entry for a symbol.
2695      The same as GD, we allocate two consecutive GOT slots
2696      for module index and module offset, the only difference
2697      with GD is the module offset should be initialized to
2698      zero without any outstanding runtime relocation. */
2699   {"tlsldm", 0,
2700    BFD_RELOC_AARCH64_TLSLD_ADR_PREL21, /* adr_type */
2701    BFD_RELOC_AARCH64_TLSLD_ADR_PAGE21,
2702    0,
2703    0,
2704    0,
2705    0},
2706
2707   /* 12 bit offset into the page containing GOT TLS entry for a symbol */
2708   {"tlsldm_lo12_nc", 0,
2709    0,                           /* adr_type */
2710    0,
2711    0,
2712    BFD_RELOC_AARCH64_TLSLD_ADD_LO12_NC,
2713    0,
2714    0},
2715
2716   /* 12 bit offset into the module TLS base address.  */
2717   {"dtprel_lo12", 0,
2718    0,                           /* adr_type */
2719    0,
2720    0,
2721    BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_LO12,
2722    BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12,
2723    0},
2724
2725   /* Same as dtprel_lo12, no overflow check.  */
2726   {"dtprel_lo12_nc", 0,
2727    0,                           /* adr_type */
2728    0,
2729    0,
2730    BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_LO12_NC,
2731    BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12_NC,
2732    0},
2733
2734   /* bits[23:12] of offset to the module TLS base address.  */
2735   {"dtprel_hi12", 0,
2736    0,                           /* adr_type */
2737    0,
2738    0,
2739    BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_HI12,
2740    0,
2741    0},
2742
2743   /* bits[15:0] of offset to the module TLS base address.  */
2744   {"dtprel_g0", 0,
2745    0,                           /* adr_type */
2746    0,
2747    BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0,
2748    0,
2749    0,
2750    0},
2751
2752   /* No overflow check version of BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0.  */
2753   {"dtprel_g0_nc", 0,
2754    0,                           /* adr_type */
2755    0,
2756    BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0_NC,
2757    0,
2758    0,
2759    0},
2760
2761   /* bits[31:16] of offset to the module TLS base address.  */
2762   {"dtprel_g1", 0,
2763    0,                           /* adr_type */
2764    0,
2765    BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1,
2766    0,
2767    0,
2768    0},
2769
2770   /* No overflow check version of BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1.  */
2771   {"dtprel_g1_nc", 0,
2772    0,                           /* adr_type */
2773    0,
2774    BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1_NC,
2775    0,
2776    0,
2777    0},
2778
2779   /* bits[47:32] of offset to the module TLS base address.  */
2780   {"dtprel_g2", 0,
2781    0,                           /* adr_type */
2782    0,
2783    BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G2,
2784    0,
2785    0,
2786    0},
2787
2788   /* Lower 16 bit offset into GOT entry for a symbol */
2789   {"tlsdesc_off_g0_nc", 0,
2790    0,                           /* adr_type */
2791    0,
2792    BFD_RELOC_AARCH64_TLSDESC_OFF_G0_NC,
2793    0,
2794    0,
2795    0},
2796
2797   /* Higher 16 bit offset into GOT entry for a symbol */
2798   {"tlsdesc_off_g1", 0,
2799    0,                           /* adr_type */
2800    0,
2801    BFD_RELOC_AARCH64_TLSDESC_OFF_G1,
2802    0,
2803    0,
2804    0},
2805
2806   /* Get to the page containing GOT TLS entry for a symbol */
2807   {"gottprel", 0,
2808    0,                           /* adr_type */
2809    BFD_RELOC_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21,
2810    0,
2811    0,
2812    0,
2813    BFD_RELOC_AARCH64_TLSIE_LD_GOTTPREL_PREL19},
2814
2815   /* 12 bit offset into the page containing GOT TLS entry for a symbol */
2816   {"gottprel_lo12", 0,
2817    0,                           /* adr_type */
2818    0,
2819    0,
2820    0,
2821    BFD_RELOC_AARCH64_TLSIE_LD_GOTTPREL_LO12_NC,
2822    0},
2823
2824   /* Get tp offset for a symbol.  */
2825   {"tprel", 0,
2826    0,                           /* adr_type */
2827    0,
2828    0,
2829    BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12,
2830    0,
2831    0},
2832
2833   /* Get tp offset for a symbol.  */
2834   {"tprel_lo12", 0,
2835    0,                           /* adr_type */
2836    0,
2837    0,
2838    BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12,
2839    0,
2840    0},
2841
2842   /* Get tp offset for a symbol.  */
2843   {"tprel_hi12", 0,
2844    0,                           /* adr_type */
2845    0,
2846    0,
2847    BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_HI12,
2848    0,
2849    0},
2850
2851   /* Get tp offset for a symbol.  */
2852   {"tprel_lo12_nc", 0,
2853    0,                           /* adr_type */
2854    0,
2855    0,
2856    BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12_NC,
2857    0,
2858    0},
2859
2860   /* Most significant bits 32-47 of address/value: MOVZ.  */
2861   {"tprel_g2", 0,
2862    0,                           /* adr_type */
2863    0,
2864    BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G2,
2865    0,
2866    0,
2867    0},
2868
2869   /* Most significant bits 16-31 of address/value: MOVZ.  */
2870   {"tprel_g1", 0,
2871    0,                           /* adr_type */
2872    0,
2873    BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1,
2874    0,
2875    0,
2876    0},
2877
2878   /* Most significant bits 16-31 of address/value: MOVZ, no check.  */
2879   {"tprel_g1_nc", 0,
2880    0,                           /* adr_type */
2881    0,
2882    BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1_NC,
2883    0,
2884    0,
2885    0},
2886
2887   /* Most significant bits 0-15 of address/value: MOVZ.  */
2888   {"tprel_g0", 0,
2889    0,                           /* adr_type */
2890    0,
2891    BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0,
2892    0,
2893    0,
2894    0},
2895
2896   /* Most significant bits 0-15 of address/value: MOVZ, no check.  */
2897   {"tprel_g0_nc", 0,
2898    0,                           /* adr_type */
2899    0,
2900    BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0_NC,
2901    0,
2902    0,
2903    0},
2904
2905   /* 15bit offset from got entry to base address of GOT table.  */
2906   {"gotpage_lo15", 0,
2907    0,
2908    0,
2909    0,
2910    0,
2911    BFD_RELOC_AARCH64_LD64_GOTPAGE_LO15,
2912    0},
2913
2914   /* 14bit offset from got entry to base address of GOT table.  */
2915   {"gotpage_lo14", 0,
2916    0,
2917    0,
2918    0,
2919    0,
2920    BFD_RELOC_AARCH64_LD32_GOTPAGE_LO14,
2921    0},
2922 };
2923
2924 /* Given the address of a pointer pointing to the textual name of a
2925    relocation as may appear in assembler source, attempt to find its
2926    details in reloc_table.  The pointer will be updated to the character
2927    after the trailing colon.  On failure, NULL will be returned;
2928    otherwise return the reloc_table_entry.  */
2929
2930 static struct reloc_table_entry *
2931 find_reloc_table_entry (char **str)
2932 {
2933   unsigned int i;
2934   for (i = 0; i < ARRAY_SIZE (reloc_table); i++)
2935     {
2936       int length = strlen (reloc_table[i].name);
2937
2938       if (strncasecmp (reloc_table[i].name, *str, length) == 0
2939           && (*str)[length] == ':')
2940         {
2941           *str += (length + 1);
2942           return &reloc_table[i];
2943         }
2944     }
2945
2946   return NULL;
2947 }
2948
2949 /* Mode argument to parse_shift and parser_shifter_operand.  */
2950 enum parse_shift_mode
2951 {
2952   SHIFTED_NONE,                 /* no shifter allowed  */
2953   SHIFTED_ARITH_IMM,            /* "rn{,lsl|lsr|asl|asr|uxt|sxt #n}" or
2954                                    "#imm{,lsl #n}"  */
2955   SHIFTED_LOGIC_IMM,            /* "rn{,lsl|lsr|asl|asr|ror #n}" or
2956                                    "#imm"  */
2957   SHIFTED_LSL,                  /* bare "lsl #n"  */
2958   SHIFTED_MUL,                  /* bare "mul #n"  */
2959   SHIFTED_LSL_MSL,              /* "lsl|msl #n"  */
2960   SHIFTED_MUL_VL,               /* "mul vl"  */
2961   SHIFTED_REG_OFFSET            /* [su]xtw|sxtx {#n} or lsl #n  */
2962 };
2963
2964 /* Parse a <shift> operator on an AArch64 data processing instruction.
2965    Return TRUE on success; otherwise return FALSE.  */
2966 static bfd_boolean
2967 parse_shift (char **str, aarch64_opnd_info *operand, enum parse_shift_mode mode)
2968 {
2969   const struct aarch64_name_value_pair *shift_op;
2970   enum aarch64_modifier_kind kind;
2971   expressionS exp;
2972   int exp_has_prefix;
2973   char *s = *str;
2974   char *p = s;
2975
2976   for (p = *str; ISALPHA (*p); p++)
2977     ;
2978
2979   if (p == *str)
2980     {
2981       set_syntax_error (_("shift expression expected"));
2982       return FALSE;
2983     }
2984
2985   shift_op = hash_find_n (aarch64_shift_hsh, *str, p - *str);
2986
2987   if (shift_op == NULL)
2988     {
2989       set_syntax_error (_("shift operator expected"));
2990       return FALSE;
2991     }
2992
2993   kind = aarch64_get_operand_modifier (shift_op);
2994
2995   if (kind == AARCH64_MOD_MSL && mode != SHIFTED_LSL_MSL)
2996     {
2997       set_syntax_error (_("invalid use of 'MSL'"));
2998       return FALSE;
2999     }
3000
3001   if (kind == AARCH64_MOD_MUL
3002       && mode != SHIFTED_MUL
3003       && mode != SHIFTED_MUL_VL)
3004     {
3005       set_syntax_error (_("invalid use of 'MUL'"));
3006       return FALSE;
3007     }
3008
3009   switch (mode)
3010     {
3011     case SHIFTED_LOGIC_IMM:
3012       if (aarch64_extend_operator_p (kind))
3013         {
3014           set_syntax_error (_("extending shift is not permitted"));
3015           return FALSE;
3016         }
3017       break;
3018
3019     case SHIFTED_ARITH_IMM:
3020       if (kind == AARCH64_MOD_ROR)
3021         {
3022           set_syntax_error (_("'ROR' shift is not permitted"));
3023           return FALSE;
3024         }
3025       break;
3026
3027     case SHIFTED_LSL:
3028       if (kind != AARCH64_MOD_LSL)
3029         {
3030           set_syntax_error (_("only 'LSL' shift is permitted"));
3031           return FALSE;
3032         }
3033       break;
3034
3035     case SHIFTED_MUL:
3036       if (kind != AARCH64_MOD_MUL)
3037         {
3038           set_syntax_error (_("only 'MUL' is permitted"));
3039           return FALSE;
3040         }
3041       break;
3042
3043     case SHIFTED_MUL_VL:
3044       /* "MUL VL" consists of two separate tokens.  Require the first
3045          token to be "MUL" and look for a following "VL".  */
3046       if (kind == AARCH64_MOD_MUL)
3047         {
3048           skip_whitespace (p);
3049           if (strncasecmp (p, "vl", 2) == 0 && !ISALPHA (p[2]))
3050             {
3051               p += 2;
3052               kind = AARCH64_MOD_MUL_VL;
3053               break;
3054             }
3055         }
3056       set_syntax_error (_("only 'MUL VL' is permitted"));
3057       return FALSE;
3058
3059     case SHIFTED_REG_OFFSET:
3060       if (kind != AARCH64_MOD_UXTW && kind != AARCH64_MOD_LSL
3061           && kind != AARCH64_MOD_SXTW && kind != AARCH64_MOD_SXTX)
3062         {
3063           set_fatal_syntax_error
3064             (_("invalid shift for the register offset addressing mode"));
3065           return FALSE;
3066         }
3067       break;
3068
3069     case SHIFTED_LSL_MSL:
3070       if (kind != AARCH64_MOD_LSL && kind != AARCH64_MOD_MSL)
3071         {
3072           set_syntax_error (_("invalid shift operator"));
3073           return FALSE;
3074         }
3075       break;
3076
3077     default:
3078       abort ();
3079     }
3080
3081   /* Whitespace can appear here if the next thing is a bare digit.  */
3082   skip_whitespace (p);
3083
3084   /* Parse shift amount.  */
3085   exp_has_prefix = 0;
3086   if ((mode == SHIFTED_REG_OFFSET && *p == ']') || kind == AARCH64_MOD_MUL_VL)
3087     exp.X_op = O_absent;
3088   else
3089     {
3090       if (is_immediate_prefix (*p))
3091         {
3092           p++;
3093           exp_has_prefix = 1;
3094         }
3095       my_get_expression (&exp, &p, GE_NO_PREFIX, 0);
3096     }
3097   if (kind == AARCH64_MOD_MUL_VL)
3098     /* For consistency, give MUL VL the same shift amount as an implicit
3099        MUL #1.  */
3100     operand->shifter.amount = 1;
3101   else if (exp.X_op == O_absent)
3102     {
3103       if (!aarch64_extend_operator_p (kind) || exp_has_prefix)
3104         {
3105           set_syntax_error (_("missing shift amount"));
3106           return FALSE;
3107         }
3108       operand->shifter.amount = 0;
3109     }
3110   else if (exp.X_op != O_constant)
3111     {
3112       set_syntax_error (_("constant shift amount required"));
3113       return FALSE;
3114     }
3115   /* For parsing purposes, MUL #n has no inherent range.  The range
3116      depends on the operand and will be checked by operand-specific
3117      routines.  */
3118   else if (kind != AARCH64_MOD_MUL
3119            && (exp.X_add_number < 0 || exp.X_add_number > 63))
3120     {
3121       set_fatal_syntax_error (_("shift amount out of range 0 to 63"));
3122       return FALSE;
3123     }
3124   else
3125     {
3126       operand->shifter.amount = exp.X_add_number;
3127       operand->shifter.amount_present = 1;
3128     }
3129
3130   operand->shifter.operator_present = 1;
3131   operand->shifter.kind = kind;
3132
3133   *str = p;
3134   return TRUE;
3135 }
3136
3137 /* Parse a <shifter_operand> for a data processing instruction:
3138
3139       #<immediate>
3140       #<immediate>, LSL #imm
3141
3142    Validation of immediate operands is deferred to md_apply_fix.
3143
3144    Return TRUE on success; otherwise return FALSE.  */
3145
3146 static bfd_boolean
3147 parse_shifter_operand_imm (char **str, aarch64_opnd_info *operand,
3148                            enum parse_shift_mode mode)
3149 {
3150   char *p;
3151
3152   if (mode != SHIFTED_ARITH_IMM && mode != SHIFTED_LOGIC_IMM)
3153     return FALSE;
3154
3155   p = *str;
3156
3157   /* Accept an immediate expression.  */
3158   if (! my_get_expression (&inst.reloc.exp, &p, GE_OPT_PREFIX, 1))
3159     return FALSE;
3160
3161   /* Accept optional LSL for arithmetic immediate values.  */
3162   if (mode == SHIFTED_ARITH_IMM && skip_past_comma (&p))
3163     if (! parse_shift (&p, operand, SHIFTED_LSL))
3164       return FALSE;
3165
3166   /* Not accept any shifter for logical immediate values.  */
3167   if (mode == SHIFTED_LOGIC_IMM && skip_past_comma (&p)
3168       && parse_shift (&p, operand, mode))
3169     {
3170       set_syntax_error (_("unexpected shift operator"));
3171       return FALSE;
3172     }
3173
3174   *str = p;
3175   return TRUE;
3176 }
3177
3178 /* Parse a <shifter_operand> for a data processing instruction:
3179
3180       <Rm>
3181       <Rm>, <shift>
3182       #<immediate>
3183       #<immediate>, LSL #imm
3184
3185    where <shift> is handled by parse_shift above, and the last two
3186    cases are handled by the function above.
3187
3188    Validation of immediate operands is deferred to md_apply_fix.
3189
3190    Return TRUE on success; otherwise return FALSE.  */
3191
3192 static bfd_boolean
3193 parse_shifter_operand (char **str, aarch64_opnd_info *operand,
3194                        enum parse_shift_mode mode)
3195 {
3196   const reg_entry *reg;
3197   aarch64_opnd_qualifier_t qualifier;
3198   enum aarch64_operand_class opd_class
3199     = aarch64_get_operand_class (operand->type);
3200
3201   reg = aarch64_reg_parse_32_64 (str, &qualifier);
3202   if (reg)
3203     {
3204       if (opd_class == AARCH64_OPND_CLASS_IMMEDIATE)
3205         {
3206           set_syntax_error (_("unexpected register in the immediate operand"));
3207           return FALSE;
3208         }
3209
3210       if (!aarch64_check_reg_type (reg, REG_TYPE_R_Z))
3211         {
3212           set_syntax_error (_(get_reg_expected_msg (REG_TYPE_R_Z)));
3213           return FALSE;
3214         }
3215
3216       operand->reg.regno = reg->number;
3217       operand->qualifier = qualifier;
3218
3219       /* Accept optional shift operation on register.  */
3220       if (! skip_past_comma (str))
3221         return TRUE;
3222
3223       if (! parse_shift (str, operand, mode))
3224         return FALSE;
3225
3226       return TRUE;
3227     }
3228   else if (opd_class == AARCH64_OPND_CLASS_MODIFIED_REG)
3229     {
3230       set_syntax_error
3231         (_("integer register expected in the extended/shifted operand "
3232            "register"));
3233       return FALSE;
3234     }
3235
3236   /* We have a shifted immediate variable.  */
3237   return parse_shifter_operand_imm (str, operand, mode);
3238 }
3239
3240 /* Return TRUE on success; return FALSE otherwise.  */
3241
3242 static bfd_boolean
3243 parse_shifter_operand_reloc (char **str, aarch64_opnd_info *operand,
3244                              enum parse_shift_mode mode)
3245 {
3246   char *p = *str;
3247
3248   /* Determine if we have the sequence of characters #: or just :
3249      coming next.  If we do, then we check for a :rello: relocation
3250      modifier.  If we don't, punt the whole lot to
3251      parse_shifter_operand.  */
3252
3253   if ((p[0] == '#' && p[1] == ':') || p[0] == ':')
3254     {
3255       struct reloc_table_entry *entry;
3256
3257       if (p[0] == '#')
3258         p += 2;
3259       else
3260         p++;
3261       *str = p;
3262
3263       /* Try to parse a relocation.  Anything else is an error.  */
3264       if (!(entry = find_reloc_table_entry (str)))
3265         {
3266           set_syntax_error (_("unknown relocation modifier"));
3267           return FALSE;
3268         }
3269
3270       if (entry->add_type == 0)
3271         {
3272           set_syntax_error
3273             (_("this relocation modifier is not allowed on this instruction"));
3274           return FALSE;
3275         }
3276
3277       /* Save str before we decompose it.  */
3278       p = *str;
3279
3280       /* Next, we parse the expression.  */
3281       if (! my_get_expression (&inst.reloc.exp, str, GE_NO_PREFIX, 1))
3282         return FALSE;
3283
3284       /* Record the relocation type (use the ADD variant here).  */
3285       inst.reloc.type = entry->add_type;
3286       inst.reloc.pc_rel = entry->pc_rel;
3287
3288       /* If str is empty, we've reached the end, stop here.  */
3289       if (**str == '\0')
3290         return TRUE;
3291
3292       /* Otherwise, we have a shifted reloc modifier, so rewind to
3293          recover the variable name and continue parsing for the shifter.  */
3294       *str = p;
3295       return parse_shifter_operand_imm (str, operand, mode);
3296     }
3297
3298   return parse_shifter_operand (str, operand, mode);
3299 }
3300
3301 /* Parse all forms of an address expression.  Information is written
3302    to *OPERAND and/or inst.reloc.
3303
3304    The A64 instruction set has the following addressing modes:
3305
3306    Offset
3307      [base]                      // in SIMD ld/st structure
3308      [base{,#0}]                 // in ld/st exclusive
3309      [base{,#imm}]
3310      [base,Xm{,LSL #imm}]
3311      [base,Xm,SXTX {#imm}]
3312      [base,Wm,(S|U)XTW {#imm}]
3313    Pre-indexed
3314      [base,#imm]!
3315    Post-indexed
3316      [base],#imm
3317      [base],Xm                   // in SIMD ld/st structure
3318    PC-relative (literal)
3319      label
3320    SVE:
3321      [base,#imm,MUL VL]
3322      [base,Zm.D{,LSL #imm}]
3323      [base,Zm.S,(S|U)XTW {#imm}]
3324      [base,Zm.D,(S|U)XTW {#imm}] // ignores top 32 bits of Zm.D elements
3325      [Zn.S,#imm]
3326      [Zn.D,#imm]
3327      [Zn.S,Zm.S{,LSL #imm}]      // in ADR
3328      [Zn.D,Zm.D{,LSL #imm}]      // in ADR
3329      [Zn.D,Zm.D,(S|U)XTW {#imm}] // in ADR
3330
3331    (As a convenience, the notation "=immediate" is permitted in conjunction
3332    with the pc-relative literal load instructions to automatically place an
3333    immediate value or symbolic address in a nearby literal pool and generate
3334    a hidden label which references it.)
3335
3336    Upon a successful parsing, the address structure in *OPERAND will be
3337    filled in the following way:
3338
3339      .base_regno = <base>
3340      .offset.is_reg     // 1 if the offset is a register
3341      .offset.imm = <imm>
3342      .offset.regno = <Rm>
3343
3344    For different addressing modes defined in the A64 ISA:
3345
3346    Offset
3347      .pcrel=0; .preind=1; .postind=0; .writeback=0
3348    Pre-indexed
3349      .pcrel=0; .preind=1; .postind=0; .writeback=1
3350    Post-indexed
3351      .pcrel=0; .preind=0; .postind=1; .writeback=1
3352    PC-relative (literal)
3353      .pcrel=1; .preind=1; .postind=0; .writeback=0
3354
3355    The shift/extension information, if any, will be stored in .shifter.
3356    The base and offset qualifiers will be stored in *BASE_QUALIFIER and
3357    *OFFSET_QUALIFIER respectively, with NIL being used if there's no
3358    corresponding register.
3359
3360    BASE_TYPE says which types of base register should be accepted and
3361    OFFSET_TYPE says the same for offset registers.  IMM_SHIFT_MODE
3362    is the type of shifter that is allowed for immediate offsets,
3363    or SHIFTED_NONE if none.
3364
3365    In all other respects, it is the caller's responsibility to check
3366    for addressing modes not supported by the instruction, and to set
3367    inst.reloc.type.  */
3368
3369 static bfd_boolean
3370 parse_address_main (char **str, aarch64_opnd_info *operand,
3371                     aarch64_opnd_qualifier_t *base_qualifier,
3372                     aarch64_opnd_qualifier_t *offset_qualifier,
3373                     aarch64_reg_type base_type, aarch64_reg_type offset_type,
3374                     enum parse_shift_mode imm_shift_mode)
3375 {
3376   char *p = *str;
3377   const reg_entry *reg;
3378   expressionS *exp = &inst.reloc.exp;
3379
3380   *base_qualifier = AARCH64_OPND_QLF_NIL;
3381   *offset_qualifier = AARCH64_OPND_QLF_NIL;
3382   if (! skip_past_char (&p, '['))
3383     {
3384       /* =immediate or label.  */
3385       operand->addr.pcrel = 1;
3386       operand->addr.preind = 1;
3387
3388       /* #:<reloc_op>:<symbol>  */
3389       skip_past_char (&p, '#');
3390       if (skip_past_char (&p, ':'))
3391         {
3392           bfd_reloc_code_real_type ty;
3393           struct reloc_table_entry *entry;
3394
3395           /* Try to parse a relocation modifier.  Anything else is
3396              an error.  */
3397           entry = find_reloc_table_entry (&p);
3398           if (! entry)
3399             {
3400               set_syntax_error (_("unknown relocation modifier"));
3401               return FALSE;
3402             }
3403
3404           switch (operand->type)
3405             {
3406             case AARCH64_OPND_ADDR_PCREL21:
3407               /* adr */
3408               ty = entry->adr_type;
3409               break;
3410
3411             default:
3412               ty = entry->ld_literal_type;
3413               break;
3414             }
3415
3416           if (ty == 0)
3417             {
3418               set_syntax_error
3419                 (_("this relocation modifier is not allowed on this "
3420                    "instruction"));
3421               return FALSE;
3422             }
3423
3424           /* #:<reloc_op>:  */
3425           if (! my_get_expression (exp, &p, GE_NO_PREFIX, 1))
3426             {
3427               set_syntax_error (_("invalid relocation expression"));
3428               return FALSE;
3429             }
3430
3431           /* #:<reloc_op>:<expr>  */
3432           /* Record the relocation type.  */
3433           inst.reloc.type = ty;
3434           inst.reloc.pc_rel = entry->pc_rel;
3435         }
3436       else
3437         {
3438
3439           if (skip_past_char (&p, '='))
3440             /* =immediate; need to generate the literal in the literal pool. */
3441             inst.gen_lit_pool = 1;
3442
3443           if (!my_get_expression (exp, &p, GE_NO_PREFIX, 1))
3444             {
3445               set_syntax_error (_("invalid address"));
3446               return FALSE;
3447             }
3448         }
3449
3450       *str = p;
3451       return TRUE;
3452     }
3453
3454   /* [ */
3455
3456   reg = aarch64_addr_reg_parse (&p, base_type, base_qualifier);
3457   if (!reg || !aarch64_check_reg_type (reg, base_type))
3458     {
3459       set_syntax_error (_(get_reg_expected_msg (base_type)));
3460       return FALSE;
3461     }
3462   operand->addr.base_regno = reg->number;
3463
3464   /* [Xn */
3465   if (skip_past_comma (&p))
3466     {
3467       /* [Xn, */
3468       operand->addr.preind = 1;
3469
3470       reg = aarch64_addr_reg_parse (&p, offset_type, offset_qualifier);
3471       if (reg)
3472         {
3473           if (!aarch64_check_reg_type (reg, offset_type))
3474             {
3475               set_syntax_error (_(get_reg_expected_msg (offset_type)));
3476               return FALSE;
3477             }
3478
3479           /* [Xn,Rm  */
3480           operand->addr.offset.regno = reg->number;
3481           operand->addr.offset.is_reg = 1;
3482           /* Shifted index.  */
3483           if (skip_past_comma (&p))
3484             {
3485               /* [Xn,Rm,  */
3486               if (! parse_shift (&p, operand, SHIFTED_REG_OFFSET))
3487                 /* Use the diagnostics set in parse_shift, so not set new
3488                    error message here.  */
3489                 return FALSE;
3490             }
3491           /* We only accept:
3492              [base,Xm{,LSL #imm}]
3493              [base,Xm,SXTX {#imm}]
3494              [base,Wm,(S|U)XTW {#imm}]  */
3495           if (operand->shifter.kind == AARCH64_MOD_NONE
3496               || operand->shifter.kind == AARCH64_MOD_LSL
3497               || operand->shifter.kind == AARCH64_MOD_SXTX)
3498             {
3499               if (*offset_qualifier == AARCH64_OPND_QLF_W)
3500                 {
3501                   set_syntax_error (_("invalid use of 32-bit register offset"));
3502                   return FALSE;
3503                 }
3504               if (aarch64_get_qualifier_esize (*base_qualifier)
3505                   != aarch64_get_qualifier_esize (*offset_qualifier))
3506                 {
3507                   set_syntax_error (_("offset has different size from base"));
3508                   return FALSE;
3509                 }
3510             }
3511           else if (*offset_qualifier == AARCH64_OPND_QLF_X)
3512             {
3513               set_syntax_error (_("invalid use of 64-bit register offset"));
3514               return FALSE;
3515             }
3516         }
3517       else
3518         {
3519           /* [Xn,#:<reloc_op>:<symbol>  */
3520           skip_past_char (&p, '#');
3521           if (skip_past_char (&p, ':'))
3522             {
3523               struct reloc_table_entry *entry;
3524
3525               /* Try to parse a relocation modifier.  Anything else is
3526                  an error.  */
3527               if (!(entry = find_reloc_table_entry (&p)))
3528                 {
3529                   set_syntax_error (_("unknown relocation modifier"));
3530                   return FALSE;
3531                 }
3532
3533               if (entry->ldst_type == 0)
3534                 {
3535                   set_syntax_error
3536                     (_("this relocation modifier is not allowed on this "
3537                        "instruction"));
3538                   return FALSE;
3539                 }
3540
3541               /* [Xn,#:<reloc_op>:  */
3542               /* We now have the group relocation table entry corresponding to
3543                  the name in the assembler source.  Next, we parse the
3544                  expression.  */
3545               if (! my_get_expression (exp, &p, GE_NO_PREFIX, 1))
3546                 {
3547                   set_syntax_error (_("invalid relocation expression"));
3548                   return FALSE;
3549                 }
3550
3551               /* [Xn,#:<reloc_op>:<expr>  */
3552               /* Record the load/store relocation type.  */
3553               inst.reloc.type = entry->ldst_type;
3554               inst.reloc.pc_rel = entry->pc_rel;
3555             }
3556           else
3557             {
3558               if (! my_get_expression (exp, &p, GE_OPT_PREFIX, 1))
3559                 {
3560                   set_syntax_error (_("invalid expression in the address"));
3561                   return FALSE;
3562                 }
3563               /* [Xn,<expr>  */
3564               if (imm_shift_mode != SHIFTED_NONE && skip_past_comma (&p))
3565                 /* [Xn,<expr>,<shifter>  */
3566                 if (! parse_shift (&p, operand, imm_shift_mode))
3567                   return FALSE;
3568             }
3569         }
3570     }
3571
3572   if (! skip_past_char (&p, ']'))
3573     {
3574       set_syntax_error (_("']' expected"));
3575       return FALSE;
3576     }
3577
3578   if (skip_past_char (&p, '!'))
3579     {
3580       if (operand->addr.preind && operand->addr.offset.is_reg)
3581         {
3582           set_syntax_error (_("register offset not allowed in pre-indexed "
3583                               "addressing mode"));
3584           return FALSE;
3585         }
3586       /* [Xn]! */
3587       operand->addr.writeback = 1;
3588     }
3589   else if (skip_past_comma (&p))
3590     {
3591       /* [Xn], */
3592       operand->addr.postind = 1;
3593       operand->addr.writeback = 1;
3594
3595       if (operand->addr.preind)
3596         {
3597           set_syntax_error (_("cannot combine pre- and post-indexing"));
3598           return FALSE;
3599         }
3600
3601       reg = aarch64_reg_parse_32_64 (&p, offset_qualifier);
3602       if (reg)
3603         {
3604           /* [Xn],Xm */
3605           if (!aarch64_check_reg_type (reg, REG_TYPE_R_64))
3606             {
3607               set_syntax_error (_(get_reg_expected_msg (REG_TYPE_R_64)));
3608               return FALSE;
3609             }
3610
3611           operand->addr.offset.regno = reg->number;
3612           operand->addr.offset.is_reg = 1;
3613         }
3614       else if (! my_get_expression (exp, &p, GE_OPT_PREFIX, 1))
3615         {
3616           /* [Xn],#expr */
3617           set_syntax_error (_("invalid expression in the address"));
3618           return FALSE;
3619         }
3620     }
3621
3622   /* If at this point neither .preind nor .postind is set, we have a
3623      bare [Rn]{!}; reject [Rn]! but accept [Rn] as a shorthand for [Rn,#0].  */
3624   if (operand->addr.preind == 0 && operand->addr.postind == 0)
3625     {
3626       if (operand->addr.writeback)
3627         {
3628           /* Reject [Rn]!   */
3629           set_syntax_error (_("missing offset in the pre-indexed address"));
3630           return FALSE;
3631         }
3632       operand->addr.preind = 1;
3633       inst.reloc.exp.X_op = O_constant;
3634       inst.reloc.exp.X_add_number = 0;
3635     }
3636
3637   *str = p;
3638   return TRUE;
3639 }
3640
3641 /* Parse a base AArch64 address (as opposed to an SVE one).  Return TRUE
3642    on success.  */
3643 static bfd_boolean
3644 parse_address (char **str, aarch64_opnd_info *operand)
3645 {
3646   aarch64_opnd_qualifier_t base_qualifier, offset_qualifier;
3647   return parse_address_main (str, operand, &base_qualifier, &offset_qualifier,
3648                              REG_TYPE_R64_SP, REG_TYPE_R_Z, SHIFTED_NONE);
3649 }
3650
3651 /* Parse an address in which SVE vector registers and MUL VL are allowed.
3652    The arguments have the same meaning as for parse_address_main.
3653    Return TRUE on success.  */
3654 static bfd_boolean
3655 parse_sve_address (char **str, aarch64_opnd_info *operand,
3656                    aarch64_opnd_qualifier_t *base_qualifier,
3657                    aarch64_opnd_qualifier_t *offset_qualifier)
3658 {
3659   return parse_address_main (str, operand, base_qualifier, offset_qualifier,
3660                              REG_TYPE_SVE_BASE, REG_TYPE_SVE_OFFSET,
3661                              SHIFTED_MUL_VL);
3662 }
3663
3664 /* Parse an operand for a MOVZ, MOVN or MOVK instruction.
3665    Return TRUE on success; otherwise return FALSE.  */
3666 static bfd_boolean
3667 parse_half (char **str, int *internal_fixup_p)
3668 {
3669   char *p = *str;
3670
3671   skip_past_char (&p, '#');
3672
3673   gas_assert (internal_fixup_p);
3674   *internal_fixup_p = 0;
3675
3676   if (*p == ':')
3677     {
3678       struct reloc_table_entry *entry;
3679
3680       /* Try to parse a relocation.  Anything else is an error.  */
3681       ++p;
3682       if (!(entry = find_reloc_table_entry (&p)))
3683         {
3684           set_syntax_error (_("unknown relocation modifier"));
3685           return FALSE;
3686         }
3687
3688       if (entry->movw_type == 0)
3689         {
3690           set_syntax_error
3691             (_("this relocation modifier is not allowed on this instruction"));
3692           return FALSE;
3693         }
3694
3695       inst.reloc.type = entry->movw_type;
3696     }
3697   else
3698     *internal_fixup_p = 1;
3699
3700   if (! my_get_expression (&inst.reloc.exp, &p, GE_NO_PREFIX, 1))
3701     return FALSE;
3702
3703   *str = p;
3704   return TRUE;
3705 }
3706
3707 /* Parse an operand for an ADRP instruction:
3708      ADRP <Xd>, <label>
3709    Return TRUE on success; otherwise return FALSE.  */
3710
3711 static bfd_boolean
3712 parse_adrp (char **str)
3713 {
3714   char *p;
3715
3716   p = *str;
3717   if (*p == ':')
3718     {
3719       struct reloc_table_entry *entry;
3720
3721       /* Try to parse a relocation.  Anything else is an error.  */
3722       ++p;
3723       if (!(entry = find_reloc_table_entry (&p)))
3724         {
3725           set_syntax_error (_("unknown relocation modifier"));
3726           return FALSE;
3727         }
3728
3729       if (entry->adrp_type == 0)
3730         {
3731           set_syntax_error
3732             (_("this relocation modifier is not allowed on this instruction"));
3733           return FALSE;
3734         }
3735
3736       inst.reloc.type = entry->adrp_type;
3737     }
3738   else
3739     inst.reloc.type = BFD_RELOC_AARCH64_ADR_HI21_PCREL;
3740
3741   inst.reloc.pc_rel = 1;
3742
3743   if (! my_get_expression (&inst.reloc.exp, &p, GE_NO_PREFIX, 1))
3744     return FALSE;
3745
3746   *str = p;
3747   return TRUE;
3748 }
3749
3750 /* Miscellaneous. */
3751
3752 /* Parse a symbolic operand such as "pow2" at *STR.  ARRAY is an array
3753    of SIZE tokens in which index I gives the token for field value I,
3754    or is null if field value I is invalid.  REG_TYPE says which register
3755    names should be treated as registers rather than as symbolic immediates.
3756
3757    Return true on success, moving *STR past the operand and storing the
3758    field value in *VAL.  */
3759
3760 static int
3761 parse_enum_string (char **str, int64_t *val, const char *const *array,
3762                    size_t size, aarch64_reg_type reg_type)
3763 {
3764   expressionS exp;
3765   char *p, *q;
3766   size_t i;
3767
3768   /* Match C-like tokens.  */
3769   p = q = *str;
3770   while (ISALNUM (*q))
3771     q++;
3772
3773   for (i = 0; i < size; ++i)
3774     if (array[i]
3775         && strncasecmp (array[i], p, q - p) == 0
3776         && array[i][q - p] == 0)
3777       {
3778         *val = i;
3779         *str = q;
3780         return TRUE;
3781       }
3782
3783   if (!parse_immediate_expression (&p, &exp, reg_type))
3784     return FALSE;
3785
3786   if (exp.X_op == O_constant
3787       && (uint64_t) exp.X_add_number < size)
3788     {
3789       *val = exp.X_add_number;
3790       *str = p;
3791       return TRUE;
3792     }
3793
3794   /* Use the default error for this operand.  */
3795   return FALSE;
3796 }
3797
3798 /* Parse an option for a preload instruction.  Returns the encoding for the
3799    option, or PARSE_FAIL.  */
3800
3801 static int
3802 parse_pldop (char **str)
3803 {
3804   char *p, *q;
3805   const struct aarch64_name_value_pair *o;
3806
3807   p = q = *str;
3808   while (ISALNUM (*q))
3809     q++;
3810
3811   o = hash_find_n (aarch64_pldop_hsh, p, q - p);
3812   if (!o)
3813     return PARSE_FAIL;
3814
3815   *str = q;
3816   return o->value;
3817 }
3818
3819 /* Parse an option for a barrier instruction.  Returns the encoding for the
3820    option, or PARSE_FAIL.  */
3821
3822 static int
3823 parse_barrier (char **str)
3824 {
3825   char *p, *q;
3826   const asm_barrier_opt *o;
3827
3828   p = q = *str;
3829   while (ISALPHA (*q))
3830     q++;
3831
3832   o = hash_find_n (aarch64_barrier_opt_hsh, p, q - p);
3833   if (!o)
3834     return PARSE_FAIL;
3835
3836   *str = q;
3837   return o->value;
3838 }
3839
3840 /* Parse an operand for a PSB barrier.  Set *HINT_OPT to the hint-option record
3841    return 0 if successful.  Otherwise return PARSE_FAIL.  */
3842
3843 static int
3844 parse_barrier_psb (char **str,
3845                    const struct aarch64_name_value_pair ** hint_opt)
3846 {
3847   char *p, *q;
3848   const struct aarch64_name_value_pair *o;
3849
3850   p = q = *str;
3851   while (ISALPHA (*q))
3852     q++;
3853
3854   o = hash_find_n (aarch64_hint_opt_hsh, p, q - p);
3855   if (!o)
3856     {
3857       set_fatal_syntax_error
3858         ( _("unknown or missing option to PSB"));
3859       return PARSE_FAIL;
3860     }
3861
3862   if (o->value != 0x11)
3863     {
3864       /* PSB only accepts option name 'CSYNC'.  */
3865       set_syntax_error
3866         (_("the specified option is not accepted for PSB"));
3867       return PARSE_FAIL;
3868     }
3869
3870   *str = q;
3871   *hint_opt = o;
3872   return 0;
3873 }
3874
3875 /* Parse a system register or a PSTATE field name for an MSR/MRS instruction.
3876    Returns the encoding for the option, or PARSE_FAIL.
3877
3878    If IMPLE_DEFINED_P is non-zero, the function will also try to parse the
3879    implementation defined system register name S<op0>_<op1>_<Cn>_<Cm>_<op2>.
3880
3881    If PSTATEFIELD_P is non-zero, the function will parse the name as a PSTATE
3882    field, otherwise as a system register.
3883 */
3884
3885 static int
3886 parse_sys_reg (char **str, struct hash_control *sys_regs,
3887                int imple_defined_p, int pstatefield_p)
3888 {
3889   char *p, *q;
3890   char buf[32];
3891   const aarch64_sys_reg *o;
3892   int value;
3893
3894   p = buf;
3895   for (q = *str; ISALNUM (*q) || *q == '_'; q++)
3896     if (p < buf + 31)
3897       *p++ = TOLOWER (*q);
3898   *p = '\0';
3899   /* Assert that BUF be large enough.  */
3900   gas_assert (p - buf == q - *str);
3901
3902   o = hash_find (sys_regs, buf);
3903   if (!o)
3904     {
3905       if (!imple_defined_p)
3906         return PARSE_FAIL;
3907       else
3908         {
3909           /* Parse S<op0>_<op1>_<Cn>_<Cm>_<op2>.  */
3910           unsigned int op0, op1, cn, cm, op2;
3911
3912           if (sscanf (buf, "s%u_%u_c%u_c%u_%u", &op0, &op1, &cn, &cm, &op2)
3913               != 5)
3914             return PARSE_FAIL;
3915           if (op0 > 3 || op1 > 7 || cn > 15 || cm > 15 || op2 > 7)
3916             return PARSE_FAIL;
3917           value = (op0 << 14) | (op1 << 11) | (cn << 7) | (cm << 3) | op2;
3918         }
3919     }
3920   else
3921     {
3922       if (pstatefield_p && !aarch64_pstatefield_supported_p (cpu_variant, o))
3923         as_bad (_("selected processor does not support PSTATE field "
3924                   "name '%s'"), buf);
3925       if (!pstatefield_p && !aarch64_sys_reg_supported_p (cpu_variant, o))
3926         as_bad (_("selected processor does not support system register "
3927                   "name '%s'"), buf);
3928       if (aarch64_sys_reg_deprecated_p (o))
3929         as_warn (_("system register name '%s' is deprecated and may be "
3930                    "removed in a future release"), buf);
3931       value = o->value;
3932     }
3933
3934   *str = q;
3935   return value;
3936 }
3937
3938 /* Parse a system reg for ic/dc/at/tlbi instructions.  Returns the table entry
3939    for the option, or NULL.  */
3940
3941 static const aarch64_sys_ins_reg *
3942 parse_sys_ins_reg (char **str, struct hash_control *sys_ins_regs)
3943 {
3944   char *p, *q;
3945   char buf[32];
3946   const aarch64_sys_ins_reg *o;
3947
3948   p = buf;
3949   for (q = *str; ISALNUM (*q) || *q == '_'; q++)
3950     if (p < buf + 31)
3951       *p++ = TOLOWER (*q);
3952   *p = '\0';
3953
3954   o = hash_find (sys_ins_regs, buf);
3955   if (!o)
3956     return NULL;
3957
3958   if (!aarch64_sys_ins_reg_supported_p (cpu_variant, o))
3959     as_bad (_("selected processor does not support system register "
3960               "name '%s'"), buf);
3961
3962   *str = q;
3963   return o;
3964 }
3965 \f
3966 #define po_char_or_fail(chr) do {                               \
3967     if (! skip_past_char (&str, chr))                           \
3968       goto failure;                                             \
3969 } while (0)
3970
3971 #define po_reg_or_fail(regtype) do {                            \
3972     val = aarch64_reg_parse (&str, regtype, &rtype, NULL);      \
3973     if (val == PARSE_FAIL)                                      \
3974       {                                                         \
3975         set_default_error ();                                   \
3976         goto failure;                                           \
3977       }                                                         \
3978   } while (0)
3979
3980 #define po_int_reg_or_fail(reg_type) do {                       \
3981     reg = aarch64_reg_parse_32_64 (&str, &qualifier);           \
3982     if (!reg || !aarch64_check_reg_type (reg, reg_type))        \
3983       {                                                         \
3984         set_default_error ();                                   \
3985         goto failure;                                           \
3986       }                                                         \
3987     info->reg.regno = reg->number;                              \
3988     info->qualifier = qualifier;                                \
3989   } while (0)
3990
3991 #define po_imm_nc_or_fail() do {                                \
3992     if (! parse_constant_immediate (&str, &val, imm_reg_type))  \
3993       goto failure;                                             \
3994   } while (0)
3995
3996 #define po_imm_or_fail(min, max) do {                           \
3997     if (! parse_constant_immediate (&str, &val, imm_reg_type))  \
3998       goto failure;                                             \
3999     if (val < min || val > max)                                 \
4000       {                                                         \
4001         set_fatal_syntax_error (_("immediate value out of range "\
4002 #min " to "#max));                                              \
4003         goto failure;                                           \
4004       }                                                         \
4005   } while (0)
4006
4007 #define po_enum_or_fail(array) do {                             \
4008     if (!parse_enum_string (&str, &val, array,                  \
4009                             ARRAY_SIZE (array), imm_reg_type))  \
4010       goto failure;                                             \
4011   } while (0)
4012
4013 #define po_misc_or_fail(expr) do {                              \
4014     if (!expr)                                                  \
4015       goto failure;                                             \
4016   } while (0)
4017 \f
4018 /* encode the 12-bit imm field of Add/sub immediate */
4019 static inline uint32_t
4020 encode_addsub_imm (uint32_t imm)
4021 {
4022   return imm << 10;
4023 }
4024
4025 /* encode the shift amount field of Add/sub immediate */
4026 static inline uint32_t
4027 encode_addsub_imm_shift_amount (uint32_t cnt)
4028 {
4029   return cnt << 22;
4030 }
4031
4032
4033 /* encode the imm field of Adr instruction */
4034 static inline uint32_t
4035 encode_adr_imm (uint32_t imm)
4036 {
4037   return (((imm & 0x3) << 29)   /*  [1:0] -> [30:29] */
4038           | ((imm & (0x7ffff << 2)) << 3));     /* [20:2] -> [23:5]  */
4039 }
4040
4041 /* encode the immediate field of Move wide immediate */
4042 static inline uint32_t
4043 encode_movw_imm (uint32_t imm)
4044 {
4045   return imm << 5;
4046 }
4047
4048 /* encode the 26-bit offset of unconditional branch */
4049 static inline uint32_t
4050 encode_branch_ofs_26 (uint32_t ofs)
4051 {
4052   return ofs & ((1 << 26) - 1);
4053 }
4054
4055 /* encode the 19-bit offset of conditional branch and compare & branch */
4056 static inline uint32_t
4057 encode_cond_branch_ofs_19 (uint32_t ofs)
4058 {
4059   return (ofs & ((1 << 19) - 1)) << 5;
4060 }
4061
4062 /* encode the 19-bit offset of ld literal */
4063 static inline uint32_t
4064 encode_ld_lit_ofs_19 (uint32_t ofs)
4065 {
4066   return (ofs & ((1 << 19) - 1)) << 5;
4067 }
4068
4069 /* Encode the 14-bit offset of test & branch.  */
4070 static inline uint32_t
4071 encode_tst_branch_ofs_14 (uint32_t ofs)
4072 {
4073   return (ofs & ((1 << 14) - 1)) << 5;
4074 }
4075
4076 /* Encode the 16-bit imm field of svc/hvc/smc.  */
4077 static inline uint32_t
4078 encode_svc_imm (uint32_t imm)
4079 {
4080   return imm << 5;
4081 }
4082
4083 /* Reencode add(s) to sub(s), or sub(s) to add(s).  */
4084 static inline uint32_t
4085 reencode_addsub_switch_add_sub (uint32_t opcode)
4086 {
4087   return opcode ^ (1 << 30);
4088 }
4089
4090 static inline uint32_t
4091 reencode_movzn_to_movz (uint32_t opcode)
4092 {
4093   return opcode | (1 << 30);
4094 }
4095
4096 static inline uint32_t
4097 reencode_movzn_to_movn (uint32_t opcode)
4098 {
4099   return opcode & ~(1 << 30);
4100 }
4101
4102 /* Overall per-instruction processing.  */
4103
4104 /* We need to be able to fix up arbitrary expressions in some statements.
4105    This is so that we can handle symbols that are an arbitrary distance from
4106    the pc.  The most common cases are of the form ((+/-sym -/+ . - 8) & mask),
4107    which returns part of an address in a form which will be valid for
4108    a data instruction.  We do this by pushing the expression into a symbol
4109    in the expr_section, and creating a fix for that.  */
4110
4111 static fixS *
4112 fix_new_aarch64 (fragS * frag,
4113                  int where,
4114                  short int size, expressionS * exp, int pc_rel, int reloc)
4115 {
4116   fixS *new_fix;
4117
4118   switch (exp->X_op)
4119     {
4120     case O_constant:
4121     case O_symbol:
4122     case O_add:
4123     case O_subtract:
4124       new_fix = fix_new_exp (frag, where, size, exp, pc_rel, reloc);
4125       break;
4126
4127     default:
4128       new_fix = fix_new (frag, where, size, make_expr_symbol (exp), 0,
4129                          pc_rel, reloc);
4130       break;
4131     }
4132   return new_fix;
4133 }
4134 \f
4135 /* Diagnostics on operands errors.  */
4136
4137 /* By default, output verbose error message.
4138    Disable the verbose error message by -mno-verbose-error.  */
4139 static int verbose_error_p = 1;
4140
4141 #ifdef DEBUG_AARCH64
4142 /* N.B. this is only for the purpose of debugging.  */
4143 const char* operand_mismatch_kind_names[] =
4144 {
4145   "AARCH64_OPDE_NIL",
4146   "AARCH64_OPDE_RECOVERABLE",
4147   "AARCH64_OPDE_SYNTAX_ERROR",
4148   "AARCH64_OPDE_FATAL_SYNTAX_ERROR",
4149   "AARCH64_OPDE_INVALID_VARIANT",
4150   "AARCH64_OPDE_OUT_OF_RANGE",
4151   "AARCH64_OPDE_UNALIGNED",
4152   "AARCH64_OPDE_REG_LIST",
4153   "AARCH64_OPDE_OTHER_ERROR",
4154 };
4155 #endif /* DEBUG_AARCH64 */
4156
4157 /* Return TRUE if LHS is of higher severity than RHS, otherwise return FALSE.
4158
4159    When multiple errors of different kinds are found in the same assembly
4160    line, only the error of the highest severity will be picked up for
4161    issuing the diagnostics.  */
4162
4163 static inline bfd_boolean
4164 operand_error_higher_severity_p (enum aarch64_operand_error_kind lhs,
4165                                  enum aarch64_operand_error_kind rhs)
4166 {
4167   gas_assert (AARCH64_OPDE_RECOVERABLE > AARCH64_OPDE_NIL);
4168   gas_assert (AARCH64_OPDE_SYNTAX_ERROR > AARCH64_OPDE_RECOVERABLE);
4169   gas_assert (AARCH64_OPDE_FATAL_SYNTAX_ERROR > AARCH64_OPDE_SYNTAX_ERROR);
4170   gas_assert (AARCH64_OPDE_INVALID_VARIANT > AARCH64_OPDE_FATAL_SYNTAX_ERROR);
4171   gas_assert (AARCH64_OPDE_OUT_OF_RANGE > AARCH64_OPDE_INVALID_VARIANT);
4172   gas_assert (AARCH64_OPDE_UNALIGNED > AARCH64_OPDE_OUT_OF_RANGE);
4173   gas_assert (AARCH64_OPDE_REG_LIST > AARCH64_OPDE_UNALIGNED);
4174   gas_assert (AARCH64_OPDE_OTHER_ERROR > AARCH64_OPDE_REG_LIST);
4175   return lhs > rhs;
4176 }
4177
4178 /* Helper routine to get the mnemonic name from the assembly instruction
4179    line; should only be called for the diagnosis purpose, as there is
4180    string copy operation involved, which may affect the runtime
4181    performance if used in elsewhere.  */
4182
4183 static const char*
4184 get_mnemonic_name (const char *str)
4185 {
4186   static char mnemonic[32];
4187   char *ptr;
4188
4189   /* Get the first 15 bytes and assume that the full name is included.  */
4190   strncpy (mnemonic, str, 31);
4191   mnemonic[31] = '\0';
4192
4193   /* Scan up to the end of the mnemonic, which must end in white space,
4194      '.', or end of string.  */
4195   for (ptr = mnemonic; is_part_of_name(*ptr); ++ptr)
4196     ;
4197
4198   *ptr = '\0';
4199
4200   /* Append '...' to the truncated long name.  */
4201   if (ptr - mnemonic == 31)
4202     mnemonic[28] = mnemonic[29] = mnemonic[30] = '.';
4203
4204   return mnemonic;
4205 }
4206
4207 static void
4208 reset_aarch64_instruction (aarch64_instruction *instruction)
4209 {
4210   memset (instruction, '\0', sizeof (aarch64_instruction));
4211   instruction->reloc.type = BFD_RELOC_UNUSED;
4212 }
4213
4214 /* Data structures storing one user error in the assembly code related to
4215    operands.  */
4216
4217 struct operand_error_record
4218 {
4219   const aarch64_opcode *opcode;
4220   aarch64_operand_error detail;
4221   struct operand_error_record *next;
4222 };
4223
4224 typedef struct operand_error_record operand_error_record;
4225
4226 struct operand_errors
4227 {
4228   operand_error_record *head;
4229   operand_error_record *tail;
4230 };
4231
4232 typedef struct operand_errors operand_errors;
4233
4234 /* Top-level data structure reporting user errors for the current line of
4235    the assembly code.
4236    The way md_assemble works is that all opcodes sharing the same mnemonic
4237    name are iterated to find a match to the assembly line.  In this data
4238    structure, each of the such opcodes will have one operand_error_record
4239    allocated and inserted.  In other words, excessive errors related with
4240    a single opcode are disregarded.  */
4241 operand_errors operand_error_report;
4242
4243 /* Free record nodes.  */
4244 static operand_error_record *free_opnd_error_record_nodes = NULL;
4245
4246 /* Initialize the data structure that stores the operand mismatch
4247    information on assembling one line of the assembly code.  */
4248 static void
4249 init_operand_error_report (void)
4250 {
4251   if (operand_error_report.head != NULL)
4252     {
4253       gas_assert (operand_error_report.tail != NULL);
4254       operand_error_report.tail->next = free_opnd_error_record_nodes;
4255       free_opnd_error_record_nodes = operand_error_report.head;
4256       operand_error_report.head = NULL;
4257       operand_error_report.tail = NULL;
4258       return;
4259     }
4260   gas_assert (operand_error_report.tail == NULL);
4261 }
4262
4263 /* Return TRUE if some operand error has been recorded during the
4264    parsing of the current assembly line using the opcode *OPCODE;
4265    otherwise return FALSE.  */
4266 static inline bfd_boolean
4267 opcode_has_operand_error_p (const aarch64_opcode *opcode)
4268 {
4269   operand_error_record *record = operand_error_report.head;
4270   return record && record->opcode == opcode;
4271 }
4272
4273 /* Add the error record *NEW_RECORD to operand_error_report.  The record's
4274    OPCODE field is initialized with OPCODE.
4275    N.B. only one record for each opcode, i.e. the maximum of one error is
4276    recorded for each instruction template.  */
4277
4278 static void
4279 add_operand_error_record (const operand_error_record* new_record)
4280 {
4281   const aarch64_opcode *opcode = new_record->opcode;
4282   operand_error_record* record = operand_error_report.head;
4283
4284   /* The record may have been created for this opcode.  If not, we need
4285      to prepare one.  */
4286   if (! opcode_has_operand_error_p (opcode))
4287     {
4288       /* Get one empty record.  */
4289       if (free_opnd_error_record_nodes == NULL)
4290         {
4291           record = XNEW (operand_error_record);
4292         }
4293       else
4294         {
4295           record = free_opnd_error_record_nodes;
4296           free_opnd_error_record_nodes = record->next;
4297         }
4298       record->opcode = opcode;
4299       /* Insert at the head.  */
4300       record->next = operand_error_report.head;
4301       operand_error_report.head = record;
4302       if (operand_error_report.tail == NULL)
4303         operand_error_report.tail = record;
4304     }
4305   else if (record->detail.kind != AARCH64_OPDE_NIL
4306            && record->detail.index <= new_record->detail.index
4307            && operand_error_higher_severity_p (record->detail.kind,
4308                                                new_record->detail.kind))
4309     {
4310       /* In the case of multiple errors found on operands related with a
4311          single opcode, only record the error of the leftmost operand and
4312          only if the error is of higher severity.  */
4313       DEBUG_TRACE ("error %s on operand %d not added to the report due to"
4314                    " the existing error %s on operand %d",
4315                    operand_mismatch_kind_names[new_record->detail.kind],
4316                    new_record->detail.index,
4317                    operand_mismatch_kind_names[record->detail.kind],
4318                    record->detail.index);
4319       return;
4320     }
4321
4322   record->detail = new_record->detail;
4323 }
4324
4325 static inline void
4326 record_operand_error_info (const aarch64_opcode *opcode,
4327                            aarch64_operand_error *error_info)
4328 {
4329   operand_error_record record;
4330   record.opcode = opcode;
4331   record.detail = *error_info;
4332   add_operand_error_record (&record);
4333 }
4334
4335 /* Record an error of kind KIND and, if ERROR is not NULL, of the detailed
4336    error message *ERROR, for operand IDX (count from 0).  */
4337
4338 static void
4339 record_operand_error (const aarch64_opcode *opcode, int idx,
4340                       enum aarch64_operand_error_kind kind,
4341                       const char* error)
4342 {
4343   aarch64_operand_error info;
4344   memset(&info, 0, sizeof (info));
4345   info.index = idx;
4346   info.kind = kind;
4347   info.error = error;
4348   record_operand_error_info (opcode, &info);
4349 }
4350
4351 static void
4352 record_operand_error_with_data (const aarch64_opcode *opcode, int idx,
4353                                 enum aarch64_operand_error_kind kind,
4354                                 const char* error, const int *extra_data)
4355 {
4356   aarch64_operand_error info;
4357   info.index = idx;
4358   info.kind = kind;
4359   info.error = error;
4360   info.data[0] = extra_data[0];
4361   info.data[1] = extra_data[1];
4362   info.data[2] = extra_data[2];
4363   record_operand_error_info (opcode, &info);
4364 }
4365
4366 static void
4367 record_operand_out_of_range_error (const aarch64_opcode *opcode, int idx,
4368                                    const char* error, int lower_bound,
4369                                    int upper_bound)
4370 {
4371   int data[3] = {lower_bound, upper_bound, 0};
4372   record_operand_error_with_data (opcode, idx, AARCH64_OPDE_OUT_OF_RANGE,
4373                                   error, data);
4374 }
4375
4376 /* Remove the operand error record for *OPCODE.  */
4377 static void ATTRIBUTE_UNUSED
4378 remove_operand_error_record (const aarch64_opcode *opcode)
4379 {
4380   if (opcode_has_operand_error_p (opcode))
4381     {
4382       operand_error_record* record = operand_error_report.head;
4383       gas_assert (record != NULL && operand_error_report.tail != NULL);
4384       operand_error_report.head = record->next;
4385       record->next = free_opnd_error_record_nodes;
4386       free_opnd_error_record_nodes = record;
4387       if (operand_error_report.head == NULL)
4388         {
4389           gas_assert (operand_error_report.tail == record);
4390           operand_error_report.tail = NULL;
4391         }
4392     }
4393 }
4394
4395 /* Given the instruction in *INSTR, return the index of the best matched
4396    qualifier sequence in the list (an array) headed by QUALIFIERS_LIST.
4397
4398    Return -1 if there is no qualifier sequence; return the first match
4399    if there is multiple matches found.  */
4400
4401 static int
4402 find_best_match (const aarch64_inst *instr,
4403                  const aarch64_opnd_qualifier_seq_t *qualifiers_list)
4404 {
4405   int i, num_opnds, max_num_matched, idx;
4406
4407   num_opnds = aarch64_num_of_operands (instr->opcode);
4408   if (num_opnds == 0)
4409     {
4410       DEBUG_TRACE ("no operand");
4411       return -1;
4412     }
4413
4414   max_num_matched = 0;
4415   idx = 0;
4416
4417   /* For each pattern.  */
4418   for (i = 0; i < AARCH64_MAX_QLF_SEQ_NUM; ++i, ++qualifiers_list)
4419     {
4420       int j, num_matched;
4421       const aarch64_opnd_qualifier_t *qualifiers = *qualifiers_list;
4422
4423       /* Most opcodes has much fewer patterns in the list.  */
4424       if (empty_qualifier_sequence_p (qualifiers))
4425         {
4426           DEBUG_TRACE_IF (i == 0, "empty list of qualifier sequence");
4427           break;
4428         }
4429
4430       for (j = 0, num_matched = 0; j < num_opnds; ++j, ++qualifiers)
4431         if (*qualifiers == instr->operands[j].qualifier)
4432           ++num_matched;
4433
4434       if (num_matched > max_num_matched)
4435         {
4436           max_num_matched = num_matched;
4437           idx = i;
4438         }
4439     }
4440
4441   DEBUG_TRACE ("return with %d", idx);
4442   return idx;
4443 }
4444
4445 /* Assign qualifiers in the qualifier sequence (headed by QUALIFIERS) to the
4446    corresponding operands in *INSTR.  */
4447
4448 static inline void
4449 assign_qualifier_sequence (aarch64_inst *instr,
4450                            const aarch64_opnd_qualifier_t *qualifiers)
4451 {
4452   int i = 0;
4453   int num_opnds = aarch64_num_of_operands (instr->opcode);
4454   gas_assert (num_opnds);
4455   for (i = 0; i < num_opnds; ++i, ++qualifiers)
4456     instr->operands[i].qualifier = *qualifiers;
4457 }
4458
4459 /* Print operands for the diagnosis purpose.  */
4460
4461 static void
4462 print_operands (char *buf, const aarch64_opcode *opcode,
4463                 const aarch64_opnd_info *opnds)
4464 {
4465   int i;
4466
4467   for (i = 0; i < AARCH64_MAX_OPND_NUM; ++i)
4468     {
4469       char str[128];
4470
4471       /* We regard the opcode operand info more, however we also look into
4472          the inst->operands to support the disassembling of the optional
4473          operand.
4474          The two operand code should be the same in all cases, apart from
4475          when the operand can be optional.  */
4476       if (opcode->operands[i] == AARCH64_OPND_NIL
4477           || opnds[i].type == AARCH64_OPND_NIL)
4478         break;
4479
4480       /* Generate the operand string in STR.  */
4481       aarch64_print_operand (str, sizeof (str), 0, opcode, opnds, i, NULL, NULL);
4482
4483       /* Delimiter.  */
4484       if (str[0] != '\0')
4485         strcat (buf, i == 0 ? " " : ", ");
4486
4487       /* Append the operand string.  */
4488       strcat (buf, str);
4489     }
4490 }
4491
4492 /* Send to stderr a string as information.  */
4493
4494 static void
4495 output_info (const char *format, ...)
4496 {
4497   const char *file;
4498   unsigned int line;
4499   va_list args;
4500
4501   file = as_where (&line);
4502   if (file)
4503     {
4504       if (line != 0)
4505         fprintf (stderr, "%s:%u: ", file, line);
4506       else
4507         fprintf (stderr, "%s: ", file);
4508     }
4509   fprintf (stderr, _("Info: "));
4510   va_start (args, format);
4511   vfprintf (stderr, format, args);
4512   va_end (args);
4513   (void) putc ('\n', stderr);
4514 }
4515
4516 /* Output one operand error record.  */
4517
4518 static void
4519 output_operand_error_record (const operand_error_record *record, char *str)
4520 {
4521   const aarch64_operand_error *detail = &record->detail;
4522   int idx = detail->index;
4523   const aarch64_opcode *opcode = record->opcode;
4524   enum aarch64_opnd opd_code = (idx >= 0 ? opcode->operands[idx]
4525                                 : AARCH64_OPND_NIL);
4526
4527   switch (detail->kind)
4528     {
4529     case AARCH64_OPDE_NIL:
4530       gas_assert (0);
4531       break;
4532
4533     case AARCH64_OPDE_SYNTAX_ERROR:
4534     case AARCH64_OPDE_RECOVERABLE:
4535     case AARCH64_OPDE_FATAL_SYNTAX_ERROR:
4536     case AARCH64_OPDE_OTHER_ERROR:
4537       /* Use the prepared error message if there is, otherwise use the
4538          operand description string to describe the error.  */
4539       if (detail->error != NULL)
4540         {
4541           if (idx < 0)
4542             as_bad (_("%s -- `%s'"), detail->error, str);
4543           else
4544             as_bad (_("%s at operand %d -- `%s'"),
4545                     detail->error, idx + 1, str);
4546         }
4547       else
4548         {
4549           gas_assert (idx >= 0);
4550           as_bad (_("operand %d must be %s -- `%s'"), idx + 1,
4551                 aarch64_get_operand_desc (opd_code), str);
4552         }
4553       break;
4554
4555     case AARCH64_OPDE_INVALID_VARIANT:
4556       as_bad (_("operand mismatch -- `%s'"), str);
4557       if (verbose_error_p)
4558         {
4559           /* We will try to correct the erroneous instruction and also provide
4560              more information e.g. all other valid variants.
4561
4562              The string representation of the corrected instruction and other
4563              valid variants are generated by
4564
4565              1) obtaining the intermediate representation of the erroneous
4566              instruction;
4567              2) manipulating the IR, e.g. replacing the operand qualifier;
4568              3) printing out the instruction by calling the printer functions
4569              shared with the disassembler.
4570
4571              The limitation of this method is that the exact input assembly
4572              line cannot be accurately reproduced in some cases, for example an
4573              optional operand present in the actual assembly line will be
4574              omitted in the output; likewise for the optional syntax rules,
4575              e.g. the # before the immediate.  Another limitation is that the
4576              assembly symbols and relocation operations in the assembly line
4577              currently cannot be printed out in the error report.  Last but not
4578              least, when there is other error(s) co-exist with this error, the
4579              'corrected' instruction may be still incorrect, e.g.  given
4580                'ldnp h0,h1,[x0,#6]!'
4581              this diagnosis will provide the version:
4582                'ldnp s0,s1,[x0,#6]!'
4583              which is still not right.  */
4584           size_t len = strlen (get_mnemonic_name (str));
4585           int i, qlf_idx;
4586           bfd_boolean result;
4587           char buf[2048];
4588           aarch64_inst *inst_base = &inst.base;
4589           const aarch64_opnd_qualifier_seq_t *qualifiers_list;
4590
4591           /* Init inst.  */
4592           reset_aarch64_instruction (&inst);
4593           inst_base->opcode = opcode;
4594
4595           /* Reset the error report so that there is no side effect on the
4596              following operand parsing.  */
4597           init_operand_error_report ();
4598
4599           /* Fill inst.  */
4600           result = parse_operands (str + len, opcode)
4601             && programmer_friendly_fixup (&inst);
4602           gas_assert (result);
4603           result = aarch64_opcode_encode (opcode, inst_base, &inst_base->value,
4604                                           NULL, NULL);
4605           gas_assert (!result);
4606
4607           /* Find the most matched qualifier sequence.  */
4608           qlf_idx = find_best_match (inst_base, opcode->qualifiers_list);
4609           gas_assert (qlf_idx > -1);
4610
4611           /* Assign the qualifiers.  */
4612           assign_qualifier_sequence (inst_base,
4613                                      opcode->qualifiers_list[qlf_idx]);
4614
4615           /* Print the hint.  */
4616           output_info (_("   did you mean this?"));
4617           snprintf (buf, sizeof (buf), "\t%s", get_mnemonic_name (str));
4618           print_operands (buf, opcode, inst_base->operands);
4619           output_info (_("   %s"), buf);
4620
4621           /* Print out other variant(s) if there is any.  */
4622           if (qlf_idx != 0 ||
4623               !empty_qualifier_sequence_p (opcode->qualifiers_list[1]))
4624             output_info (_("   other valid variant(s):"));
4625
4626           /* For each pattern.  */
4627           qualifiers_list = opcode->qualifiers_list;
4628           for (i = 0; i < AARCH64_MAX_QLF_SEQ_NUM; ++i, ++qualifiers_list)
4629             {
4630               /* Most opcodes has much fewer patterns in the list.
4631                  First NIL qualifier indicates the end in the list.   */
4632               if (empty_qualifier_sequence_p (*qualifiers_list))
4633                 break;
4634
4635               if (i != qlf_idx)
4636                 {
4637                   /* Mnemonics name.  */
4638                   snprintf (buf, sizeof (buf), "\t%s", get_mnemonic_name (str));
4639
4640                   /* Assign the qualifiers.  */
4641                   assign_qualifier_sequence (inst_base, *qualifiers_list);
4642
4643                   /* Print instruction.  */
4644                   print_operands (buf, opcode, inst_base->operands);
4645
4646                   output_info (_("   %s"), buf);
4647                 }
4648             }
4649         }
4650       break;
4651
4652     case AARCH64_OPDE_UNTIED_OPERAND:
4653       as_bad (_("operand %d must be the same register as operand 1 -- `%s'"),
4654               detail->index + 1, str);
4655       break;
4656
4657     case AARCH64_OPDE_OUT_OF_RANGE:
4658       if (detail->data[0] != detail->data[1])
4659         as_bad (_("%s out of range %d to %d at operand %d -- `%s'"),
4660                 detail->error ? detail->error : _("immediate value"),
4661                 detail->data[0], detail->data[1], idx + 1, str);
4662       else
4663         as_bad (_("%s must be %d at operand %d -- `%s'"),
4664                 detail->error ? detail->error : _("immediate value"),
4665                 detail->data[0], idx + 1, str);
4666       break;
4667
4668     case AARCH64_OPDE_REG_LIST:
4669       if (detail->data[0] == 1)
4670         as_bad (_("invalid number of registers in the list; "
4671                   "only 1 register is expected at operand %d -- `%s'"),
4672                 idx + 1, str);
4673       else
4674         as_bad (_("invalid number of registers in the list; "
4675                   "%d registers are expected at operand %d -- `%s'"),
4676               detail->data[0], idx + 1, str);
4677       break;
4678
4679     case AARCH64_OPDE_UNALIGNED:
4680       as_bad (_("immediate value must be a multiple of "
4681                 "%d at operand %d -- `%s'"),
4682               detail->data[0], idx + 1, str);
4683       break;
4684
4685     default:
4686       gas_assert (0);
4687       break;
4688     }
4689 }
4690
4691 /* Process and output the error message about the operand mismatching.
4692
4693    When this function is called, the operand error information had
4694    been collected for an assembly line and there will be multiple
4695    errors in the case of multiple instruction templates; output the
4696    error message that most closely describes the problem.  */
4697
4698 static void
4699 output_operand_error_report (char *str)
4700 {
4701   int largest_error_pos;
4702   const char *msg = NULL;
4703   enum aarch64_operand_error_kind kind;
4704   operand_error_record *curr;
4705   operand_error_record *head = operand_error_report.head;
4706   operand_error_record *record = NULL;
4707
4708   /* No error to report.  */
4709   if (head == NULL)
4710     return;
4711
4712   gas_assert (head != NULL && operand_error_report.tail != NULL);
4713
4714   /* Only one error.  */
4715   if (head == operand_error_report.tail)
4716     {
4717       DEBUG_TRACE ("single opcode entry with error kind: %s",
4718                    operand_mismatch_kind_names[head->detail.kind]);
4719       output_operand_error_record (head, str);
4720       return;
4721     }
4722
4723   /* Find the error kind of the highest severity.  */
4724   DEBUG_TRACE ("multiple opcode entries with error kind");
4725   kind = AARCH64_OPDE_NIL;
4726   for (curr = head; curr != NULL; curr = curr->next)
4727     {
4728       gas_assert (curr->detail.kind != AARCH64_OPDE_NIL);
4729       DEBUG_TRACE ("\t%s", operand_mismatch_kind_names[curr->detail.kind]);
4730       if (operand_error_higher_severity_p (curr->detail.kind, kind))
4731         kind = curr->detail.kind;
4732     }
4733   gas_assert (kind != AARCH64_OPDE_NIL);
4734
4735   /* Pick up one of errors of KIND to report.  */
4736   largest_error_pos = -2; /* Index can be -1 which means unknown index.  */
4737   for (curr = head; curr != NULL; curr = curr->next)
4738     {
4739       if (curr->detail.kind != kind)
4740         continue;
4741       /* If there are multiple errors, pick up the one with the highest
4742          mismatching operand index.  In the case of multiple errors with
4743          the equally highest operand index, pick up the first one or the
4744          first one with non-NULL error message.  */
4745       if (curr->detail.index > largest_error_pos
4746           || (curr->detail.index == largest_error_pos && msg == NULL
4747               && curr->detail.error != NULL))
4748         {
4749           largest_error_pos = curr->detail.index;
4750           record = curr;
4751           msg = record->detail.error;
4752         }
4753     }
4754
4755   gas_assert (largest_error_pos != -2 && record != NULL);
4756   DEBUG_TRACE ("Pick up error kind %s to report",
4757                operand_mismatch_kind_names[record->detail.kind]);
4758
4759   /* Output.  */
4760   output_operand_error_record (record, str);
4761 }
4762 \f
4763 /* Write an AARCH64 instruction to buf - always little-endian.  */
4764 static void
4765 put_aarch64_insn (char *buf, uint32_t insn)
4766 {
4767   unsigned char *where = (unsigned char *) buf;
4768   where[0] = insn;
4769   where[1] = insn >> 8;
4770   where[2] = insn >> 16;
4771   where[3] = insn >> 24;
4772 }
4773
4774 static uint32_t
4775 get_aarch64_insn (char *buf)
4776 {
4777   unsigned char *where = (unsigned char *) buf;
4778   uint32_t result;
4779   result = (where[0] | (where[1] << 8) | (where[2] << 16) | (where[3] << 24));
4780   return result;
4781 }
4782
4783 static void
4784 output_inst (struct aarch64_inst *new_inst)
4785 {
4786   char *to = NULL;
4787
4788   to = frag_more (INSN_SIZE);
4789
4790   frag_now->tc_frag_data.recorded = 1;
4791
4792   put_aarch64_insn (to, inst.base.value);
4793
4794   if (inst.reloc.type != BFD_RELOC_UNUSED)
4795     {
4796       fixS *fixp = fix_new_aarch64 (frag_now, to - frag_now->fr_literal,
4797                                     INSN_SIZE, &inst.reloc.exp,
4798                                     inst.reloc.pc_rel,
4799                                     inst.reloc.type);
4800       DEBUG_TRACE ("Prepared relocation fix up");
4801       /* Don't check the addend value against the instruction size,
4802          that's the job of our code in md_apply_fix(). */
4803       fixp->fx_no_overflow = 1;
4804       if (new_inst != NULL)
4805         fixp->tc_fix_data.inst = new_inst;
4806       if (aarch64_gas_internal_fixup_p ())
4807         {
4808           gas_assert (inst.reloc.opnd != AARCH64_OPND_NIL);
4809           fixp->tc_fix_data.opnd = inst.reloc.opnd;
4810           fixp->fx_addnumber = inst.reloc.flags;
4811         }
4812     }
4813
4814   dwarf2_emit_insn (INSN_SIZE);
4815 }
4816
4817 /* Link together opcodes of the same name.  */
4818
4819 struct templates
4820 {
4821   aarch64_opcode *opcode;
4822   struct templates *next;
4823 };
4824
4825 typedef struct templates templates;
4826
4827 static templates *
4828 lookup_mnemonic (const char *start, int len)
4829 {
4830   templates *templ = NULL;
4831
4832   templ = hash_find_n (aarch64_ops_hsh, start, len);
4833   return templ;
4834 }
4835
4836 /* Subroutine of md_assemble, responsible for looking up the primary
4837    opcode from the mnemonic the user wrote.  STR points to the
4838    beginning of the mnemonic. */
4839
4840 static templates *
4841 opcode_lookup (char **str)
4842 {
4843   char *end, *base, *dot;
4844   const aarch64_cond *cond;
4845   char condname[16];
4846   int len;
4847
4848   /* Scan up to the end of the mnemonic, which must end in white space,
4849      '.', or end of string.  */
4850   dot = 0;
4851   for (base = end = *str; is_part_of_name(*end); end++)
4852     if (*end == '.' && !dot)
4853       dot = end;
4854
4855   if (end == base || dot == base)
4856     return 0;
4857
4858   inst.cond = COND_ALWAYS;
4859
4860   /* Handle a possible condition.  */
4861   if (dot)
4862     {
4863       cond = hash_find_n (aarch64_cond_hsh, dot + 1, end - dot - 1);
4864       if (cond)
4865         {
4866           inst.cond = cond->value;
4867           *str = end;
4868         }
4869       else
4870         {
4871           *str = dot;
4872           return 0;
4873         }
4874       len = dot - base;
4875     }
4876   else
4877     {
4878       *str = end;
4879       len = end - base;
4880     }
4881
4882   if (inst.cond == COND_ALWAYS)
4883     {
4884       /* Look for unaffixed mnemonic.  */
4885       return lookup_mnemonic (base, len);
4886     }
4887   else if (len <= 13)
4888     {
4889       /* append ".c" to mnemonic if conditional */
4890       memcpy (condname, base, len);
4891       memcpy (condname + len, ".c", 2);
4892       base = condname;
4893       len += 2;
4894       return lookup_mnemonic (base, len);
4895     }
4896
4897   return NULL;
4898 }
4899
4900 /* Internal helper routine converting a vector_type_el structure *VECTYPE
4901    to a corresponding operand qualifier.  */
4902
4903 static inline aarch64_opnd_qualifier_t
4904 vectype_to_qualifier (const struct vector_type_el *vectype)
4905 {
4906   /* Element size in bytes indexed by vector_el_type.  */
4907   const unsigned char ele_size[5]
4908     = {1, 2, 4, 8, 16};
4909   const unsigned int ele_base [5] =
4910     {
4911       AARCH64_OPND_QLF_V_8B,
4912       AARCH64_OPND_QLF_V_2H,
4913       AARCH64_OPND_QLF_V_2S,
4914       AARCH64_OPND_QLF_V_1D,
4915       AARCH64_OPND_QLF_V_1Q
4916   };
4917
4918   if (!vectype->defined || vectype->type == NT_invtype)
4919     goto vectype_conversion_fail;
4920
4921   if (vectype->type == NT_zero)
4922     return AARCH64_OPND_QLF_P_Z;
4923   if (vectype->type == NT_merge)
4924     return AARCH64_OPND_QLF_P_M;
4925
4926   gas_assert (vectype->type >= NT_b && vectype->type <= NT_q);
4927
4928   if (vectype->defined & (NTA_HASINDEX | NTA_HASVARWIDTH))
4929     /* Vector element register.  */
4930     return AARCH64_OPND_QLF_S_B + vectype->type;
4931   else
4932     {
4933       /* Vector register.  */
4934       int reg_size = ele_size[vectype->type] * vectype->width;
4935       unsigned offset;
4936       unsigned shift;
4937       if (reg_size != 16 && reg_size != 8 && reg_size != 4)
4938         goto vectype_conversion_fail;
4939
4940       /* The conversion is by calculating the offset from the base operand
4941          qualifier for the vector type.  The operand qualifiers are regular
4942          enough that the offset can established by shifting the vector width by
4943          a vector-type dependent amount.  */
4944       shift = 0;
4945       if (vectype->type == NT_b)
4946         shift = 4;
4947       else if (vectype->type == NT_h || vectype->type == NT_s)
4948         shift = 2;
4949       else if (vectype->type >= NT_d)
4950         shift = 1;
4951       else
4952         gas_assert (0);
4953
4954       offset = ele_base [vectype->type] + (vectype->width >> shift);
4955       gas_assert (AARCH64_OPND_QLF_V_8B <= offset
4956                   && offset <= AARCH64_OPND_QLF_V_1Q);
4957       return offset;
4958     }
4959
4960 vectype_conversion_fail:
4961   first_error (_("bad vector arrangement type"));
4962   return AARCH64_OPND_QLF_NIL;
4963 }
4964
4965 /* Process an optional operand that is found omitted from the assembly line.
4966    Fill *OPERAND for such an operand of type TYPE.  OPCODE points to the
4967    instruction's opcode entry while IDX is the index of this omitted operand.
4968    */
4969
4970 static void
4971 process_omitted_operand (enum aarch64_opnd type, const aarch64_opcode *opcode,
4972                          int idx, aarch64_opnd_info *operand)
4973 {
4974   aarch64_insn default_value = get_optional_operand_default_value (opcode);
4975   gas_assert (optional_operand_p (opcode, idx));
4976   gas_assert (!operand->present);
4977
4978   switch (type)
4979     {
4980     case AARCH64_OPND_Rd:
4981     case AARCH64_OPND_Rn:
4982     case AARCH64_OPND_Rm:
4983     case AARCH64_OPND_Rt:
4984     case AARCH64_OPND_Rt2:
4985     case AARCH64_OPND_Rs:
4986     case AARCH64_OPND_Ra:
4987     case AARCH64_OPND_Rt_SYS:
4988     case AARCH64_OPND_Rd_SP:
4989     case AARCH64_OPND_Rn_SP:
4990     case AARCH64_OPND_Rm_SP:
4991     case AARCH64_OPND_Fd:
4992     case AARCH64_OPND_Fn:
4993     case AARCH64_OPND_Fm:
4994     case AARCH64_OPND_Fa:
4995     case AARCH64_OPND_Ft:
4996     case AARCH64_OPND_Ft2:
4997     case AARCH64_OPND_Sd:
4998     case AARCH64_OPND_Sn:
4999     case AARCH64_OPND_Sm:
5000     case AARCH64_OPND_Vd:
5001     case AARCH64_OPND_Vn:
5002     case AARCH64_OPND_Vm:
5003     case AARCH64_OPND_VdD1:
5004     case AARCH64_OPND_VnD1:
5005       operand->reg.regno = default_value;
5006       break;
5007
5008     case AARCH64_OPND_Ed:
5009     case AARCH64_OPND_En:
5010     case AARCH64_OPND_Em:
5011       operand->reglane.regno = default_value;
5012       break;
5013
5014     case AARCH64_OPND_IDX:
5015     case AARCH64_OPND_BIT_NUM:
5016     case AARCH64_OPND_IMMR:
5017     case AARCH64_OPND_IMMS:
5018     case AARCH64_OPND_SHLL_IMM:
5019     case AARCH64_OPND_IMM_VLSL:
5020     case AARCH64_OPND_IMM_VLSR:
5021     case AARCH64_OPND_CCMP_IMM:
5022     case AARCH64_OPND_FBITS:
5023     case AARCH64_OPND_UIMM4:
5024     case AARCH64_OPND_UIMM3_OP1:
5025     case AARCH64_OPND_UIMM3_OP2:
5026     case AARCH64_OPND_IMM:
5027     case AARCH64_OPND_WIDTH:
5028     case AARCH64_OPND_UIMM7:
5029     case AARCH64_OPND_NZCV:
5030     case AARCH64_OPND_SVE_PATTERN:
5031     case AARCH64_OPND_SVE_PRFOP:
5032       operand->imm.value = default_value;
5033       break;
5034
5035     case AARCH64_OPND_SVE_PATTERN_SCALED:
5036       operand->imm.value = default_value;
5037       operand->shifter.kind = AARCH64_MOD_MUL;
5038       operand->shifter.amount = 1;
5039       break;
5040
5041     case AARCH64_OPND_EXCEPTION:
5042       inst.reloc.type = BFD_RELOC_UNUSED;
5043       break;
5044
5045     case AARCH64_OPND_BARRIER_ISB:
5046       operand->barrier = aarch64_barrier_options + default_value;
5047
5048     default:
5049       break;
5050     }
5051 }
5052
5053 /* Process the relocation type for move wide instructions.
5054    Return TRUE on success; otherwise return FALSE.  */
5055
5056 static bfd_boolean
5057 process_movw_reloc_info (void)
5058 {
5059   int is32;
5060   unsigned shift;
5061
5062   is32 = inst.base.operands[0].qualifier == AARCH64_OPND_QLF_W ? 1 : 0;
5063
5064   if (inst.base.opcode->op == OP_MOVK)
5065     switch (inst.reloc.type)
5066       {
5067       case BFD_RELOC_AARCH64_MOVW_G0_S:
5068       case BFD_RELOC_AARCH64_MOVW_G1_S:
5069       case BFD_RELOC_AARCH64_MOVW_G2_S:
5070       case BFD_RELOC_AARCH64_TLSGD_MOVW_G1:
5071       case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0:
5072       case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1:
5073       case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G2:
5074         set_syntax_error
5075           (_("the specified relocation type is not allowed for MOVK"));
5076         return FALSE;
5077       default:
5078         break;
5079       }
5080
5081   switch (inst.reloc.type)
5082     {
5083     case BFD_RELOC_AARCH64_MOVW_G0:
5084     case BFD_RELOC_AARCH64_MOVW_G0_NC:
5085     case BFD_RELOC_AARCH64_MOVW_G0_S:
5086     case BFD_RELOC_AARCH64_MOVW_GOTOFF_G0_NC:
5087     case BFD_RELOC_AARCH64_TLSDESC_OFF_G0_NC:
5088     case BFD_RELOC_AARCH64_TLSGD_MOVW_G0_NC:
5089     case BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC:
5090     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0:
5091     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0_NC:
5092     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0:
5093     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0_NC:
5094       shift = 0;
5095       break;
5096     case BFD_RELOC_AARCH64_MOVW_G1:
5097     case BFD_RELOC_AARCH64_MOVW_G1_NC:
5098     case BFD_RELOC_AARCH64_MOVW_G1_S:
5099     case BFD_RELOC_AARCH64_MOVW_GOTOFF_G1:
5100     case BFD_RELOC_AARCH64_TLSDESC_OFF_G1:
5101     case BFD_RELOC_AARCH64_TLSGD_MOVW_G1:
5102     case BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G1:
5103     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1:
5104     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1_NC:
5105     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1:
5106     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1_NC:
5107       shift = 16;
5108       break;
5109     case BFD_RELOC_AARCH64_MOVW_G2:
5110     case BFD_RELOC_AARCH64_MOVW_G2_NC:
5111     case BFD_RELOC_AARCH64_MOVW_G2_S:
5112     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G2:
5113     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G2:
5114       if (is32)
5115         {
5116           set_fatal_syntax_error
5117             (_("the specified relocation type is not allowed for 32-bit "
5118                "register"));
5119           return FALSE;
5120         }
5121       shift = 32;
5122       break;
5123     case BFD_RELOC_AARCH64_MOVW_G3:
5124       if (is32)
5125         {
5126           set_fatal_syntax_error
5127             (_("the specified relocation type is not allowed for 32-bit "
5128                "register"));
5129           return FALSE;
5130         }
5131       shift = 48;
5132       break;
5133     default:
5134       /* More cases should be added when more MOVW-related relocation types
5135          are supported in GAS.  */
5136       gas_assert (aarch64_gas_internal_fixup_p ());
5137       /* The shift amount should have already been set by the parser.  */
5138       return TRUE;
5139     }
5140   inst.base.operands[1].shifter.amount = shift;
5141   return TRUE;
5142 }
5143
5144 /* A primitive log calculator.  */
5145
5146 static inline unsigned int
5147 get_logsz (unsigned int size)
5148 {
5149   const unsigned char ls[16] =
5150     {0, 1, -1, 2, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1, -1, 4};
5151   if (size > 16)
5152     {
5153       gas_assert (0);
5154       return -1;
5155     }
5156   gas_assert (ls[size - 1] != (unsigned char)-1);
5157   return ls[size - 1];
5158 }
5159
5160 /* Determine and return the real reloc type code for an instruction
5161    with the pseudo reloc type code BFD_RELOC_AARCH64_LDST_LO12.  */
5162
5163 static inline bfd_reloc_code_real_type
5164 ldst_lo12_determine_real_reloc_type (void)
5165 {
5166   unsigned logsz;
5167   enum aarch64_opnd_qualifier opd0_qlf = inst.base.operands[0].qualifier;
5168   enum aarch64_opnd_qualifier opd1_qlf = inst.base.operands[1].qualifier;
5169
5170   const bfd_reloc_code_real_type reloc_ldst_lo12[3][5] = {
5171     {
5172       BFD_RELOC_AARCH64_LDST8_LO12,
5173       BFD_RELOC_AARCH64_LDST16_LO12,
5174       BFD_RELOC_AARCH64_LDST32_LO12,
5175       BFD_RELOC_AARCH64_LDST64_LO12,
5176       BFD_RELOC_AARCH64_LDST128_LO12
5177     },
5178     {
5179       BFD_RELOC_AARCH64_TLSLD_LDST8_DTPREL_LO12,
5180       BFD_RELOC_AARCH64_TLSLD_LDST16_DTPREL_LO12,
5181       BFD_RELOC_AARCH64_TLSLD_LDST32_DTPREL_LO12,
5182       BFD_RELOC_AARCH64_TLSLD_LDST64_DTPREL_LO12,
5183       BFD_RELOC_AARCH64_NONE
5184     },
5185     {
5186       BFD_RELOC_AARCH64_TLSLD_LDST8_DTPREL_LO12_NC,
5187       BFD_RELOC_AARCH64_TLSLD_LDST16_DTPREL_LO12_NC,
5188       BFD_RELOC_AARCH64_TLSLD_LDST32_DTPREL_LO12_NC,
5189       BFD_RELOC_AARCH64_TLSLD_LDST64_DTPREL_LO12_NC,
5190       BFD_RELOC_AARCH64_NONE
5191     }
5192   };
5193
5194   gas_assert (inst.reloc.type == BFD_RELOC_AARCH64_LDST_LO12
5195               || inst.reloc.type == BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12
5196               || (inst.reloc.type
5197                   == BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12_NC));
5198   gas_assert (inst.base.opcode->operands[1] == AARCH64_OPND_ADDR_UIMM12);
5199
5200   if (opd1_qlf == AARCH64_OPND_QLF_NIL)
5201     opd1_qlf =
5202       aarch64_get_expected_qualifier (inst.base.opcode->qualifiers_list,
5203                                       1, opd0_qlf, 0);
5204   gas_assert (opd1_qlf != AARCH64_OPND_QLF_NIL);
5205
5206   logsz = get_logsz (aarch64_get_qualifier_esize (opd1_qlf));
5207   if (inst.reloc.type == BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12
5208       || inst.reloc.type == BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12_NC)
5209     gas_assert (logsz <= 3);
5210   else
5211     gas_assert (logsz <= 4);
5212
5213   /* In reloc.c, these pseudo relocation types should be defined in similar
5214      order as above reloc_ldst_lo12 array. Because the array index calculation
5215      below relies on this.  */
5216   return reloc_ldst_lo12[inst.reloc.type - BFD_RELOC_AARCH64_LDST_LO12][logsz];
5217 }
5218
5219 /* Check whether a register list REGINFO is valid.  The registers must be
5220    numbered in increasing order (modulo 32), in increments of one or two.
5221
5222    If ACCEPT_ALTERNATE is non-zero, the register numbers should be in
5223    increments of two.
5224
5225    Return FALSE if such a register list is invalid, otherwise return TRUE.  */
5226
5227 static bfd_boolean
5228 reg_list_valid_p (uint32_t reginfo, int accept_alternate)
5229 {
5230   uint32_t i, nb_regs, prev_regno, incr;
5231
5232   nb_regs = 1 + (reginfo & 0x3);
5233   reginfo >>= 2;
5234   prev_regno = reginfo & 0x1f;
5235   incr = accept_alternate ? 2 : 1;
5236
5237   for (i = 1; i < nb_regs; ++i)
5238     {
5239       uint32_t curr_regno;
5240       reginfo >>= 5;
5241       curr_regno = reginfo & 0x1f;
5242       if (curr_regno != ((prev_regno + incr) & 0x1f))
5243         return FALSE;
5244       prev_regno = curr_regno;
5245     }
5246
5247   return TRUE;
5248 }
5249
5250 /* Generic instruction operand parser.  This does no encoding and no
5251    semantic validation; it merely squirrels values away in the inst
5252    structure.  Returns TRUE or FALSE depending on whether the
5253    specified grammar matched.  */
5254
5255 static bfd_boolean
5256 parse_operands (char *str, const aarch64_opcode *opcode)
5257 {
5258   int i;
5259   char *backtrack_pos = 0;
5260   const enum aarch64_opnd *operands = opcode->operands;
5261   aarch64_reg_type imm_reg_type;
5262
5263   clear_error ();
5264   skip_whitespace (str);
5265
5266   if (AARCH64_CPU_HAS_FEATURE (AARCH64_FEATURE_SVE, *opcode->avariant))
5267     imm_reg_type = REG_TYPE_R_Z_BHSDQ_VZP;
5268   else
5269     imm_reg_type = REG_TYPE_R_Z_BHSDQ_V;
5270
5271   for (i = 0; operands[i] != AARCH64_OPND_NIL; i++)
5272     {
5273       int64_t val;
5274       const reg_entry *reg;
5275       int comma_skipped_p = 0;
5276       aarch64_reg_type rtype;
5277       struct vector_type_el vectype;
5278       aarch64_opnd_qualifier_t qualifier, base_qualifier, offset_qualifier;
5279       aarch64_opnd_info *info = &inst.base.operands[i];
5280       aarch64_reg_type reg_type;
5281
5282       DEBUG_TRACE ("parse operand %d", i);
5283
5284       /* Assign the operand code.  */
5285       info->type = operands[i];
5286
5287       if (optional_operand_p (opcode, i))
5288         {
5289           /* Remember where we are in case we need to backtrack.  */
5290           gas_assert (!backtrack_pos);
5291           backtrack_pos = str;
5292         }
5293
5294       /* Expect comma between operands; the backtrack mechanism will take
5295          care of cases of omitted optional operand.  */
5296       if (i > 0 && ! skip_past_char (&str, ','))
5297         {
5298           set_syntax_error (_("comma expected between operands"));
5299           goto failure;
5300         }
5301       else
5302         comma_skipped_p = 1;
5303
5304       switch (operands[i])
5305         {
5306         case AARCH64_OPND_Rd:
5307         case AARCH64_OPND_Rn:
5308         case AARCH64_OPND_Rm:
5309         case AARCH64_OPND_Rt:
5310         case AARCH64_OPND_Rt2:
5311         case AARCH64_OPND_Rs:
5312         case AARCH64_OPND_Ra:
5313         case AARCH64_OPND_Rt_SYS:
5314         case AARCH64_OPND_PAIRREG:
5315         case AARCH64_OPND_SVE_Rm:
5316           po_int_reg_or_fail (REG_TYPE_R_Z);
5317           break;
5318
5319         case AARCH64_OPND_Rd_SP:
5320         case AARCH64_OPND_Rn_SP:
5321         case AARCH64_OPND_SVE_Rn_SP:
5322         case AARCH64_OPND_Rm_SP:
5323           po_int_reg_or_fail (REG_TYPE_R_SP);
5324           break;
5325
5326         case AARCH64_OPND_Rm_EXT:
5327         case AARCH64_OPND_Rm_SFT:
5328           po_misc_or_fail (parse_shifter_operand
5329                            (&str, info, (operands[i] == AARCH64_OPND_Rm_EXT
5330                                          ? SHIFTED_ARITH_IMM
5331                                          : SHIFTED_LOGIC_IMM)));
5332           if (!info->shifter.operator_present)
5333             {
5334               /* Default to LSL if not present.  Libopcodes prefers shifter
5335                  kind to be explicit.  */
5336               gas_assert (info->shifter.kind == AARCH64_MOD_NONE);
5337               info->shifter.kind = AARCH64_MOD_LSL;
5338               /* For Rm_EXT, libopcodes will carry out further check on whether
5339                  or not stack pointer is used in the instruction (Recall that
5340                  "the extend operator is not optional unless at least one of
5341                  "Rd" or "Rn" is '11111' (i.e. WSP)").  */
5342             }
5343           break;
5344
5345         case AARCH64_OPND_Fd:
5346         case AARCH64_OPND_Fn:
5347         case AARCH64_OPND_Fm:
5348         case AARCH64_OPND_Fa:
5349         case AARCH64_OPND_Ft:
5350         case AARCH64_OPND_Ft2:
5351         case AARCH64_OPND_Sd:
5352         case AARCH64_OPND_Sn:
5353         case AARCH64_OPND_Sm:
5354         case AARCH64_OPND_SVE_VZn:
5355         case AARCH64_OPND_SVE_Vd:
5356         case AARCH64_OPND_SVE_Vm:
5357         case AARCH64_OPND_SVE_Vn:
5358           val = aarch64_reg_parse (&str, REG_TYPE_BHSDQ, &rtype, NULL);
5359           if (val == PARSE_FAIL)
5360             {
5361               first_error (_(get_reg_expected_msg (REG_TYPE_BHSDQ)));
5362               goto failure;
5363             }
5364           gas_assert (rtype >= REG_TYPE_FP_B && rtype <= REG_TYPE_FP_Q);
5365
5366           info->reg.regno = val;
5367           info->qualifier = AARCH64_OPND_QLF_S_B + (rtype - REG_TYPE_FP_B);
5368           break;
5369
5370         case AARCH64_OPND_SVE_Pd:
5371         case AARCH64_OPND_SVE_Pg3:
5372         case AARCH64_OPND_SVE_Pg4_5:
5373         case AARCH64_OPND_SVE_Pg4_10:
5374         case AARCH64_OPND_SVE_Pg4_16:
5375         case AARCH64_OPND_SVE_Pm:
5376         case AARCH64_OPND_SVE_Pn:
5377         case AARCH64_OPND_SVE_Pt:
5378           reg_type = REG_TYPE_PN;
5379           goto vector_reg;
5380
5381         case AARCH64_OPND_SVE_Za_5:
5382         case AARCH64_OPND_SVE_Za_16:
5383         case AARCH64_OPND_SVE_Zd:
5384         case AARCH64_OPND_SVE_Zm_5:
5385         case AARCH64_OPND_SVE_Zm_16:
5386         case AARCH64_OPND_SVE_Zn:
5387         case AARCH64_OPND_SVE_Zt:
5388           reg_type = REG_TYPE_ZN;
5389           goto vector_reg;
5390
5391         case AARCH64_OPND_Vd:
5392         case AARCH64_OPND_Vn:
5393         case AARCH64_OPND_Vm:
5394           reg_type = REG_TYPE_VN;
5395         vector_reg:
5396           val = aarch64_reg_parse (&str, reg_type, NULL, &vectype);
5397           if (val == PARSE_FAIL)
5398             {
5399               first_error (_(get_reg_expected_msg (reg_type)));
5400               goto failure;
5401             }
5402           if (vectype.defined & NTA_HASINDEX)
5403             goto failure;
5404
5405           info->reg.regno = val;
5406           if ((reg_type == REG_TYPE_PN || reg_type == REG_TYPE_ZN)
5407               && vectype.type == NT_invtype)
5408             /* Unqualified Pn and Zn registers are allowed in certain
5409                contexts.  Rely on F_STRICT qualifier checking to catch
5410                invalid uses.  */
5411             info->qualifier = AARCH64_OPND_QLF_NIL;
5412           else
5413             {
5414               info->qualifier = vectype_to_qualifier (&vectype);
5415               if (info->qualifier == AARCH64_OPND_QLF_NIL)
5416                 goto failure;
5417             }
5418           break;
5419
5420         case AARCH64_OPND_VdD1:
5421         case AARCH64_OPND_VnD1:
5422           val = aarch64_reg_parse (&str, REG_TYPE_VN, NULL, &vectype);
5423           if (val == PARSE_FAIL)
5424             {
5425               set_first_syntax_error (_(get_reg_expected_msg (REG_TYPE_VN)));
5426               goto failure;
5427             }
5428           if (vectype.type != NT_d || vectype.index != 1)
5429             {
5430               set_fatal_syntax_error
5431                 (_("the top half of a 128-bit FP/SIMD register is expected"));
5432               goto failure;
5433             }
5434           info->reg.regno = val;
5435           /* N.B: VdD1 and VnD1 are treated as an fp or advsimd scalar register
5436              here; it is correct for the purpose of encoding/decoding since
5437              only the register number is explicitly encoded in the related
5438              instructions, although this appears a bit hacky.  */
5439           info->qualifier = AARCH64_OPND_QLF_S_D;
5440           break;
5441
5442         case AARCH64_OPND_SVE_Zm3_INDEX:
5443         case AARCH64_OPND_SVE_Zm3_22_INDEX:
5444         case AARCH64_OPND_SVE_Zm4_INDEX:
5445         case AARCH64_OPND_SVE_Zn_INDEX:
5446           reg_type = REG_TYPE_ZN;
5447           goto vector_reg_index;
5448
5449         case AARCH64_OPND_Ed:
5450         case AARCH64_OPND_En:
5451         case AARCH64_OPND_Em:
5452           reg_type = REG_TYPE_VN;
5453         vector_reg_index:
5454           val = aarch64_reg_parse (&str, reg_type, NULL, &vectype);
5455           if (val == PARSE_FAIL)
5456             {
5457               first_error (_(get_reg_expected_msg (reg_type)));
5458               goto failure;
5459             }
5460           if (vectype.type == NT_invtype || !(vectype.defined & NTA_HASINDEX))
5461             goto failure;
5462
5463           info->reglane.regno = val;
5464           info->reglane.index = vectype.index;
5465           info->qualifier = vectype_to_qualifier (&vectype);
5466           if (info->qualifier == AARCH64_OPND_QLF_NIL)
5467             goto failure;
5468           break;
5469
5470         case AARCH64_OPND_SVE_ZnxN:
5471         case AARCH64_OPND_SVE_ZtxN:
5472           reg_type = REG_TYPE_ZN;
5473           goto vector_reg_list;
5474
5475         case AARCH64_OPND_LVn:
5476         case AARCH64_OPND_LVt:
5477         case AARCH64_OPND_LVt_AL:
5478         case AARCH64_OPND_LEt:
5479           reg_type = REG_TYPE_VN;
5480         vector_reg_list:
5481           if (reg_type == REG_TYPE_ZN
5482               && get_opcode_dependent_value (opcode) == 1
5483               && *str != '{')
5484             {
5485               val = aarch64_reg_parse (&str, reg_type, NULL, &vectype);
5486               if (val == PARSE_FAIL)
5487                 {
5488                   first_error (_(get_reg_expected_msg (reg_type)));
5489                   goto failure;
5490                 }
5491               info->reglist.first_regno = val;
5492               info->reglist.num_regs = 1;
5493             }
5494           else
5495             {
5496               val = parse_vector_reg_list (&str, reg_type, &vectype);
5497               if (val == PARSE_FAIL)
5498                 goto failure;
5499               if (! reg_list_valid_p (val, /* accept_alternate */ 0))
5500                 {
5501                   set_fatal_syntax_error (_("invalid register list"));
5502                   goto failure;
5503                 }
5504               info->reglist.first_regno = (val >> 2) & 0x1f;
5505               info->reglist.num_regs = (val & 0x3) + 1;
5506             }
5507           if (operands[i] == AARCH64_OPND_LEt)
5508             {
5509               if (!(vectype.defined & NTA_HASINDEX))
5510                 goto failure;
5511               info->reglist.has_index = 1;
5512               info->reglist.index = vectype.index;
5513             }
5514           else
5515             {
5516               if (vectype.defined & NTA_HASINDEX)
5517                 goto failure;
5518               if (!(vectype.defined & NTA_HASTYPE))
5519                 {
5520                   if (reg_type == REG_TYPE_ZN)
5521                     set_fatal_syntax_error (_("missing type suffix"));
5522                   goto failure;
5523                 }
5524             }
5525           info->qualifier = vectype_to_qualifier (&vectype);
5526           if (info->qualifier == AARCH64_OPND_QLF_NIL)
5527             goto failure;
5528           break;
5529
5530         case AARCH64_OPND_CRn:
5531         case AARCH64_OPND_CRm:
5532             {
5533               char prefix = *(str++);
5534               if (prefix != 'c' && prefix != 'C')
5535                 goto failure;
5536
5537               po_imm_nc_or_fail ();
5538               if (val > 15)
5539                 {
5540                   set_fatal_syntax_error (_(N_ ("C0 - C15 expected")));
5541                   goto failure;
5542                 }
5543               info->qualifier = AARCH64_OPND_QLF_CR;
5544               info->imm.value = val;
5545               break;
5546             }
5547
5548         case AARCH64_OPND_SHLL_IMM:
5549         case AARCH64_OPND_IMM_VLSR:
5550           po_imm_or_fail (1, 64);
5551           info->imm.value = val;
5552           break;
5553
5554         case AARCH64_OPND_CCMP_IMM:
5555         case AARCH64_OPND_SIMM5:
5556         case AARCH64_OPND_FBITS:
5557         case AARCH64_OPND_UIMM4:
5558         case AARCH64_OPND_UIMM3_OP1:
5559         case AARCH64_OPND_UIMM3_OP2:
5560         case AARCH64_OPND_IMM_VLSL:
5561         case AARCH64_OPND_IMM:
5562         case AARCH64_OPND_WIDTH:
5563         case AARCH64_OPND_SVE_INV_LIMM:
5564         case AARCH64_OPND_SVE_LIMM:
5565         case AARCH64_OPND_SVE_LIMM_MOV:
5566         case AARCH64_OPND_SVE_SHLIMM_PRED:
5567         case AARCH64_OPND_SVE_SHLIMM_UNPRED:
5568         case AARCH64_OPND_SVE_SHRIMM_PRED:
5569         case AARCH64_OPND_SVE_SHRIMM_UNPRED:
5570         case AARCH64_OPND_SVE_SIMM5:
5571         case AARCH64_OPND_SVE_SIMM5B:
5572         case AARCH64_OPND_SVE_SIMM6:
5573         case AARCH64_OPND_SVE_SIMM8:
5574         case AARCH64_OPND_SVE_UIMM3:
5575         case AARCH64_OPND_SVE_UIMM7:
5576         case AARCH64_OPND_SVE_UIMM8:
5577         case AARCH64_OPND_SVE_UIMM8_53:
5578         case AARCH64_OPND_IMM_ROT1:
5579         case AARCH64_OPND_IMM_ROT2:
5580         case AARCH64_OPND_IMM_ROT3:
5581         case AARCH64_OPND_SVE_IMM_ROT1:
5582         case AARCH64_OPND_SVE_IMM_ROT2:
5583           po_imm_nc_or_fail ();
5584           info->imm.value = val;
5585           break;
5586
5587         case AARCH64_OPND_SVE_AIMM:
5588         case AARCH64_OPND_SVE_ASIMM:
5589           po_imm_nc_or_fail ();
5590           info->imm.value = val;
5591           skip_whitespace (str);
5592           if (skip_past_comma (&str))
5593             po_misc_or_fail (parse_shift (&str, info, SHIFTED_LSL));
5594           else
5595             inst.base.operands[i].shifter.kind = AARCH64_MOD_LSL;
5596           break;
5597
5598         case AARCH64_OPND_SVE_PATTERN:
5599           po_enum_or_fail (aarch64_sve_pattern_array);
5600           info->imm.value = val;
5601           break;
5602
5603         case AARCH64_OPND_SVE_PATTERN_SCALED:
5604           po_enum_or_fail (aarch64_sve_pattern_array);
5605           info->imm.value = val;
5606           if (skip_past_comma (&str)
5607               && !parse_shift (&str, info, SHIFTED_MUL))
5608             goto failure;
5609           if (!info->shifter.operator_present)
5610             {
5611               gas_assert (info->shifter.kind == AARCH64_MOD_NONE);
5612               info->shifter.kind = AARCH64_MOD_MUL;
5613               info->shifter.amount = 1;
5614             }
5615           break;
5616
5617         case AARCH64_OPND_SVE_PRFOP:
5618           po_enum_or_fail (aarch64_sve_prfop_array);
5619           info->imm.value = val;
5620           break;
5621
5622         case AARCH64_OPND_UIMM7:
5623           po_imm_or_fail (0, 127);
5624           info->imm.value = val;
5625           break;
5626
5627         case AARCH64_OPND_IDX:
5628         case AARCH64_OPND_BIT_NUM:
5629         case AARCH64_OPND_IMMR:
5630         case AARCH64_OPND_IMMS:
5631           po_imm_or_fail (0, 63);
5632           info->imm.value = val;
5633           break;
5634
5635         case AARCH64_OPND_IMM0:
5636           po_imm_nc_or_fail ();
5637           if (val != 0)
5638             {
5639               set_fatal_syntax_error (_("immediate zero expected"));
5640               goto failure;
5641             }
5642           info->imm.value = 0;
5643           break;
5644
5645         case AARCH64_OPND_FPIMM0:
5646           {
5647             int qfloat;
5648             bfd_boolean res1 = FALSE, res2 = FALSE;
5649             /* N.B. -0.0 will be rejected; although -0.0 shouldn't be rejected,
5650                it is probably not worth the effort to support it.  */
5651             if (!(res1 = parse_aarch64_imm_float (&str, &qfloat, FALSE,
5652                                                   imm_reg_type))
5653                 && (error_p ()
5654                     || !(res2 = parse_constant_immediate (&str, &val,
5655                                                           imm_reg_type))))
5656               goto failure;
5657             if ((res1 && qfloat == 0) || (res2 && val == 0))
5658               {
5659                 info->imm.value = 0;
5660                 info->imm.is_fp = 1;
5661                 break;
5662               }
5663             set_fatal_syntax_error (_("immediate zero expected"));
5664             goto failure;
5665           }
5666
5667         case AARCH64_OPND_IMM_MOV:
5668           {
5669             char *saved = str;
5670             if (reg_name_p (str, REG_TYPE_R_Z_SP) ||
5671                 reg_name_p (str, REG_TYPE_VN))
5672               goto failure;
5673             str = saved;
5674             po_misc_or_fail (my_get_expression (&inst.reloc.exp, &str,
5675                                                 GE_OPT_PREFIX, 1));
5676             /* The MOV immediate alias will be fixed up by fix_mov_imm_insn
5677                later.  fix_mov_imm_insn will try to determine a machine
5678                instruction (MOVZ, MOVN or ORR) for it and will issue an error
5679                message if the immediate cannot be moved by a single
5680                instruction.  */
5681             aarch64_set_gas_internal_fixup (&inst.reloc, info, 1);
5682             inst.base.operands[i].skip = 1;
5683           }
5684           break;
5685
5686         case AARCH64_OPND_SIMD_IMM:
5687         case AARCH64_OPND_SIMD_IMM_SFT:
5688           if (! parse_big_immediate (&str, &val, imm_reg_type))
5689             goto failure;
5690           assign_imm_if_const_or_fixup_later (&inst.reloc, info,
5691                                               /* addr_off_p */ 0,
5692                                               /* need_libopcodes_p */ 1,
5693                                               /* skip_p */ 1);
5694           /* Parse shift.
5695              N.B. although AARCH64_OPND_SIMD_IMM doesn't permit any
5696              shift, we don't check it here; we leave the checking to
5697              the libopcodes (operand_general_constraint_met_p).  By
5698              doing this, we achieve better diagnostics.  */
5699           if (skip_past_comma (&str)
5700               && ! parse_shift (&str, info, SHIFTED_LSL_MSL))
5701             goto failure;
5702           if (!info->shifter.operator_present
5703               && info->type == AARCH64_OPND_SIMD_IMM_SFT)
5704             {
5705               /* Default to LSL if not present.  Libopcodes prefers shifter
5706                  kind to be explicit.  */
5707               gas_assert (info->shifter.kind == AARCH64_MOD_NONE);
5708               info->shifter.kind = AARCH64_MOD_LSL;
5709             }
5710           break;
5711
5712         case AARCH64_OPND_FPIMM:
5713         case AARCH64_OPND_SIMD_FPIMM:
5714         case AARCH64_OPND_SVE_FPIMM8:
5715           {
5716             int qfloat;
5717             bfd_boolean dp_p;
5718
5719             dp_p = double_precision_operand_p (&inst.base.operands[0]);
5720             if (!parse_aarch64_imm_float (&str, &qfloat, dp_p, imm_reg_type)
5721                 || !aarch64_imm_float_p (qfloat))
5722               {
5723                 if (!error_p ())
5724                   set_fatal_syntax_error (_("invalid floating-point"
5725                                             " constant"));
5726                 goto failure;
5727               }
5728             inst.base.operands[i].imm.value = encode_imm_float_bits (qfloat);
5729             inst.base.operands[i].imm.is_fp = 1;
5730           }
5731           break;
5732
5733         case AARCH64_OPND_SVE_I1_HALF_ONE:
5734         case AARCH64_OPND_SVE_I1_HALF_TWO:
5735         case AARCH64_OPND_SVE_I1_ZERO_ONE:
5736           {
5737             int qfloat;
5738             bfd_boolean dp_p;
5739
5740             dp_p = double_precision_operand_p (&inst.base.operands[0]);
5741             if (!parse_aarch64_imm_float (&str, &qfloat, dp_p, imm_reg_type))
5742               {
5743                 if (!error_p ())
5744                   set_fatal_syntax_error (_("invalid floating-point"
5745                                             " constant"));
5746                 goto failure;
5747               }
5748             inst.base.operands[i].imm.value = qfloat;
5749             inst.base.operands[i].imm.is_fp = 1;
5750           }
5751           break;
5752
5753         case AARCH64_OPND_LIMM:
5754           po_misc_or_fail (parse_shifter_operand (&str, info,
5755                                                   SHIFTED_LOGIC_IMM));
5756           if (info->shifter.operator_present)
5757             {
5758               set_fatal_syntax_error
5759                 (_("shift not allowed for bitmask immediate"));
5760               goto failure;
5761             }
5762           assign_imm_if_const_or_fixup_later (&inst.reloc, info,
5763                                               /* addr_off_p */ 0,
5764                                               /* need_libopcodes_p */ 1,
5765                                               /* skip_p */ 1);
5766           break;
5767
5768         case AARCH64_OPND_AIMM:
5769           if (opcode->op == OP_ADD)
5770             /* ADD may have relocation types.  */
5771             po_misc_or_fail (parse_shifter_operand_reloc (&str, info,
5772                                                           SHIFTED_ARITH_IMM));
5773           else
5774             po_misc_or_fail (parse_shifter_operand (&str, info,
5775                                                     SHIFTED_ARITH_IMM));
5776           switch (inst.reloc.type)
5777             {
5778             case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_HI12:
5779               info->shifter.amount = 12;
5780               break;
5781             case BFD_RELOC_UNUSED:
5782               aarch64_set_gas_internal_fixup (&inst.reloc, info, 0);
5783               if (info->shifter.kind != AARCH64_MOD_NONE)
5784                 inst.reloc.flags = FIXUP_F_HAS_EXPLICIT_SHIFT;
5785               inst.reloc.pc_rel = 0;
5786               break;
5787             default:
5788               break;
5789             }
5790           info->imm.value = 0;
5791           if (!info->shifter.operator_present)
5792             {
5793               /* Default to LSL if not present.  Libopcodes prefers shifter
5794                  kind to be explicit.  */
5795               gas_assert (info->shifter.kind == AARCH64_MOD_NONE);
5796               info->shifter.kind = AARCH64_MOD_LSL;
5797             }
5798           break;
5799
5800         case AARCH64_OPND_HALF:
5801             {
5802               /* #<imm16> or relocation.  */
5803               int internal_fixup_p;
5804               po_misc_or_fail (parse_half (&str, &internal_fixup_p));
5805               if (internal_fixup_p)
5806                 aarch64_set_gas_internal_fixup (&inst.reloc, info, 0);
5807               skip_whitespace (str);
5808               if (skip_past_comma (&str))
5809                 {
5810                   /* {, LSL #<shift>}  */
5811                   if (! aarch64_gas_internal_fixup_p ())
5812                     {
5813                       set_fatal_syntax_error (_("can't mix relocation modifier "
5814                                                 "with explicit shift"));
5815                       goto failure;
5816                     }
5817                   po_misc_or_fail (parse_shift (&str, info, SHIFTED_LSL));
5818                 }
5819               else
5820                 inst.base.operands[i].shifter.amount = 0;
5821               inst.base.operands[i].shifter.kind = AARCH64_MOD_LSL;
5822               inst.base.operands[i].imm.value = 0;
5823               if (! process_movw_reloc_info ())
5824                 goto failure;
5825             }
5826           break;
5827
5828         case AARCH64_OPND_EXCEPTION:
5829           po_misc_or_fail (parse_immediate_expression (&str, &inst.reloc.exp,
5830                                                        imm_reg_type));
5831           assign_imm_if_const_or_fixup_later (&inst.reloc, info,
5832                                               /* addr_off_p */ 0,
5833                                               /* need_libopcodes_p */ 0,
5834                                               /* skip_p */ 1);
5835           break;
5836
5837         case AARCH64_OPND_NZCV:
5838           {
5839             const asm_nzcv *nzcv = hash_find_n (aarch64_nzcv_hsh, str, 4);
5840             if (nzcv != NULL)
5841               {
5842                 str += 4;
5843                 info->imm.value = nzcv->value;
5844                 break;
5845               }
5846             po_imm_or_fail (0, 15);
5847             info->imm.value = val;
5848           }
5849           break;
5850
5851         case AARCH64_OPND_COND:
5852         case AARCH64_OPND_COND1:
5853           {
5854             char *start = str;
5855             do
5856               str++;
5857             while (ISALPHA (*str));
5858             info->cond = hash_find_n (aarch64_cond_hsh, start, str - start);
5859             if (info->cond == NULL)
5860               {
5861                 set_syntax_error (_("invalid condition"));
5862                 goto failure;
5863               }
5864             else if (operands[i] == AARCH64_OPND_COND1
5865                      && (info->cond->value & 0xe) == 0xe)
5866               {
5867                 /* Do not allow AL or NV.  */
5868                 set_default_error ();
5869                 goto failure;
5870               }
5871           }
5872           break;
5873
5874         case AARCH64_OPND_ADDR_ADRP:
5875           po_misc_or_fail (parse_adrp (&str));
5876           /* Clear the value as operand needs to be relocated.  */
5877           info->imm.value = 0;
5878           break;
5879
5880         case AARCH64_OPND_ADDR_PCREL14:
5881         case AARCH64_OPND_ADDR_PCREL19:
5882         case AARCH64_OPND_ADDR_PCREL21:
5883         case AARCH64_OPND_ADDR_PCREL26:
5884           po_misc_or_fail (parse_address (&str, info));
5885           if (!info->addr.pcrel)
5886             {
5887               set_syntax_error (_("invalid pc-relative address"));
5888               goto failure;
5889             }
5890           if (inst.gen_lit_pool
5891               && (opcode->iclass != loadlit || opcode->op == OP_PRFM_LIT))
5892             {
5893               /* Only permit "=value" in the literal load instructions.
5894                  The literal will be generated by programmer_friendly_fixup.  */
5895               set_syntax_error (_("invalid use of \"=immediate\""));
5896               goto failure;
5897             }
5898           if (inst.reloc.exp.X_op == O_symbol && find_reloc_table_entry (&str))
5899             {
5900               set_syntax_error (_("unrecognized relocation suffix"));
5901               goto failure;
5902             }
5903           if (inst.reloc.exp.X_op == O_constant && !inst.gen_lit_pool)
5904             {
5905               info->imm.value = inst.reloc.exp.X_add_number;
5906               inst.reloc.type = BFD_RELOC_UNUSED;
5907             }
5908           else
5909             {
5910               info->imm.value = 0;
5911               if (inst.reloc.type == BFD_RELOC_UNUSED)
5912                 switch (opcode->iclass)
5913                   {
5914                   case compbranch:
5915                   case condbranch:
5916                     /* e.g. CBZ or B.COND  */
5917                     gas_assert (operands[i] == AARCH64_OPND_ADDR_PCREL19);
5918                     inst.reloc.type = BFD_RELOC_AARCH64_BRANCH19;
5919                     break;
5920                   case testbranch:
5921                     /* e.g. TBZ  */
5922                     gas_assert (operands[i] == AARCH64_OPND_ADDR_PCREL14);
5923                     inst.reloc.type = BFD_RELOC_AARCH64_TSTBR14;
5924                     break;
5925                   case branch_imm:
5926                     /* e.g. B or BL  */
5927                     gas_assert (operands[i] == AARCH64_OPND_ADDR_PCREL26);
5928                     inst.reloc.type =
5929                       (opcode->op == OP_BL) ? BFD_RELOC_AARCH64_CALL26
5930                          : BFD_RELOC_AARCH64_JUMP26;
5931                     break;
5932                   case loadlit:
5933                     gas_assert (operands[i] == AARCH64_OPND_ADDR_PCREL19);
5934                     inst.reloc.type = BFD_RELOC_AARCH64_LD_LO19_PCREL;
5935                     break;
5936                   case pcreladdr:
5937                     gas_assert (operands[i] == AARCH64_OPND_ADDR_PCREL21);
5938                     inst.reloc.type = BFD_RELOC_AARCH64_ADR_LO21_PCREL;
5939                     break;
5940                   default:
5941                     gas_assert (0);
5942                     abort ();
5943                   }
5944               inst.reloc.pc_rel = 1;
5945             }
5946           break;
5947
5948         case AARCH64_OPND_ADDR_SIMPLE:
5949         case AARCH64_OPND_SIMD_ADDR_SIMPLE:
5950           {
5951             /* [<Xn|SP>{, #<simm>}]  */
5952             char *start = str;
5953             /* First use the normal address-parsing routines, to get
5954                the usual syntax errors.  */
5955             po_misc_or_fail (parse_address (&str, info));
5956             if (info->addr.pcrel || info->addr.offset.is_reg
5957                 || !info->addr.preind || info->addr.postind
5958                 || info->addr.writeback)
5959               {
5960                 set_syntax_error (_("invalid addressing mode"));
5961                 goto failure;
5962               }
5963
5964             /* Then retry, matching the specific syntax of these addresses.  */
5965             str = start;
5966             po_char_or_fail ('[');
5967             po_reg_or_fail (REG_TYPE_R64_SP);
5968             /* Accept optional ", #0".  */
5969             if (operands[i] == AARCH64_OPND_ADDR_SIMPLE
5970                 && skip_past_char (&str, ','))
5971               {
5972                 skip_past_char (&str, '#');
5973                 if (! skip_past_char (&str, '0'))
5974                   {
5975                     set_fatal_syntax_error
5976                       (_("the optional immediate offset can only be 0"));
5977                     goto failure;
5978                   }
5979               }
5980             po_char_or_fail (']');
5981             break;
5982           }
5983
5984         case AARCH64_OPND_ADDR_REGOFF:
5985           /* [<Xn|SP>, <R><m>{, <extend> {<amount>}}]  */
5986           po_misc_or_fail (parse_address (&str, info));
5987         regoff_addr:
5988           if (info->addr.pcrel || !info->addr.offset.is_reg
5989               || !info->addr.preind || info->addr.postind
5990               || info->addr.writeback)
5991             {
5992               set_syntax_error (_("invalid addressing mode"));
5993               goto failure;
5994             }
5995           if (!info->shifter.operator_present)
5996             {
5997               /* Default to LSL if not present.  Libopcodes prefers shifter
5998                  kind to be explicit.  */
5999               gas_assert (info->shifter.kind == AARCH64_MOD_NONE);
6000               info->shifter.kind = AARCH64_MOD_LSL;
6001             }
6002           /* Qualifier to be deduced by libopcodes.  */
6003           break;
6004
6005         case AARCH64_OPND_ADDR_SIMM7:
6006           po_misc_or_fail (parse_address (&str, info));
6007           if (info->addr.pcrel || info->addr.offset.is_reg
6008               || (!info->addr.preind && !info->addr.postind))
6009             {
6010               set_syntax_error (_("invalid addressing mode"));
6011               goto failure;
6012             }
6013           if (inst.reloc.type != BFD_RELOC_UNUSED)
6014             {
6015               set_syntax_error (_("relocation not allowed"));
6016               goto failure;
6017             }
6018           assign_imm_if_const_or_fixup_later (&inst.reloc, info,
6019                                               /* addr_off_p */ 1,
6020                                               /* need_libopcodes_p */ 1,
6021                                               /* skip_p */ 0);
6022           break;
6023
6024         case AARCH64_OPND_ADDR_SIMM9:
6025         case AARCH64_OPND_ADDR_SIMM9_2:
6026           po_misc_or_fail (parse_address (&str, info));
6027           if (info->addr.pcrel || info->addr.offset.is_reg
6028               || (!info->addr.preind && !info->addr.postind)
6029               || (operands[i] == AARCH64_OPND_ADDR_SIMM9_2
6030                   && info->addr.writeback))
6031             {
6032               set_syntax_error (_("invalid addressing mode"));
6033               goto failure;
6034             }
6035           if (inst.reloc.type != BFD_RELOC_UNUSED)
6036             {
6037               set_syntax_error (_("relocation not allowed"));
6038               goto failure;
6039             }
6040           assign_imm_if_const_or_fixup_later (&inst.reloc, info,
6041                                               /* addr_off_p */ 1,
6042                                               /* need_libopcodes_p */ 1,
6043                                               /* skip_p */ 0);
6044           break;
6045
6046         case AARCH64_OPND_ADDR_SIMM10:
6047           po_misc_or_fail (parse_address (&str, info));
6048           if (info->addr.pcrel || info->addr.offset.is_reg
6049               || !info->addr.preind || info->addr.postind)
6050             {
6051               set_syntax_error (_("invalid addressing mode"));
6052               goto failure;
6053             }
6054           if (inst.reloc.type != BFD_RELOC_UNUSED)
6055             {
6056               set_syntax_error (_("relocation not allowed"));
6057               goto failure;
6058             }
6059           assign_imm_if_const_or_fixup_later (&inst.reloc, info,
6060                                               /* addr_off_p */ 1,
6061                                               /* need_libopcodes_p */ 1,
6062                                               /* skip_p */ 0);
6063           break;
6064
6065         case AARCH64_OPND_ADDR_UIMM12:
6066           po_misc_or_fail (parse_address (&str, info));
6067           if (info->addr.pcrel || info->addr.offset.is_reg
6068               || !info->addr.preind || info->addr.writeback)
6069             {
6070               set_syntax_error (_("invalid addressing mode"));
6071               goto failure;
6072             }
6073           if (inst.reloc.type == BFD_RELOC_UNUSED)
6074             aarch64_set_gas_internal_fixup (&inst.reloc, info, 1);
6075           else if (inst.reloc.type == BFD_RELOC_AARCH64_LDST_LO12
6076                    || (inst.reloc.type
6077                        == BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12)
6078                    || (inst.reloc.type
6079                        == BFD_RELOC_AARCH64_TLSLD_LDST_DTPREL_LO12_NC))
6080             inst.reloc.type = ldst_lo12_determine_real_reloc_type ();
6081           /* Leave qualifier to be determined by libopcodes.  */
6082           break;
6083
6084         case AARCH64_OPND_SIMD_ADDR_POST:
6085           /* [<Xn|SP>], <Xm|#<amount>>  */
6086           po_misc_or_fail (parse_address (&str, info));
6087           if (!info->addr.postind || !info->addr.writeback)
6088             {
6089               set_syntax_error (_("invalid addressing mode"));
6090               goto failure;
6091             }
6092           if (!info->addr.offset.is_reg)
6093             {
6094               if (inst.reloc.exp.X_op == O_constant)
6095                 info->addr.offset.imm = inst.reloc.exp.X_add_number;
6096               else
6097                 {
6098                   set_fatal_syntax_error
6099                     (_("writeback value must be an immediate constant"));
6100                   goto failure;
6101                 }
6102             }
6103           /* No qualifier.  */
6104           break;
6105
6106         case AARCH64_OPND_SVE_ADDR_RI_S4x16:
6107         case AARCH64_OPND_SVE_ADDR_RI_S4xVL:
6108         case AARCH64_OPND_SVE_ADDR_RI_S4x2xVL:
6109         case AARCH64_OPND_SVE_ADDR_RI_S4x3xVL:
6110         case AARCH64_OPND_SVE_ADDR_RI_S4x4xVL:
6111         case AARCH64_OPND_SVE_ADDR_RI_S6xVL:
6112         case AARCH64_OPND_SVE_ADDR_RI_S9xVL:
6113         case AARCH64_OPND_SVE_ADDR_RI_U6:
6114         case AARCH64_OPND_SVE_ADDR_RI_U6x2:
6115         case AARCH64_OPND_SVE_ADDR_RI_U6x4:
6116         case AARCH64_OPND_SVE_ADDR_RI_U6x8:
6117           /* [X<n>{, #imm, MUL VL}]
6118              [X<n>{, #imm}]
6119              but recognizing SVE registers.  */
6120           po_misc_or_fail (parse_sve_address (&str, info, &base_qualifier,
6121                                               &offset_qualifier));
6122           if (base_qualifier != AARCH64_OPND_QLF_X)
6123             {
6124               set_syntax_error (_("invalid addressing mode"));
6125               goto failure;
6126             }
6127         sve_regimm:
6128           if (info->addr.pcrel || info->addr.offset.is_reg
6129               || !info->addr.preind || info->addr.writeback)
6130             {
6131               set_syntax_error (_("invalid addressing mode"));
6132               goto failure;
6133             }
6134           if (inst.reloc.type != BFD_RELOC_UNUSED
6135               || inst.reloc.exp.X_op != O_constant)
6136             {
6137               /* Make sure this has priority over
6138                  "invalid addressing mode".  */
6139               set_fatal_syntax_error (_("constant offset required"));
6140               goto failure;
6141             }
6142           info->addr.offset.imm = inst.reloc.exp.X_add_number;
6143           break;
6144
6145         case AARCH64_OPND_SVE_ADDR_RR:
6146         case AARCH64_OPND_SVE_ADDR_RR_LSL1:
6147         case AARCH64_OPND_SVE_ADDR_RR_LSL2:
6148         case AARCH64_OPND_SVE_ADDR_RR_LSL3:
6149         case AARCH64_OPND_SVE_ADDR_RX:
6150         case AARCH64_OPND_SVE_ADDR_RX_LSL1:
6151         case AARCH64_OPND_SVE_ADDR_RX_LSL2:
6152         case AARCH64_OPND_SVE_ADDR_RX_LSL3:
6153           /* [<Xn|SP>, <R><m>{, lsl #<amount>}]
6154              but recognizing SVE registers.  */
6155           po_misc_or_fail (parse_sve_address (&str, info, &base_qualifier,
6156                                               &offset_qualifier));
6157           if (base_qualifier != AARCH64_OPND_QLF_X
6158               || offset_qualifier != AARCH64_OPND_QLF_X)
6159             {
6160               set_syntax_error (_("invalid addressing mode"));
6161               goto failure;
6162             }
6163           goto regoff_addr;
6164
6165         case AARCH64_OPND_SVE_ADDR_RZ:
6166         case AARCH64_OPND_SVE_ADDR_RZ_LSL1:
6167         case AARCH64_OPND_SVE_ADDR_RZ_LSL2:
6168         case AARCH64_OPND_SVE_ADDR_RZ_LSL3:
6169         case AARCH64_OPND_SVE_ADDR_RZ_XTW_14:
6170         case AARCH64_OPND_SVE_ADDR_RZ_XTW_22:
6171         case AARCH64_OPND_SVE_ADDR_RZ_XTW1_14:
6172         case AARCH64_OPND_SVE_ADDR_RZ_XTW1_22:
6173         case AARCH64_OPND_SVE_ADDR_RZ_XTW2_14:
6174         case AARCH64_OPND_SVE_ADDR_RZ_XTW2_22:
6175         case AARCH64_OPND_SVE_ADDR_RZ_XTW3_14:
6176         case AARCH64_OPND_SVE_ADDR_RZ_XTW3_22:
6177           /* [<Xn|SP>, Z<m>.D{, LSL #<amount>}]
6178              [<Xn|SP>, Z<m>.<T>, <extend> {#<amount>}]  */
6179           po_misc_or_fail (parse_sve_address (&str, info, &base_qualifier,
6180                                               &offset_qualifier));
6181           if (base_qualifier != AARCH64_OPND_QLF_X
6182               || (offset_qualifier != AARCH64_OPND_QLF_S_S
6183                   && offset_qualifier != AARCH64_OPND_QLF_S_D))
6184             {
6185               set_syntax_error (_("invalid addressing mode"));
6186               goto failure;
6187             }
6188           info->qualifier = offset_qualifier;
6189           goto regoff_addr;
6190
6191         case AARCH64_OPND_SVE_ADDR_ZI_U5:
6192         case AARCH64_OPND_SVE_ADDR_ZI_U5x2:
6193         case AARCH64_OPND_SVE_ADDR_ZI_U5x4:
6194         case AARCH64_OPND_SVE_ADDR_ZI_U5x8:
6195           /* [Z<n>.<T>{, #imm}]  */
6196           po_misc_or_fail (parse_sve_address (&str, info, &base_qualifier,
6197                                               &offset_qualifier));
6198           if (base_qualifier != AARCH64_OPND_QLF_S_S
6199               && base_qualifier != AARCH64_OPND_QLF_S_D)
6200             {
6201               set_syntax_error (_("invalid addressing mode"));
6202               goto failure;
6203             }
6204           info->qualifier = base_qualifier;
6205           goto sve_regimm;
6206
6207         case AARCH64_OPND_SVE_ADDR_ZZ_LSL:
6208         case AARCH64_OPND_SVE_ADDR_ZZ_SXTW:
6209         case AARCH64_OPND_SVE_ADDR_ZZ_UXTW:
6210           /* [Z<n>.<T>, Z<m>.<T>{, LSL #<amount>}]
6211              [Z<n>.D, Z<m>.D, <extend> {#<amount>}]
6212
6213              We don't reject:
6214
6215              [Z<n>.S, Z<m>.S, <extend> {#<amount>}]
6216
6217              here since we get better error messages by leaving it to
6218              the qualifier checking routines.  */
6219           po_misc_or_fail (parse_sve_address (&str, info, &base_qualifier,
6220                                               &offset_qualifier));
6221           if ((base_qualifier != AARCH64_OPND_QLF_S_S
6222                && base_qualifier != AARCH64_OPND_QLF_S_D)
6223               || offset_qualifier != base_qualifier)
6224             {
6225               set_syntax_error (_("invalid addressing mode"));
6226               goto failure;
6227             }
6228           info->qualifier = base_qualifier;
6229           goto regoff_addr;
6230
6231         case AARCH64_OPND_SYSREG:
6232           if ((val = parse_sys_reg (&str, aarch64_sys_regs_hsh, 1, 0))
6233               == PARSE_FAIL)
6234             {
6235               set_syntax_error (_("unknown or missing system register name"));
6236               goto failure;
6237             }
6238           inst.base.operands[i].sysreg = val;
6239           break;
6240
6241         case AARCH64_OPND_PSTATEFIELD:
6242           if ((val = parse_sys_reg (&str, aarch64_pstatefield_hsh, 0, 1))
6243               == PARSE_FAIL)
6244             {
6245               set_syntax_error (_("unknown or missing PSTATE field name"));
6246               goto failure;
6247             }
6248           inst.base.operands[i].pstatefield = val;
6249           break;
6250
6251         case AARCH64_OPND_SYSREG_IC:
6252           inst.base.operands[i].sysins_op =
6253             parse_sys_ins_reg (&str, aarch64_sys_regs_ic_hsh);
6254           goto sys_reg_ins;
6255         case AARCH64_OPND_SYSREG_DC:
6256           inst.base.operands[i].sysins_op =
6257             parse_sys_ins_reg (&str, aarch64_sys_regs_dc_hsh);
6258           goto sys_reg_ins;
6259         case AARCH64_OPND_SYSREG_AT:
6260           inst.base.operands[i].sysins_op =
6261             parse_sys_ins_reg (&str, aarch64_sys_regs_at_hsh);
6262           goto sys_reg_ins;
6263         case AARCH64_OPND_SYSREG_TLBI:
6264           inst.base.operands[i].sysins_op =
6265             parse_sys_ins_reg (&str, aarch64_sys_regs_tlbi_hsh);
6266 sys_reg_ins:
6267           if (inst.base.operands[i].sysins_op == NULL)
6268             {
6269               set_fatal_syntax_error ( _("unknown or missing operation name"));
6270               goto failure;
6271             }
6272           break;
6273
6274         case AARCH64_OPND_BARRIER:
6275         case AARCH64_OPND_BARRIER_ISB:
6276           val = parse_barrier (&str);
6277           if (val != PARSE_FAIL
6278               && operands[i] == AARCH64_OPND_BARRIER_ISB && val != 0xf)
6279             {
6280               /* ISB only accepts options name 'sy'.  */
6281               set_syntax_error
6282                 (_("the specified option is not accepted in ISB"));
6283               /* Turn off backtrack as this optional operand is present.  */
6284               backtrack_pos = 0;
6285               goto failure;
6286             }
6287           /* This is an extension to accept a 0..15 immediate.  */
6288           if (val == PARSE_FAIL)
6289             po_imm_or_fail (0, 15);
6290           info->barrier = aarch64_barrier_options + val;
6291           break;
6292
6293         case AARCH64_OPND_PRFOP:
6294           val = parse_pldop (&str);
6295           /* This is an extension to accept a 0..31 immediate.  */
6296           if (val == PARSE_FAIL)
6297             po_imm_or_fail (0, 31);
6298           inst.base.operands[i].prfop = aarch64_prfops + val;
6299           break;
6300
6301         case AARCH64_OPND_BARRIER_PSB:
6302           val = parse_barrier_psb (&str, &(info->hint_option));
6303           if (val == PARSE_FAIL)
6304             goto failure;
6305           break;
6306
6307         default:
6308           as_fatal (_("unhandled operand code %d"), operands[i]);
6309         }
6310
6311       /* If we get here, this operand was successfully parsed.  */
6312       inst.base.operands[i].present = 1;
6313       continue;
6314
6315 failure:
6316       /* The parse routine should already have set the error, but in case
6317          not, set a default one here.  */
6318       if (! error_p ())
6319         set_default_error ();
6320
6321       if (! backtrack_pos)
6322         goto parse_operands_return;
6323
6324       {
6325         /* We reach here because this operand is marked as optional, and
6326            either no operand was supplied or the operand was supplied but it
6327            was syntactically incorrect.  In the latter case we report an
6328            error.  In the former case we perform a few more checks before
6329            dropping through to the code to insert the default operand.  */
6330
6331         char *tmp = backtrack_pos;
6332         char endchar = END_OF_INSN;
6333
6334         if (i != (aarch64_num_of_operands (opcode) - 1))
6335           endchar = ',';
6336         skip_past_char (&tmp, ',');
6337
6338         if (*tmp != endchar)
6339           /* The user has supplied an operand in the wrong format.  */
6340           goto parse_operands_return;
6341
6342         /* Make sure there is not a comma before the optional operand.
6343            For example the fifth operand of 'sys' is optional:
6344
6345              sys #0,c0,c0,#0,  <--- wrong
6346              sys #0,c0,c0,#0   <--- correct.  */
6347         if (comma_skipped_p && i && endchar == END_OF_INSN)
6348           {
6349             set_fatal_syntax_error
6350               (_("unexpected comma before the omitted optional operand"));
6351             goto parse_operands_return;
6352           }
6353       }
6354
6355       /* Reaching here means we are dealing with an optional operand that is
6356          omitted from the assembly line.  */
6357       gas_assert (optional_operand_p (opcode, i));
6358       info->present = 0;
6359       process_omitted_operand (operands[i], opcode, i, info);
6360
6361       /* Try again, skipping the optional operand at backtrack_pos.  */
6362       str = backtrack_pos;
6363       backtrack_pos = 0;
6364
6365       /* Clear any error record after the omitted optional operand has been
6366          successfully handled.  */
6367       clear_error ();
6368     }
6369
6370   /* Check if we have parsed all the operands.  */
6371   if (*str != '\0' && ! error_p ())
6372     {
6373       /* Set I to the index of the last present operand; this is
6374          for the purpose of diagnostics.  */
6375       for (i -= 1; i >= 0 && !inst.base.operands[i].present; --i)
6376         ;
6377       set_fatal_syntax_error
6378         (_("unexpected characters following instruction"));
6379     }
6380
6381 parse_operands_return:
6382
6383   if (error_p ())
6384     {
6385       DEBUG_TRACE ("parsing FAIL: %s - %s",
6386                    operand_mismatch_kind_names[get_error_kind ()],
6387                    get_error_message ());
6388       /* Record the operand error properly; this is useful when there
6389          are multiple instruction templates for a mnemonic name, so that
6390          later on, we can select the error that most closely describes
6391          the problem.  */
6392       record_operand_error (opcode, i, get_error_kind (),
6393                             get_error_message ());
6394       return FALSE;
6395     }
6396   else
6397     {
6398       DEBUG_TRACE ("parsing SUCCESS");
6399       return TRUE;
6400     }
6401 }
6402
6403 /* It does some fix-up to provide some programmer friendly feature while
6404    keeping the libopcodes happy, i.e. libopcodes only accepts
6405    the preferred architectural syntax.
6406    Return FALSE if there is any failure; otherwise return TRUE.  */
6407
6408 static bfd_boolean
6409 programmer_friendly_fixup (aarch64_instruction *instr)
6410 {
6411   aarch64_inst *base = &instr->base;
6412   const aarch64_opcode *opcode = base->opcode;
6413   enum aarch64_op op = opcode->op;
6414   aarch64_opnd_info *operands = base->operands;
6415
6416   DEBUG_TRACE ("enter");
6417
6418   switch (opcode->iclass)
6419     {
6420     case testbranch:
6421       /* TBNZ Xn|Wn, #uimm6, label
6422          Test and Branch Not Zero: conditionally jumps to label if bit number
6423          uimm6 in register Xn is not zero.  The bit number implies the width of
6424          the register, which may be written and should be disassembled as Wn if
6425          uimm is less than 32.  */
6426       if (operands[0].qualifier == AARCH64_OPND_QLF_W)
6427         {
6428           if (operands[1].imm.value >= 32)
6429             {
6430               record_operand_out_of_range_error (opcode, 1, _("immediate value"),
6431                                                  0, 31);
6432               return FALSE;
6433             }
6434           operands[0].qualifier = AARCH64_OPND_QLF_X;
6435         }
6436       break;
6437     case loadlit:
6438       /* LDR Wt, label | =value
6439          As a convenience assemblers will typically permit the notation
6440          "=value" in conjunction with the pc-relative literal load instructions
6441          to automatically place an immediate value or symbolic address in a
6442          nearby literal pool and generate a hidden label which references it.
6443          ISREG has been set to 0 in the case of =value.  */
6444       if (instr->gen_lit_pool
6445           && (op == OP_LDR_LIT || op == OP_LDRV_LIT || op == OP_LDRSW_LIT))
6446         {
6447           int size = aarch64_get_qualifier_esize (operands[0].qualifier);
6448           if (op == OP_LDRSW_LIT)
6449             size = 4;
6450           if (instr->reloc.exp.X_op != O_constant
6451               && instr->reloc.exp.X_op != O_big
6452               && instr->reloc.exp.X_op != O_symbol)
6453             {
6454               record_operand_error (opcode, 1,
6455                                     AARCH64_OPDE_FATAL_SYNTAX_ERROR,
6456                                     _("constant expression expected"));
6457               return FALSE;
6458             }
6459           if (! add_to_lit_pool (&instr->reloc.exp, size))
6460             {
6461               record_operand_error (opcode, 1,
6462                                     AARCH64_OPDE_OTHER_ERROR,
6463                                     _("literal pool insertion failed"));
6464               return FALSE;
6465             }
6466         }
6467       break;
6468     case log_shift:
6469     case bitfield:
6470       /* UXT[BHW] Wd, Wn
6471          Unsigned Extend Byte|Halfword|Word: UXT[BH] is architectural alias
6472          for UBFM Wd,Wn,#0,#7|15, while UXTW is pseudo instruction which is
6473          encoded using ORR Wd, WZR, Wn (MOV Wd,Wn).
6474          A programmer-friendly assembler should accept a destination Xd in
6475          place of Wd, however that is not the preferred form for disassembly.
6476          */
6477       if ((op == OP_UXTB || op == OP_UXTH || op == OP_UXTW)
6478           && operands[1].qualifier == AARCH64_OPND_QLF_W
6479           && operands[0].qualifier == AARCH64_OPND_QLF_X)
6480         operands[0].qualifier = AARCH64_OPND_QLF_W;
6481       break;
6482
6483     case addsub_ext:
6484         {
6485           /* In the 64-bit form, the final register operand is written as Wm
6486              for all but the (possibly omitted) UXTX/LSL and SXTX
6487              operators.
6488              As a programmer-friendly assembler, we accept e.g.
6489              ADDS <Xd>, <Xn|SP>, <Xm>{, UXTB {#<amount>}} and change it to
6490              ADDS <Xd>, <Xn|SP>, <Wm>{, UXTB {#<amount>}}.  */
6491           int idx = aarch64_operand_index (opcode->operands,
6492                                            AARCH64_OPND_Rm_EXT);
6493           gas_assert (idx == 1 || idx == 2);
6494           if (operands[0].qualifier == AARCH64_OPND_QLF_X
6495               && operands[idx].qualifier == AARCH64_OPND_QLF_X
6496               && operands[idx].shifter.kind != AARCH64_MOD_LSL
6497               && operands[idx].shifter.kind != AARCH64_MOD_UXTX
6498               && operands[idx].shifter.kind != AARCH64_MOD_SXTX)
6499             operands[idx].qualifier = AARCH64_OPND_QLF_W;
6500         }
6501       break;
6502
6503     default:
6504       break;
6505     }
6506
6507   DEBUG_TRACE ("exit with SUCCESS");
6508   return TRUE;
6509 }
6510
6511 /* Check for loads and stores that will cause unpredictable behavior.  */
6512
6513 static void
6514 warn_unpredictable_ldst (aarch64_instruction *instr, char *str)
6515 {
6516   aarch64_inst *base = &instr->base;
6517   const aarch64_opcode *opcode = base->opcode;
6518   const aarch64_opnd_info *opnds = base->operands;
6519   switch (opcode->iclass)
6520     {
6521     case ldst_pos:
6522     case ldst_imm9:
6523     case ldst_imm10:
6524     case ldst_unscaled:
6525     case ldst_unpriv:
6526       /* Loading/storing the base register is unpredictable if writeback.  */
6527       if ((aarch64_get_operand_class (opnds[0].type)
6528            == AARCH64_OPND_CLASS_INT_REG)
6529           && opnds[0].reg.regno == opnds[1].addr.base_regno
6530           && opnds[1].addr.base_regno != REG_SP
6531           && opnds[1].addr.writeback)
6532         as_warn (_("unpredictable transfer with writeback -- `%s'"), str);
6533       break;
6534     case ldstpair_off:
6535     case ldstnapair_offs:
6536     case ldstpair_indexed:
6537       /* Loading/storing the base register is unpredictable if writeback.  */
6538       if ((aarch64_get_operand_class (opnds[0].type)
6539            == AARCH64_OPND_CLASS_INT_REG)
6540           && (opnds[0].reg.regno == opnds[2].addr.base_regno
6541             || opnds[1].reg.regno == opnds[2].addr.base_regno)
6542           && opnds[2].addr.base_regno != REG_SP
6543           && opnds[2].addr.writeback)
6544             as_warn (_("unpredictable transfer with writeback -- `%s'"), str);
6545       /* Load operations must load different registers.  */
6546       if ((opcode->opcode & (1 << 22))
6547           && opnds[0].reg.regno == opnds[1].reg.regno)
6548             as_warn (_("unpredictable load of register pair -- `%s'"), str);
6549       break;
6550     default:
6551       break;
6552     }
6553 }
6554
6555 /* A wrapper function to interface with libopcodes on encoding and
6556    record the error message if there is any.
6557
6558    Return TRUE on success; otherwise return FALSE.  */
6559
6560 static bfd_boolean
6561 do_encode (const aarch64_opcode *opcode, aarch64_inst *instr,
6562            aarch64_insn *code)
6563 {
6564   aarch64_operand_error error_info;
6565   error_info.kind = AARCH64_OPDE_NIL;
6566   if (aarch64_opcode_encode (opcode, instr, code, NULL, &error_info))
6567     return TRUE;
6568   else
6569     {
6570       gas_assert (error_info.kind != AARCH64_OPDE_NIL);
6571       record_operand_error_info (opcode, &error_info);
6572       return FALSE;
6573     }
6574 }
6575
6576 #ifdef DEBUG_AARCH64
6577 static inline void
6578 dump_opcode_operands (const aarch64_opcode *opcode)
6579 {
6580   int i = 0;
6581   while (opcode->operands[i] != AARCH64_OPND_NIL)
6582     {
6583       aarch64_verbose ("\t\t opnd%d: %s", i,
6584                        aarch64_get_operand_name (opcode->operands[i])[0] != '\0'
6585                        ? aarch64_get_operand_name (opcode->operands[i])
6586                        : aarch64_get_operand_desc (opcode->operands[i]));
6587       ++i;
6588     }
6589 }
6590 #endif /* DEBUG_AARCH64 */
6591
6592 /* This is the guts of the machine-dependent assembler.  STR points to a
6593    machine dependent instruction.  This function is supposed to emit
6594    the frags/bytes it assembles to.  */
6595
6596 void
6597 md_assemble (char *str)
6598 {
6599   char *p = str;
6600   templates *template;
6601   aarch64_opcode *opcode;
6602   aarch64_inst *inst_base;
6603   unsigned saved_cond;
6604
6605   /* Align the previous label if needed.  */
6606   if (last_label_seen != NULL)
6607     {
6608       symbol_set_frag (last_label_seen, frag_now);
6609       S_SET_VALUE (last_label_seen, (valueT) frag_now_fix ());
6610       S_SET_SEGMENT (last_label_seen, now_seg);
6611     }
6612
6613   inst.reloc.type = BFD_RELOC_UNUSED;
6614
6615   DEBUG_TRACE ("\n\n");
6616   DEBUG_TRACE ("==============================");
6617   DEBUG_TRACE ("Enter md_assemble with %s", str);
6618
6619   template = opcode_lookup (&p);
6620   if (!template)
6621     {
6622       /* It wasn't an instruction, but it might be a register alias of
6623          the form alias .req reg directive.  */
6624       if (!create_register_alias (str, p))
6625         as_bad (_("unknown mnemonic `%s' -- `%s'"), get_mnemonic_name (str),
6626                 str);
6627       return;
6628     }
6629
6630   skip_whitespace (p);
6631   if (*p == ',')
6632     {
6633       as_bad (_("unexpected comma after the mnemonic name `%s' -- `%s'"),
6634               get_mnemonic_name (str), str);
6635       return;
6636     }
6637
6638   init_operand_error_report ();
6639
6640   /* Sections are assumed to start aligned. In executable section, there is no
6641      MAP_DATA symbol pending. So we only align the address during
6642      MAP_DATA --> MAP_INSN transition.
6643      For other sections, this is not guaranteed.  */
6644   enum mstate mapstate = seg_info (now_seg)->tc_segment_info_data.mapstate;
6645   if (!need_pass_2 && subseg_text_p (now_seg) && mapstate == MAP_DATA)
6646     frag_align_code (2, 0);
6647
6648   saved_cond = inst.cond;
6649   reset_aarch64_instruction (&inst);
6650   inst.cond = saved_cond;
6651
6652   /* Iterate through all opcode entries with the same mnemonic name.  */
6653   do
6654     {
6655       opcode = template->opcode;
6656
6657       DEBUG_TRACE ("opcode %s found", opcode->name);
6658 #ifdef DEBUG_AARCH64
6659       if (debug_dump)
6660         dump_opcode_operands (opcode);
6661 #endif /* DEBUG_AARCH64 */
6662
6663       mapping_state (MAP_INSN);
6664
6665       inst_base = &inst.base;
6666       inst_base->opcode = opcode;
6667
6668       /* Truly conditionally executed instructions, e.g. b.cond.  */
6669       if (opcode->flags & F_COND)
6670         {
6671           gas_assert (inst.cond != COND_ALWAYS);
6672           inst_base->cond = get_cond_from_value (inst.cond);
6673           DEBUG_TRACE ("condition found %s", inst_base->cond->names[0]);
6674         }
6675       else if (inst.cond != COND_ALWAYS)
6676         {
6677           /* It shouldn't arrive here, where the assembly looks like a
6678              conditional instruction but the found opcode is unconditional.  */
6679           gas_assert (0);
6680           continue;
6681         }
6682
6683       if (parse_operands (p, opcode)
6684           && programmer_friendly_fixup (&inst)
6685           && do_encode (inst_base->opcode, &inst.base, &inst_base->value))
6686         {
6687           /* Check that this instruction is supported for this CPU.  */
6688           if (!opcode->avariant
6689               || !AARCH64_CPU_HAS_ALL_FEATURES (cpu_variant, *opcode->avariant))
6690             {
6691               as_bad (_("selected processor does not support `%s'"), str);
6692               return;
6693             }
6694
6695           warn_unpredictable_ldst (&inst, str);
6696
6697           if (inst.reloc.type == BFD_RELOC_UNUSED
6698               || !inst.reloc.need_libopcodes_p)
6699             output_inst (NULL);
6700           else
6701             {
6702               /* If there is relocation generated for the instruction,
6703                  store the instruction information for the future fix-up.  */
6704               struct aarch64_inst *copy;
6705               gas_assert (inst.reloc.type != BFD_RELOC_UNUSED);
6706               copy = XNEW (struct aarch64_inst);
6707               memcpy (copy, &inst.base, sizeof (struct aarch64_inst));
6708               output_inst (copy);
6709             }
6710           return;
6711         }
6712
6713       template = template->next;
6714       if (template != NULL)
6715         {
6716           reset_aarch64_instruction (&inst);
6717           inst.cond = saved_cond;
6718         }
6719     }
6720   while (template != NULL);
6721
6722   /* Issue the error messages if any.  */
6723   output_operand_error_report (str);
6724 }
6725
6726 /* Various frobbings of labels and their addresses.  */
6727
6728 void
6729 aarch64_start_line_hook (void)
6730 {
6731   last_label_seen = NULL;
6732 }
6733
6734 void
6735 aarch64_frob_label (symbolS * sym)
6736 {
6737   last_label_seen = sym;
6738
6739   dwarf2_emit_label (sym);
6740 }
6741
6742 int
6743 aarch64_data_in_code (void)
6744 {
6745   if (!strncmp (input_line_pointer + 1, "data:", 5))
6746     {
6747       *input_line_pointer = '/';
6748       input_line_pointer += 5;
6749       *input_line_pointer = 0;
6750       return 1;
6751     }
6752
6753   return 0;
6754 }
6755
6756 char *
6757 aarch64_canonicalize_symbol_name (char *name)
6758 {
6759   int len;
6760
6761   if ((len = strlen (name)) > 5 && streq (name + len - 5, "/data"))
6762     *(name + len - 5) = 0;
6763
6764   return name;
6765 }
6766 \f
6767 /* Table of all register names defined by default.  The user can
6768    define additional names with .req.  Note that all register names
6769    should appear in both upper and lowercase variants.  Some registers
6770    also have mixed-case names.  */
6771
6772 #define REGDEF(s,n,t) { #s, n, REG_TYPE_##t, TRUE }
6773 #define REGNUM(p,n,t) REGDEF(p##n, n, t)
6774 #define REGSET16(p,t) \
6775   REGNUM(p, 0,t), REGNUM(p, 1,t), REGNUM(p, 2,t), REGNUM(p, 3,t), \
6776   REGNUM(p, 4,t), REGNUM(p, 5,t), REGNUM(p, 6,t), REGNUM(p, 7,t), \
6777   REGNUM(p, 8,t), REGNUM(p, 9,t), REGNUM(p,10,t), REGNUM(p,11,t), \
6778   REGNUM(p,12,t), REGNUM(p,13,t), REGNUM(p,14,t), REGNUM(p,15,t)
6779 #define REGSET31(p,t) \
6780   REGSET16(p, t), \
6781   REGNUM(p,16,t), REGNUM(p,17,t), REGNUM(p,18,t), REGNUM(p,19,t), \
6782   REGNUM(p,20,t), REGNUM(p,21,t), REGNUM(p,22,t), REGNUM(p,23,t), \
6783   REGNUM(p,24,t), REGNUM(p,25,t), REGNUM(p,26,t), REGNUM(p,27,t), \
6784   REGNUM(p,28,t), REGNUM(p,29,t), REGNUM(p,30,t)
6785 #define REGSET(p,t) \
6786   REGSET31(p,t), REGNUM(p,31,t)
6787
6788 /* These go into aarch64_reg_hsh hash-table.  */
6789 static const reg_entry reg_names[] = {
6790   /* Integer registers.  */
6791   REGSET31 (x, R_64), REGSET31 (X, R_64),
6792   REGSET31 (w, R_32), REGSET31 (W, R_32),
6793
6794   REGDEF (wsp, 31, SP_32), REGDEF (WSP, 31, SP_32),
6795   REGDEF (sp, 31, SP_64), REGDEF (SP, 31, SP_64),
6796
6797   REGDEF (wzr, 31, Z_32), REGDEF (WZR, 31, Z_32),
6798   REGDEF (xzr, 31, Z_64), REGDEF (XZR, 31, Z_64),
6799
6800   REGDEF (ip0, 16, R_64), REGDEF (IP0, 16, R_64),
6801   REGDEF (ip1, 17, R_64), REGDEF (IP1, 17, R_64),
6802   REGDEF (fp, 29, R_64), REGDEF (FP, 29, R_64),
6803   REGDEF (lr, 30, R_64), REGDEF (LR, 30, R_64),
6804
6805   /* Floating-point single precision registers.  */
6806   REGSET (s, FP_S), REGSET (S, FP_S),
6807
6808   /* Floating-point double precision registers.  */
6809   REGSET (d, FP_D), REGSET (D, FP_D),
6810
6811   /* Floating-point half precision registers.  */
6812   REGSET (h, FP_H), REGSET (H, FP_H),
6813
6814   /* Floating-point byte precision registers.  */
6815   REGSET (b, FP_B), REGSET (B, FP_B),
6816
6817   /* Floating-point quad precision registers.  */
6818   REGSET (q, FP_Q), REGSET (Q, FP_Q),
6819
6820   /* FP/SIMD registers.  */
6821   REGSET (v, VN), REGSET (V, VN),
6822
6823   /* SVE vector registers.  */
6824   REGSET (z, ZN), REGSET (Z, ZN),
6825
6826   /* SVE predicate registers.  */
6827   REGSET16 (p, PN), REGSET16 (P, PN)
6828 };
6829
6830 #undef REGDEF
6831 #undef REGNUM
6832 #undef REGSET16
6833 #undef REGSET31
6834 #undef REGSET
6835
6836 #define N 1
6837 #define n 0
6838 #define Z 1
6839 #define z 0
6840 #define C 1
6841 #define c 0
6842 #define V 1
6843 #define v 0
6844 #define B(a,b,c,d) (((a) << 3) | ((b) << 2) | ((c) << 1) | (d))
6845 static const asm_nzcv nzcv_names[] = {
6846   {"nzcv", B (n, z, c, v)},
6847   {"nzcV", B (n, z, c, V)},
6848   {"nzCv", B (n, z, C, v)},
6849   {"nzCV", B (n, z, C, V)},
6850   {"nZcv", B (n, Z, c, v)},
6851   {"nZcV", B (n, Z, c, V)},
6852   {"nZCv", B (n, Z, C, v)},
6853   {"nZCV", B (n, Z, C, V)},
6854   {"Nzcv", B (N, z, c, v)},
6855   {"NzcV", B (N, z, c, V)},
6856   {"NzCv", B (N, z, C, v)},
6857   {"NzCV", B (N, z, C, V)},
6858   {"NZcv", B (N, Z, c, v)},
6859   {"NZcV", B (N, Z, c, V)},
6860   {"NZCv", B (N, Z, C, v)},
6861   {"NZCV", B (N, Z, C, V)}
6862 };
6863
6864 #undef N
6865 #undef n
6866 #undef Z
6867 #undef z
6868 #undef C
6869 #undef c
6870 #undef V
6871 #undef v
6872 #undef B
6873 \f
6874 /* MD interface: bits in the object file.  */
6875
6876 /* Turn an integer of n bytes (in val) into a stream of bytes appropriate
6877    for use in the a.out file, and stores them in the array pointed to by buf.
6878    This knows about the endian-ness of the target machine and does
6879    THE RIGHT THING, whatever it is.  Possible values for n are 1 (byte)
6880    2 (short) and 4 (long)  Floating numbers are put out as a series of
6881    LITTLENUMS (shorts, here at least).  */
6882
6883 void
6884 md_number_to_chars (char *buf, valueT val, int n)
6885 {
6886   if (target_big_endian)
6887     number_to_chars_bigendian (buf, val, n);
6888   else
6889     number_to_chars_littleendian (buf, val, n);
6890 }
6891
6892 /* MD interface: Sections.  */
6893
6894 /* Estimate the size of a frag before relaxing.  Assume everything fits in
6895    4 bytes.  */
6896
6897 int
6898 md_estimate_size_before_relax (fragS * fragp, segT segtype ATTRIBUTE_UNUSED)
6899 {
6900   fragp->fr_var = 4;
6901   return 4;
6902 }
6903
6904 /* Round up a section size to the appropriate boundary.  */
6905
6906 valueT
6907 md_section_align (segT segment ATTRIBUTE_UNUSED, valueT size)
6908 {
6909   return size;
6910 }
6911
6912 /* This is called from HANDLE_ALIGN in write.c.  Fill in the contents
6913    of an rs_align_code fragment.
6914
6915    Here we fill the frag with the appropriate info for padding the
6916    output stream.  The resulting frag will consist of a fixed (fr_fix)
6917    and of a repeating (fr_var) part.
6918
6919    The fixed content is always emitted before the repeating content and
6920    these two parts are used as follows in constructing the output:
6921    - the fixed part will be used to align to a valid instruction word
6922      boundary, in case that we start at a misaligned address; as no
6923      executable instruction can live at the misaligned location, we
6924      simply fill with zeros;
6925    - the variable part will be used to cover the remaining padding and
6926      we fill using the AArch64 NOP instruction.
6927
6928    Note that the size of a RS_ALIGN_CODE fragment is always 7 to provide
6929    enough storage space for up to 3 bytes for padding the back to a valid
6930    instruction alignment and exactly 4 bytes to store the NOP pattern.  */
6931
6932 void
6933 aarch64_handle_align (fragS * fragP)
6934 {
6935   /* NOP = d503201f */
6936   /* AArch64 instructions are always little-endian.  */
6937   static unsigned char const aarch64_noop[4] = { 0x1f, 0x20, 0x03, 0xd5 };
6938
6939   int bytes, fix, noop_size;
6940   char *p;
6941
6942   if (fragP->fr_type != rs_align_code)
6943     return;
6944
6945   bytes = fragP->fr_next->fr_address - fragP->fr_address - fragP->fr_fix;
6946   p = fragP->fr_literal + fragP->fr_fix;
6947
6948 #ifdef OBJ_ELF
6949   gas_assert (fragP->tc_frag_data.recorded);
6950 #endif
6951
6952   noop_size = sizeof (aarch64_noop);
6953
6954   fix = bytes & (noop_size - 1);
6955   if (fix)
6956     {
6957 #ifdef OBJ_ELF
6958       insert_data_mapping_symbol (MAP_INSN, fragP->fr_fix, fragP, fix);
6959 #endif
6960       memset (p, 0, fix);
6961       p += fix;
6962       fragP->fr_fix += fix;
6963     }
6964
6965   if (noop_size)
6966     memcpy (p, aarch64_noop, noop_size);
6967   fragP->fr_var = noop_size;
6968 }
6969
6970 /* Perform target specific initialisation of a frag.
6971    Note - despite the name this initialisation is not done when the frag
6972    is created, but only when its type is assigned.  A frag can be created
6973    and used a long time before its type is set, so beware of assuming that
6974    this initialisation is performed first.  */
6975
6976 #ifndef OBJ_ELF
6977 void
6978 aarch64_init_frag (fragS * fragP ATTRIBUTE_UNUSED,
6979                    int max_chars ATTRIBUTE_UNUSED)
6980 {
6981 }
6982
6983 #else /* OBJ_ELF is defined.  */
6984 void
6985 aarch64_init_frag (fragS * fragP, int max_chars)
6986 {
6987   /* Record a mapping symbol for alignment frags.  We will delete this
6988      later if the alignment ends up empty.  */
6989   if (!fragP->tc_frag_data.recorded)
6990     fragP->tc_frag_data.recorded = 1;
6991
6992   switch (fragP->fr_type)
6993     {
6994     case rs_align_test:
6995     case rs_fill:
6996       mapping_state_2 (MAP_DATA, max_chars);
6997       break;
6998     case rs_align:
6999       /* PR 20364: We can get alignment frags in code sections,
7000          so do not just assume that we should use the MAP_DATA state.  */
7001       mapping_state_2 (subseg_text_p (now_seg) ? MAP_INSN : MAP_DATA, max_chars);
7002       break;
7003     case rs_align_code:
7004       mapping_state_2 (MAP_INSN, max_chars);
7005       break;
7006     default:
7007       break;
7008     }
7009 }
7010 \f
7011 /* Initialize the DWARF-2 unwind information for this procedure.  */
7012
7013 void
7014 tc_aarch64_frame_initial_instructions (void)
7015 {
7016   cfi_add_CFA_def_cfa (REG_SP, 0);
7017 }
7018 #endif /* OBJ_ELF */
7019
7020 /* Convert REGNAME to a DWARF-2 register number.  */
7021
7022 int
7023 tc_aarch64_regname_to_dw2regnum (char *regname)
7024 {
7025   const reg_entry *reg = parse_reg (&regname);
7026   if (reg == NULL)
7027     return -1;
7028
7029   switch (reg->type)
7030     {
7031     case REG_TYPE_SP_32:
7032     case REG_TYPE_SP_64:
7033     case REG_TYPE_R_32:
7034     case REG_TYPE_R_64:
7035       return reg->number;
7036
7037     case REG_TYPE_FP_B:
7038     case REG_TYPE_FP_H:
7039     case REG_TYPE_FP_S:
7040     case REG_TYPE_FP_D:
7041     case REG_TYPE_FP_Q:
7042       return reg->number + 64;
7043
7044     default:
7045       break;
7046     }
7047   return -1;
7048 }
7049
7050 /* Implement DWARF2_ADDR_SIZE.  */
7051
7052 int
7053 aarch64_dwarf2_addr_size (void)
7054 {
7055 #if defined (OBJ_MAYBE_ELF) || defined (OBJ_ELF)
7056   if (ilp32_p)
7057     return 4;
7058 #endif
7059   return bfd_arch_bits_per_address (stdoutput) / 8;
7060 }
7061
7062 /* MD interface: Symbol and relocation handling.  */
7063
7064 /* Return the address within the segment that a PC-relative fixup is
7065    relative to.  For AArch64 PC-relative fixups applied to instructions
7066    are generally relative to the location plus AARCH64_PCREL_OFFSET bytes.  */
7067
7068 long
7069 md_pcrel_from_section (fixS * fixP, segT seg)
7070 {
7071   offsetT base = fixP->fx_where + fixP->fx_frag->fr_address;
7072
7073   /* If this is pc-relative and we are going to emit a relocation
7074      then we just want to put out any pipeline compensation that the linker
7075      will need.  Otherwise we want to use the calculated base.  */
7076   if (fixP->fx_pcrel
7077       && ((fixP->fx_addsy && S_GET_SEGMENT (fixP->fx_addsy) != seg)
7078           || aarch64_force_relocation (fixP)))
7079     base = 0;
7080
7081   /* AArch64 should be consistent for all pc-relative relocations.  */
7082   return base + AARCH64_PCREL_OFFSET;
7083 }
7084
7085 /* Under ELF we need to default _GLOBAL_OFFSET_TABLE.
7086    Otherwise we have no need to default values of symbols.  */
7087
7088 symbolS *
7089 md_undefined_symbol (char *name ATTRIBUTE_UNUSED)
7090 {
7091 #ifdef OBJ_ELF
7092   if (name[0] == '_' && name[1] == 'G'
7093       && streq (name, GLOBAL_OFFSET_TABLE_NAME))
7094     {
7095       if (!GOT_symbol)
7096         {
7097           if (symbol_find (name))
7098             as_bad (_("GOT already in the symbol table"));
7099
7100           GOT_symbol = symbol_new (name, undefined_section,
7101                                    (valueT) 0, &zero_address_frag);
7102         }
7103
7104       return GOT_symbol;
7105     }
7106 #endif
7107
7108   return 0;
7109 }
7110
7111 /* Return non-zero if the indicated VALUE has overflowed the maximum
7112    range expressible by a unsigned number with the indicated number of
7113    BITS.  */
7114
7115 static bfd_boolean
7116 unsigned_overflow (valueT value, unsigned bits)
7117 {
7118   valueT lim;
7119   if (bits >= sizeof (valueT) * 8)
7120     return FALSE;
7121   lim = (valueT) 1 << bits;
7122   return (value >= lim);
7123 }
7124
7125
7126 /* Return non-zero if the indicated VALUE has overflowed the maximum
7127    range expressible by an signed number with the indicated number of
7128    BITS.  */
7129
7130 static bfd_boolean
7131 signed_overflow (offsetT value, unsigned bits)
7132 {
7133   offsetT lim;
7134   if (bits >= sizeof (offsetT) * 8)
7135     return FALSE;
7136   lim = (offsetT) 1 << (bits - 1);
7137   return (value < -lim || value >= lim);
7138 }
7139
7140 /* Given an instruction in *INST, which is expected to be a scaled, 12-bit,
7141    unsigned immediate offset load/store instruction, try to encode it as
7142    an unscaled, 9-bit, signed immediate offset load/store instruction.
7143    Return TRUE if it is successful; otherwise return FALSE.
7144
7145    As a programmer-friendly assembler, LDUR/STUR instructions can be generated
7146    in response to the standard LDR/STR mnemonics when the immediate offset is
7147    unambiguous, i.e. when it is negative or unaligned.  */
7148
7149 static bfd_boolean
7150 try_to_encode_as_unscaled_ldst (aarch64_inst *instr)
7151 {
7152   int idx;
7153   enum aarch64_op new_op;
7154   const aarch64_opcode *new_opcode;
7155
7156   gas_assert (instr->opcode->iclass == ldst_pos);
7157
7158   switch (instr->opcode->op)
7159     {
7160     case OP_LDRB_POS:new_op = OP_LDURB; break;
7161     case OP_STRB_POS: new_op = OP_STURB; break;
7162     case OP_LDRSB_POS: new_op = OP_LDURSB; break;
7163     case OP_LDRH_POS: new_op = OP_LDURH; break;
7164     case OP_STRH_POS: new_op = OP_STURH; break;
7165     case OP_LDRSH_POS: new_op = OP_LDURSH; break;
7166     case OP_LDR_POS: new_op = OP_LDUR; break;
7167     case OP_STR_POS: new_op = OP_STUR; break;
7168     case OP_LDRF_POS: new_op = OP_LDURV; break;
7169     case OP_STRF_POS: new_op = OP_STURV; break;
7170     case OP_LDRSW_POS: new_op = OP_LDURSW; break;
7171     case OP_PRFM_POS: new_op = OP_PRFUM; break;
7172     default: new_op = OP_NIL; break;
7173     }
7174
7175   if (new_op == OP_NIL)
7176     return FALSE;
7177
7178   new_opcode = aarch64_get_opcode (new_op);
7179   gas_assert (new_opcode != NULL);
7180
7181   DEBUG_TRACE ("Check programmer-friendly STURB/LDURB -> STRB/LDRB: %d == %d",
7182                instr->opcode->op, new_opcode->op);
7183
7184   aarch64_replace_opcode (instr, new_opcode);
7185
7186   /* Clear up the ADDR_SIMM9's qualifier; otherwise the
7187      qualifier matching may fail because the out-of-date qualifier will
7188      prevent the operand being updated with a new and correct qualifier.  */
7189   idx = aarch64_operand_index (instr->opcode->operands,
7190                                AARCH64_OPND_ADDR_SIMM9);
7191   gas_assert (idx == 1);
7192   instr->operands[idx].qualifier = AARCH64_OPND_QLF_NIL;
7193
7194   DEBUG_TRACE ("Found LDURB entry to encode programmer-friendly LDRB");
7195
7196   if (!aarch64_opcode_encode (instr->opcode, instr, &instr->value, NULL, NULL))
7197     return FALSE;
7198
7199   return TRUE;
7200 }
7201
7202 /* Called by fix_insn to fix a MOV immediate alias instruction.
7203
7204    Operand for a generic move immediate instruction, which is an alias
7205    instruction that generates a single MOVZ, MOVN or ORR instruction to loads
7206    a 32-bit/64-bit immediate value into general register.  An assembler error
7207    shall result if the immediate cannot be created by a single one of these
7208    instructions. If there is a choice, then to ensure reversability an
7209    assembler must prefer a MOVZ to MOVN, and MOVZ or MOVN to ORR.  */
7210
7211 static void
7212 fix_mov_imm_insn (fixS *fixP, char *buf, aarch64_inst *instr, offsetT value)
7213 {
7214   const aarch64_opcode *opcode;
7215
7216   /* Need to check if the destination is SP/ZR.  The check has to be done
7217      before any aarch64_replace_opcode.  */
7218   int try_mov_wide_p = !aarch64_stack_pointer_p (&instr->operands[0]);
7219   int try_mov_bitmask_p = !aarch64_zero_register_p (&instr->operands[0]);
7220
7221   instr->operands[1].imm.value = value;
7222   instr->operands[1].skip = 0;
7223
7224   if (try_mov_wide_p)
7225     {
7226       /* Try the MOVZ alias.  */
7227       opcode = aarch64_get_opcode (OP_MOV_IMM_WIDE);
7228       aarch64_replace_opcode (instr, opcode);
7229       if (aarch64_opcode_encode (instr->opcode, instr,
7230                                  &instr->value, NULL, NULL))
7231         {
7232           put_aarch64_insn (buf, instr->value);
7233           return;
7234         }
7235       /* Try the MOVK alias.  */
7236       opcode = aarch64_get_opcode (OP_MOV_IMM_WIDEN);
7237       aarch64_replace_opcode (instr, opcode);
7238       if (aarch64_opcode_encode (instr->opcode, instr,
7239                                  &instr->value, NULL, NULL))
7240         {
7241           put_aarch64_insn (buf, instr->value);
7242           return;
7243         }
7244     }
7245
7246   if (try_mov_bitmask_p)
7247     {
7248       /* Try the ORR alias.  */
7249       opcode = aarch64_get_opcode (OP_MOV_IMM_LOG);
7250       aarch64_replace_opcode (instr, opcode);
7251       if (aarch64_opcode_encode (instr->opcode, instr,
7252                                  &instr->value, NULL, NULL))
7253         {
7254           put_aarch64_insn (buf, instr->value);
7255           return;
7256         }
7257     }
7258
7259   as_bad_where (fixP->fx_file, fixP->fx_line,
7260                 _("immediate cannot be moved by a single instruction"));
7261 }
7262
7263 /* An instruction operand which is immediate related may have symbol used
7264    in the assembly, e.g.
7265
7266      mov     w0, u32
7267      .set    u32,    0x00ffff00
7268
7269    At the time when the assembly instruction is parsed, a referenced symbol,
7270    like 'u32' in the above example may not have been seen; a fixS is created
7271    in such a case and is handled here after symbols have been resolved.
7272    Instruction is fixed up with VALUE using the information in *FIXP plus
7273    extra information in FLAGS.
7274
7275    This function is called by md_apply_fix to fix up instructions that need
7276    a fix-up described above but does not involve any linker-time relocation.  */
7277
7278 static void
7279 fix_insn (fixS *fixP, uint32_t flags, offsetT value)
7280 {
7281   int idx;
7282   uint32_t insn;
7283   char *buf = fixP->fx_where + fixP->fx_frag->fr_literal;
7284   enum aarch64_opnd opnd = fixP->tc_fix_data.opnd;
7285   aarch64_inst *new_inst = fixP->tc_fix_data.inst;
7286
7287   if (new_inst)
7288     {
7289       /* Now the instruction is about to be fixed-up, so the operand that
7290          was previously marked as 'ignored' needs to be unmarked in order
7291          to get the encoding done properly.  */
7292       idx = aarch64_operand_index (new_inst->opcode->operands, opnd);
7293       new_inst->operands[idx].skip = 0;
7294     }
7295
7296   gas_assert (opnd != AARCH64_OPND_NIL);
7297
7298   switch (opnd)
7299     {
7300     case AARCH64_OPND_EXCEPTION:
7301       if (unsigned_overflow (value, 16))
7302         as_bad_where (fixP->fx_file, fixP->fx_line,
7303                       _("immediate out of range"));
7304       insn = get_aarch64_insn (buf);
7305       insn |= encode_svc_imm (value);
7306       put_aarch64_insn (buf, insn);
7307       break;
7308
7309     case AARCH64_OPND_AIMM:
7310       /* ADD or SUB with immediate.
7311          NOTE this assumes we come here with a add/sub shifted reg encoding
7312                   3  322|2222|2  2  2 21111 111111
7313                   1  098|7654|3  2  1 09876 543210 98765 43210
7314          0b000000 sf 000|1011|shift 0 Rm    imm6   Rn    Rd    ADD
7315          2b000000 sf 010|1011|shift 0 Rm    imm6   Rn    Rd    ADDS
7316          4b000000 sf 100|1011|shift 0 Rm    imm6   Rn    Rd    SUB
7317          6b000000 sf 110|1011|shift 0 Rm    imm6   Rn    Rd    SUBS
7318          ->
7319                   3  322|2222|2 2   221111111111
7320                   1  098|7654|3 2   109876543210 98765 43210
7321          11000000 sf 001|0001|shift imm12        Rn    Rd    ADD
7322          31000000 sf 011|0001|shift imm12        Rn    Rd    ADDS
7323          51000000 sf 101|0001|shift imm12        Rn    Rd    SUB
7324          71000000 sf 111|0001|shift imm12        Rn    Rd    SUBS
7325          Fields sf Rn Rd are already set.  */
7326       insn = get_aarch64_insn (buf);
7327       if (value < 0)
7328         {
7329           /* Add <-> sub.  */
7330           insn = reencode_addsub_switch_add_sub (insn);
7331           value = -value;
7332         }
7333
7334       if ((flags & FIXUP_F_HAS_EXPLICIT_SHIFT) == 0
7335           && unsigned_overflow (value, 12))
7336         {
7337           /* Try to shift the value by 12 to make it fit.  */
7338           if (((value >> 12) << 12) == value
7339               && ! unsigned_overflow (value, 12 + 12))
7340             {
7341               value >>= 12;
7342               insn |= encode_addsub_imm_shift_amount (1);
7343             }
7344         }
7345
7346       if (unsigned_overflow (value, 12))
7347         as_bad_where (fixP->fx_file, fixP->fx_line,
7348                       _("immediate out of range"));
7349
7350       insn |= encode_addsub_imm (value);
7351
7352       put_aarch64_insn (buf, insn);
7353       break;
7354
7355     case AARCH64_OPND_SIMD_IMM:
7356     case AARCH64_OPND_SIMD_IMM_SFT:
7357     case AARCH64_OPND_LIMM:
7358       /* Bit mask immediate.  */
7359       gas_assert (new_inst != NULL);
7360       idx = aarch64_operand_index (new_inst->opcode->operands, opnd);
7361       new_inst->operands[idx].imm.value = value;
7362       if (aarch64_opcode_encode (new_inst->opcode, new_inst,
7363                                  &new_inst->value, NULL, NULL))
7364         put_aarch64_insn (buf, new_inst->value);
7365       else
7366         as_bad_where (fixP->fx_file, fixP->fx_line,
7367                       _("invalid immediate"));
7368       break;
7369
7370     case AARCH64_OPND_HALF:
7371       /* 16-bit unsigned immediate.  */
7372       if (unsigned_overflow (value, 16))
7373         as_bad_where (fixP->fx_file, fixP->fx_line,
7374                       _("immediate out of range"));
7375       insn = get_aarch64_insn (buf);
7376       insn |= encode_movw_imm (value & 0xffff);
7377       put_aarch64_insn (buf, insn);
7378       break;
7379
7380     case AARCH64_OPND_IMM_MOV:
7381       /* Operand for a generic move immediate instruction, which is
7382          an alias instruction that generates a single MOVZ, MOVN or ORR
7383          instruction to loads a 32-bit/64-bit immediate value into general
7384          register.  An assembler error shall result if the immediate cannot be
7385          created by a single one of these instructions. If there is a choice,
7386          then to ensure reversability an assembler must prefer a MOVZ to MOVN,
7387          and MOVZ or MOVN to ORR.  */
7388       gas_assert (new_inst != NULL);
7389       fix_mov_imm_insn (fixP, buf, new_inst, value);
7390       break;
7391
7392     case AARCH64_OPND_ADDR_SIMM7:
7393     case AARCH64_OPND_ADDR_SIMM9:
7394     case AARCH64_OPND_ADDR_SIMM9_2:
7395     case AARCH64_OPND_ADDR_SIMM10:
7396     case AARCH64_OPND_ADDR_UIMM12:
7397       /* Immediate offset in an address.  */
7398       insn = get_aarch64_insn (buf);
7399
7400       gas_assert (new_inst != NULL && new_inst->value == insn);
7401       gas_assert (new_inst->opcode->operands[1] == opnd
7402                   || new_inst->opcode->operands[2] == opnd);
7403
7404       /* Get the index of the address operand.  */
7405       if (new_inst->opcode->operands[1] == opnd)
7406         /* e.g. STR <Xt>, [<Xn|SP>, <R><m>{, <extend> {<amount>}}].  */
7407         idx = 1;
7408       else
7409         /* e.g. LDP <Qt1>, <Qt2>, [<Xn|SP>{, #<imm>}].  */
7410         idx = 2;
7411
7412       /* Update the resolved offset value.  */
7413       new_inst->operands[idx].addr.offset.imm = value;
7414
7415       /* Encode/fix-up.  */
7416       if (aarch64_opcode_encode (new_inst->opcode, new_inst,
7417                                  &new_inst->value, NULL, NULL))
7418         {
7419           put_aarch64_insn (buf, new_inst->value);
7420           break;
7421         }
7422       else if (new_inst->opcode->iclass == ldst_pos
7423                && try_to_encode_as_unscaled_ldst (new_inst))
7424         {
7425           put_aarch64_insn (buf, new_inst->value);
7426           break;
7427         }
7428
7429       as_bad_where (fixP->fx_file, fixP->fx_line,
7430                     _("immediate offset out of range"));
7431       break;
7432
7433     default:
7434       gas_assert (0);
7435       as_fatal (_("unhandled operand code %d"), opnd);
7436     }
7437 }
7438
7439 /* Apply a fixup (fixP) to segment data, once it has been determined
7440    by our caller that we have all the info we need to fix it up.
7441
7442    Parameter valP is the pointer to the value of the bits.  */
7443
7444 void
7445 md_apply_fix (fixS * fixP, valueT * valP, segT seg)
7446 {
7447   offsetT value = *valP;
7448   uint32_t insn;
7449   char *buf = fixP->fx_where + fixP->fx_frag->fr_literal;
7450   int scale;
7451   unsigned flags = fixP->fx_addnumber;
7452
7453   DEBUG_TRACE ("\n\n");
7454   DEBUG_TRACE ("~~~~~~~~~~~~~~~~~~~~~~~~~");
7455   DEBUG_TRACE ("Enter md_apply_fix");
7456
7457   gas_assert (fixP->fx_r_type <= BFD_RELOC_UNUSED);
7458
7459   /* Note whether this will delete the relocation.  */
7460
7461   if (fixP->fx_addsy == 0 && !fixP->fx_pcrel)
7462     fixP->fx_done = 1;
7463
7464   /* Process the relocations.  */
7465   switch (fixP->fx_r_type)
7466     {
7467     case BFD_RELOC_NONE:
7468       /* This will need to go in the object file.  */
7469       fixP->fx_done = 0;
7470       break;
7471
7472     case BFD_RELOC_8:
7473     case BFD_RELOC_8_PCREL:
7474       if (fixP->fx_done || !seg->use_rela_p)
7475         md_number_to_chars (buf, value, 1);
7476       break;
7477
7478     case BFD_RELOC_16:
7479     case BFD_RELOC_16_PCREL:
7480       if (fixP->fx_done || !seg->use_rela_p)
7481         md_number_to_chars (buf, value, 2);
7482       break;
7483
7484     case BFD_RELOC_32:
7485     case BFD_RELOC_32_PCREL:
7486       if (fixP->fx_done || !seg->use_rela_p)
7487         md_number_to_chars (buf, value, 4);
7488       break;
7489
7490     case BFD_RELOC_64:
7491     case BFD_RELOC_64_PCREL:
7492       if (fixP->fx_done || !seg->use_rela_p)
7493         md_number_to_chars (buf, value, 8);
7494       break;
7495
7496     case BFD_RELOC_AARCH64_GAS_INTERNAL_FIXUP:
7497       /* We claim that these fixups have been processed here, even if
7498          in fact we generate an error because we do not have a reloc
7499          for them, so tc_gen_reloc() will reject them.  */
7500       fixP->fx_done = 1;
7501       if (fixP->fx_addsy && !S_IS_DEFINED (fixP->fx_addsy))
7502         {
7503           as_bad_where (fixP->fx_file, fixP->fx_line,
7504                         _("undefined symbol %s used as an immediate value"),
7505                         S_GET_NAME (fixP->fx_addsy));
7506           goto apply_fix_return;
7507         }
7508       fix_insn (fixP, flags, value);
7509       break;
7510
7511     case BFD_RELOC_AARCH64_LD_LO19_PCREL:
7512       if (fixP->fx_done || !seg->use_rela_p)
7513         {
7514           if (value & 3)
7515             as_bad_where (fixP->fx_file, fixP->fx_line,
7516                           _("pc-relative load offset not word aligned"));
7517           if (signed_overflow (value, 21))
7518             as_bad_where (fixP->fx_file, fixP->fx_line,
7519                           _("pc-relative load offset out of range"));
7520           insn = get_aarch64_insn (buf);
7521           insn |= encode_ld_lit_ofs_19 (value >> 2);
7522           put_aarch64_insn (buf, insn);
7523         }
7524       break;
7525
7526     case BFD_RELOC_AARCH64_ADR_LO21_PCREL:
7527       if (fixP->fx_done || !seg->use_rela_p)
7528         {
7529           if (signed_overflow (value, 21))
7530             as_bad_where (fixP->fx_file, fixP->fx_line,
7531                           _("pc-relative address offset out of range"));
7532           insn = get_aarch64_insn (buf);
7533           insn |= encode_adr_imm (value);
7534           put_aarch64_insn (buf, insn);
7535         }
7536       break;
7537
7538     case BFD_RELOC_AARCH64_BRANCH19:
7539       if (fixP->fx_done || !seg->use_rela_p)
7540         {
7541           if (value & 3)
7542             as_bad_where (fixP->fx_file, fixP->fx_line,
7543                           _("conditional branch target not word aligned"));
7544           if (signed_overflow (value, 21))
7545             as_bad_where (fixP->fx_file, fixP->fx_line,
7546                           _("conditional branch out of range"));
7547           insn = get_aarch64_insn (buf);
7548           insn |= encode_cond_branch_ofs_19 (value >> 2);
7549           put_aarch64_insn (buf, insn);
7550         }
7551       break;
7552
7553     case BFD_RELOC_AARCH64_TSTBR14:
7554       if (fixP->fx_done || !seg->use_rela_p)
7555         {
7556           if (value & 3)
7557             as_bad_where (fixP->fx_file, fixP->fx_line,
7558                           _("conditional branch target not word aligned"));
7559           if (signed_overflow (value, 16))
7560             as_bad_where (fixP->fx_file, fixP->fx_line,
7561                           _("conditional branch out of range"));
7562           insn = get_aarch64_insn (buf);
7563           insn |= encode_tst_branch_ofs_14 (value >> 2);
7564           put_aarch64_insn (buf, insn);
7565         }
7566       break;
7567
7568     case BFD_RELOC_AARCH64_CALL26:
7569     case BFD_RELOC_AARCH64_JUMP26:
7570       if (fixP->fx_done || !seg->use_rela_p)
7571         {
7572           if (value & 3)
7573             as_bad_where (fixP->fx_file, fixP->fx_line,
7574                           _("branch target not word aligned"));
7575           if (signed_overflow (value, 28))
7576             as_bad_where (fixP->fx_file, fixP->fx_line,
7577                           _("branch out of range"));
7578           insn = get_aarch64_insn (buf);
7579           insn |= encode_branch_ofs_26 (value >> 2);
7580           put_aarch64_insn (buf, insn);
7581         }
7582       break;
7583
7584     case BFD_RELOC_AARCH64_MOVW_G0:
7585     case BFD_RELOC_AARCH64_MOVW_G0_NC:
7586     case BFD_RELOC_AARCH64_MOVW_G0_S:
7587     case BFD_RELOC_AARCH64_MOVW_GOTOFF_G0_NC:
7588       scale = 0;
7589       goto movw_common;
7590     case BFD_RELOC_AARCH64_MOVW_G1:
7591     case BFD_RELOC_AARCH64_MOVW_G1_NC:
7592     case BFD_RELOC_AARCH64_MOVW_G1_S:
7593     case BFD_RELOC_AARCH64_MOVW_GOTOFF_G1:
7594       scale = 16;
7595       goto movw_common;
7596     case BFD_RELOC_AARCH64_TLSDESC_OFF_G0_NC:
7597       scale = 0;
7598       S_SET_THREAD_LOCAL (fixP->fx_addsy);
7599       /* Should always be exported to object file, see
7600          aarch64_force_relocation().  */
7601       gas_assert (!fixP->fx_done);
7602       gas_assert (seg->use_rela_p);
7603       goto movw_common;
7604     case BFD_RELOC_AARCH64_TLSDESC_OFF_G1:
7605       scale = 16;
7606       S_SET_THREAD_LOCAL (fixP->fx_addsy);
7607       /* Should always be exported to object file, see
7608          aarch64_force_relocation().  */
7609       gas_assert (!fixP->fx_done);
7610       gas_assert (seg->use_rela_p);
7611       goto movw_common;
7612     case BFD_RELOC_AARCH64_MOVW_G2:
7613     case BFD_RELOC_AARCH64_MOVW_G2_NC:
7614     case BFD_RELOC_AARCH64_MOVW_G2_S:
7615       scale = 32;
7616       goto movw_common;
7617     case BFD_RELOC_AARCH64_MOVW_G3:
7618       scale = 48;
7619     movw_common:
7620       if (fixP->fx_done || !seg->use_rela_p)
7621         {
7622           insn = get_aarch64_insn (buf);
7623
7624           if (!fixP->fx_done)
7625             {
7626               /* REL signed addend must fit in 16 bits */
7627               if (signed_overflow (value, 16))
7628                 as_bad_where (fixP->fx_file, fixP->fx_line,
7629                               _("offset out of range"));
7630             }
7631           else
7632             {
7633               /* Check for overflow and scale. */
7634               switch (fixP->fx_r_type)
7635                 {
7636                 case BFD_RELOC_AARCH64_MOVW_G0:
7637                 case BFD_RELOC_AARCH64_MOVW_G1:
7638                 case BFD_RELOC_AARCH64_MOVW_G2:
7639                 case BFD_RELOC_AARCH64_MOVW_G3:
7640                 case BFD_RELOC_AARCH64_MOVW_GOTOFF_G1:
7641                 case BFD_RELOC_AARCH64_TLSDESC_OFF_G1:
7642                   if (unsigned_overflow (value, scale + 16))
7643                     as_bad_where (fixP->fx_file, fixP->fx_line,
7644                                   _("unsigned value out of range"));
7645                   break;
7646                 case BFD_RELOC_AARCH64_MOVW_G0_S:
7647                 case BFD_RELOC_AARCH64_MOVW_G1_S:
7648                 case BFD_RELOC_AARCH64_MOVW_G2_S:
7649                   /* NOTE: We can only come here with movz or movn. */
7650                   if (signed_overflow (value, scale + 16))
7651                     as_bad_where (fixP->fx_file, fixP->fx_line,
7652                                   _("signed value out of range"));
7653                   if (value < 0)
7654                     {
7655                       /* Force use of MOVN.  */
7656                       value = ~value;
7657                       insn = reencode_movzn_to_movn (insn);
7658                     }
7659                   else
7660                     {
7661                       /* Force use of MOVZ.  */
7662                       insn = reencode_movzn_to_movz (insn);
7663                     }
7664                   break;
7665                 default:
7666                   /* Unchecked relocations.  */
7667                   break;
7668                 }
7669               value >>= scale;
7670             }
7671
7672           /* Insert value into MOVN/MOVZ/MOVK instruction. */
7673           insn |= encode_movw_imm (value & 0xffff);
7674
7675           put_aarch64_insn (buf, insn);
7676         }
7677       break;
7678
7679     case BFD_RELOC_AARCH64_TLSIE_LD_GOTTPREL_LO12_NC:
7680       fixP->fx_r_type = (ilp32_p
7681                          ? BFD_RELOC_AARCH64_TLSIE_LD32_GOTTPREL_LO12_NC
7682                          : BFD_RELOC_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC);
7683       S_SET_THREAD_LOCAL (fixP->fx_addsy);
7684       /* Should always be exported to object file, see
7685          aarch64_force_relocation().  */
7686       gas_assert (!fixP->fx_done);
7687       gas_assert (seg->use_rela_p);
7688       break;
7689
7690     case BFD_RELOC_AARCH64_TLSDESC_LD_LO12_NC:
7691       fixP->fx_r_type = (ilp32_p
7692                          ? BFD_RELOC_AARCH64_TLSDESC_LD32_LO12_NC
7693                          : BFD_RELOC_AARCH64_TLSDESC_LD64_LO12);
7694       S_SET_THREAD_LOCAL (fixP->fx_addsy);
7695       /* Should always be exported to object file, see
7696          aarch64_force_relocation().  */
7697       gas_assert (!fixP->fx_done);
7698       gas_assert (seg->use_rela_p);
7699       break;
7700
7701     case BFD_RELOC_AARCH64_TLSDESC_ADD_LO12:
7702     case BFD_RELOC_AARCH64_TLSDESC_ADR_PAGE21:
7703     case BFD_RELOC_AARCH64_TLSDESC_ADR_PREL21:
7704     case BFD_RELOC_AARCH64_TLSDESC_LD32_LO12_NC:
7705     case BFD_RELOC_AARCH64_TLSDESC_LD64_LO12:
7706     case BFD_RELOC_AARCH64_TLSDESC_LD_PREL19:
7707     case BFD_RELOC_AARCH64_TLSGD_ADD_LO12_NC:
7708     case BFD_RELOC_AARCH64_TLSGD_ADR_PAGE21:
7709     case BFD_RELOC_AARCH64_TLSGD_ADR_PREL21:
7710     case BFD_RELOC_AARCH64_TLSGD_MOVW_G0_NC:
7711     case BFD_RELOC_AARCH64_TLSGD_MOVW_G1:
7712     case BFD_RELOC_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
7713     case BFD_RELOC_AARCH64_TLSIE_LD32_GOTTPREL_LO12_NC:
7714     case BFD_RELOC_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
7715     case BFD_RELOC_AARCH64_TLSIE_LD_GOTTPREL_PREL19:
7716     case BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC:
7717     case BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G1:
7718     case BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_HI12:
7719     case BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_LO12:
7720     case BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_LO12_NC:
7721     case BFD_RELOC_AARCH64_TLSLD_ADD_LO12_NC:
7722     case BFD_RELOC_AARCH64_TLSLD_ADR_PAGE21:
7723     case BFD_RELOC_AARCH64_TLSLD_ADR_PREL21:
7724     case BFD_RELOC_AARCH64_TLSLD_LDST16_DTPREL_LO12:
7725     case BFD_RELOC_AARCH64_TLSLD_LDST16_DTPREL_LO12_NC:
7726     case BFD_RELOC_AARCH64_TLSLD_LDST32_DTPREL_LO12:
7727     case BFD_RELOC_AARCH64_TLSLD_LDST32_DTPREL_LO12_NC:
7728     case BFD_RELOC_AARCH64_TLSLD_LDST64_DTPREL_LO12:
7729     case BFD_RELOC_AARCH64_TLSLD_LDST64_DTPREL_LO12_NC:
7730     case BFD_RELOC_AARCH64_TLSLD_LDST8_DTPREL_LO12:
7731     case BFD_RELOC_AARCH64_TLSLD_LDST8_DTPREL_LO12_NC:
7732     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0:
7733     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0_NC:
7734     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1:
7735     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1_NC:
7736     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G2:
7737     case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_HI12:
7738     case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12:
7739     case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
7740     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0:
7741     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0_NC:
7742     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1:
7743     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1_NC:
7744     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G2:
7745       S_SET_THREAD_LOCAL (fixP->fx_addsy);
7746       /* Should always be exported to object file, see
7747          aarch64_force_relocation().  */
7748       gas_assert (!fixP->fx_done);
7749       gas_assert (seg->use_rela_p);
7750       break;
7751
7752     case BFD_RELOC_AARCH64_LD_GOT_LO12_NC:
7753       /* Should always be exported to object file, see
7754          aarch64_force_relocation().  */
7755       fixP->fx_r_type = (ilp32_p
7756                          ? BFD_RELOC_AARCH64_LD32_GOT_LO12_NC
7757                          : BFD_RELOC_AARCH64_LD64_GOT_LO12_NC);
7758       gas_assert (!fixP->fx_done);
7759       gas_assert (seg->use_rela_p);
7760       break;
7761
7762     case BFD_RELOC_AARCH64_ADD_LO12:
7763     case BFD_RELOC_AARCH64_ADR_GOT_PAGE:
7764     case BFD_RELOC_AARCH64_ADR_HI21_NC_PCREL:
7765     case BFD_RELOC_AARCH64_ADR_HI21_PCREL:
7766     case BFD_RELOC_AARCH64_GOT_LD_PREL19:
7767     case BFD_RELOC_AARCH64_LD32_GOT_LO12_NC:
7768     case BFD_RELOC_AARCH64_LD32_GOTPAGE_LO14:
7769     case BFD_RELOC_AARCH64_LD64_GOTOFF_LO15:
7770     case BFD_RELOC_AARCH64_LD64_GOTPAGE_LO15:
7771     case BFD_RELOC_AARCH64_LD64_GOT_LO12_NC:
7772     case BFD_RELOC_AARCH64_LDST128_LO12:
7773     case BFD_RELOC_AARCH64_LDST16_LO12:
7774     case BFD_RELOC_AARCH64_LDST32_LO12:
7775     case BFD_RELOC_AARCH64_LDST64_LO12:
7776     case BFD_RELOC_AARCH64_LDST8_LO12:
7777       /* Should always be exported to object file, see
7778          aarch64_force_relocation().  */
7779       gas_assert (!fixP->fx_done);
7780       gas_assert (seg->use_rela_p);
7781       break;
7782
7783     case BFD_RELOC_AARCH64_TLSDESC_ADD:
7784     case BFD_RELOC_AARCH64_TLSDESC_CALL:
7785     case BFD_RELOC_AARCH64_TLSDESC_LDR:
7786       break;
7787
7788     case BFD_RELOC_UNUSED:
7789       /* An error will already have been reported.  */
7790       break;
7791
7792     default:
7793       as_bad_where (fixP->fx_file, fixP->fx_line,
7794                     _("unexpected %s fixup"),
7795                     bfd_get_reloc_code_name (fixP->fx_r_type));
7796       break;
7797     }
7798
7799 apply_fix_return:
7800   /* Free the allocated the struct aarch64_inst.
7801      N.B. currently there are very limited number of fix-up types actually use
7802      this field, so the impact on the performance should be minimal .  */
7803   if (fixP->tc_fix_data.inst != NULL)
7804     free (fixP->tc_fix_data.inst);
7805
7806   return;
7807 }
7808
7809 /* Translate internal representation of relocation info to BFD target
7810    format.  */
7811
7812 arelent *
7813 tc_gen_reloc (asection * section, fixS * fixp)
7814 {
7815   arelent *reloc;
7816   bfd_reloc_code_real_type code;
7817
7818   reloc = XNEW (arelent);
7819
7820   reloc->sym_ptr_ptr = XNEW (asymbol *);
7821   *reloc->sym_ptr_ptr = symbol_get_bfdsym (fixp->fx_addsy);
7822   reloc->address = fixp->fx_frag->fr_address + fixp->fx_where;
7823
7824   if (fixp->fx_pcrel)
7825     {
7826       if (section->use_rela_p)
7827         fixp->fx_offset -= md_pcrel_from_section (fixp, section);
7828       else
7829         fixp->fx_offset = reloc->address;
7830     }
7831   reloc->addend = fixp->fx_offset;
7832
7833   code = fixp->fx_r_type;
7834   switch (code)
7835     {
7836     case BFD_RELOC_16:
7837       if (fixp->fx_pcrel)
7838         code = BFD_RELOC_16_PCREL;
7839       break;
7840
7841     case BFD_RELOC_32:
7842       if (fixp->fx_pcrel)
7843         code = BFD_RELOC_32_PCREL;
7844       break;
7845
7846     case BFD_RELOC_64:
7847       if (fixp->fx_pcrel)
7848         code = BFD_RELOC_64_PCREL;
7849       break;
7850
7851     default:
7852       break;
7853     }
7854
7855   reloc->howto = bfd_reloc_type_lookup (stdoutput, code);
7856   if (reloc->howto == NULL)
7857     {
7858       as_bad_where (fixp->fx_file, fixp->fx_line,
7859                     _
7860                     ("cannot represent %s relocation in this object file format"),
7861                     bfd_get_reloc_code_name (code));
7862       return NULL;
7863     }
7864
7865   return reloc;
7866 }
7867
7868 /* This fix_new is called by cons via TC_CONS_FIX_NEW.  */
7869
7870 void
7871 cons_fix_new_aarch64 (fragS * frag, int where, int size, expressionS * exp)
7872 {
7873   bfd_reloc_code_real_type type;
7874   int pcrel = 0;
7875
7876   /* Pick a reloc.
7877      FIXME: @@ Should look at CPU word size.  */
7878   switch (size)
7879     {
7880     case 1:
7881       type = BFD_RELOC_8;
7882       break;
7883     case 2:
7884       type = BFD_RELOC_16;
7885       break;
7886     case 4:
7887       type = BFD_RELOC_32;
7888       break;
7889     case 8:
7890       type = BFD_RELOC_64;
7891       break;
7892     default:
7893       as_bad (_("cannot do %u-byte relocation"), size);
7894       type = BFD_RELOC_UNUSED;
7895       break;
7896     }
7897
7898   fix_new_exp (frag, where, (int) size, exp, pcrel, type);
7899 }
7900
7901 int
7902 aarch64_force_relocation (struct fix *fixp)
7903 {
7904   switch (fixp->fx_r_type)
7905     {
7906     case BFD_RELOC_AARCH64_GAS_INTERNAL_FIXUP:
7907       /* Perform these "immediate" internal relocations
7908          even if the symbol is extern or weak.  */
7909       return 0;
7910
7911     case BFD_RELOC_AARCH64_LD_GOT_LO12_NC:
7912     case BFD_RELOC_AARCH64_TLSDESC_LD_LO12_NC:
7913     case BFD_RELOC_AARCH64_TLSIE_LD_GOTTPREL_LO12_NC:
7914       /* Pseudo relocs that need to be fixed up according to
7915          ilp32_p.  */
7916       return 0;
7917
7918     case BFD_RELOC_AARCH64_ADD_LO12:
7919     case BFD_RELOC_AARCH64_ADR_GOT_PAGE:
7920     case BFD_RELOC_AARCH64_ADR_HI21_NC_PCREL:
7921     case BFD_RELOC_AARCH64_ADR_HI21_PCREL:
7922     case BFD_RELOC_AARCH64_GOT_LD_PREL19:
7923     case BFD_RELOC_AARCH64_LD32_GOT_LO12_NC:
7924     case BFD_RELOC_AARCH64_LD32_GOTPAGE_LO14:
7925     case BFD_RELOC_AARCH64_LD64_GOTOFF_LO15:
7926     case BFD_RELOC_AARCH64_LD64_GOTPAGE_LO15:
7927     case BFD_RELOC_AARCH64_LD64_GOT_LO12_NC:
7928     case BFD_RELOC_AARCH64_LDST128_LO12:
7929     case BFD_RELOC_AARCH64_LDST16_LO12:
7930     case BFD_RELOC_AARCH64_LDST32_LO12:
7931     case BFD_RELOC_AARCH64_LDST64_LO12:
7932     case BFD_RELOC_AARCH64_LDST8_LO12:
7933     case BFD_RELOC_AARCH64_TLSDESC_ADD_LO12:
7934     case BFD_RELOC_AARCH64_TLSDESC_ADR_PAGE21:
7935     case BFD_RELOC_AARCH64_TLSDESC_ADR_PREL21:
7936     case BFD_RELOC_AARCH64_TLSDESC_LD32_LO12_NC:
7937     case BFD_RELOC_AARCH64_TLSDESC_LD64_LO12:
7938     case BFD_RELOC_AARCH64_TLSDESC_LD_PREL19:
7939     case BFD_RELOC_AARCH64_TLSDESC_OFF_G0_NC:
7940     case BFD_RELOC_AARCH64_TLSDESC_OFF_G1:
7941     case BFD_RELOC_AARCH64_TLSGD_ADD_LO12_NC:
7942     case BFD_RELOC_AARCH64_TLSGD_ADR_PAGE21:
7943     case BFD_RELOC_AARCH64_TLSGD_ADR_PREL21:
7944     case BFD_RELOC_AARCH64_TLSGD_MOVW_G0_NC:
7945     case BFD_RELOC_AARCH64_TLSGD_MOVW_G1:
7946     case BFD_RELOC_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21:
7947     case BFD_RELOC_AARCH64_TLSIE_LD32_GOTTPREL_LO12_NC:
7948     case BFD_RELOC_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC:
7949     case BFD_RELOC_AARCH64_TLSIE_LD_GOTTPREL_PREL19:
7950     case BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC:
7951     case BFD_RELOC_AARCH64_TLSIE_MOVW_GOTTPREL_G1:
7952    case BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_HI12:
7953     case BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_LO12:
7954     case BFD_RELOC_AARCH64_TLSLD_ADD_DTPREL_LO12_NC:
7955     case BFD_RELOC_AARCH64_TLSLD_ADD_LO12_NC:
7956     case BFD_RELOC_AARCH64_TLSLD_ADR_PAGE21:
7957     case BFD_RELOC_AARCH64_TLSLD_ADR_PREL21:
7958     case BFD_RELOC_AARCH64_TLSLD_LDST16_DTPREL_LO12:
7959     case BFD_RELOC_AARCH64_TLSLD_LDST16_DTPREL_LO12_NC:
7960     case BFD_RELOC_AARCH64_TLSLD_LDST32_DTPREL_LO12:
7961     case BFD_RELOC_AARCH64_TLSLD_LDST32_DTPREL_LO12_NC:
7962     case BFD_RELOC_AARCH64_TLSLD_LDST64_DTPREL_LO12:
7963     case BFD_RELOC_AARCH64_TLSLD_LDST64_DTPREL_LO12_NC:
7964     case BFD_RELOC_AARCH64_TLSLD_LDST8_DTPREL_LO12:
7965     case BFD_RELOC_AARCH64_TLSLD_LDST8_DTPREL_LO12_NC:
7966     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0:
7967     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G0_NC:
7968     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1:
7969     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G1_NC:
7970     case BFD_RELOC_AARCH64_TLSLD_MOVW_DTPREL_G2:
7971     case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_HI12:
7972     case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12:
7973     case BFD_RELOC_AARCH64_TLSLE_ADD_TPREL_LO12_NC:
7974     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0:
7975     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G0_NC:
7976     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1:
7977     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G1_NC:
7978     case BFD_RELOC_AARCH64_TLSLE_MOVW_TPREL_G2:
7979       /* Always leave these relocations for the linker.  */
7980       return 1;
7981
7982     default:
7983       break;
7984     }
7985
7986   return generic_force_reloc (fixp);
7987 }
7988
7989 #ifdef OBJ_ELF
7990
7991 /* Implement md_after_parse_args.  This is the earliest time we need to decide
7992    ABI.  If no -mabi specified, the ABI will be decided by target triplet.  */
7993
7994 void
7995 aarch64_after_parse_args (void)
7996 {
7997   if (aarch64_abi != AARCH64_ABI_NONE)
7998     return;
7999
8000   /* DEFAULT_ARCH will have ":32" extension if it's configured for ILP32.  */
8001   if (strlen (default_arch) > 7 && strcmp (default_arch + 7, ":32") == 0)
8002     aarch64_abi = AARCH64_ABI_ILP32;
8003   else
8004     aarch64_abi = AARCH64_ABI_LP64;
8005 }
8006
8007 const char *
8008 elf64_aarch64_target_format (void)
8009 {
8010   if (strcmp (TARGET_OS, "cloudabi") == 0)
8011     {
8012       /* FIXME: What to do for ilp32_p ?  */
8013       return target_big_endian ? "elf64-bigaarch64-cloudabi" : "elf64-littleaarch64-cloudabi";
8014     }
8015   if (target_big_endian)
8016     return ilp32_p ? "elf32-bigaarch64" : "elf64-bigaarch64";
8017   else
8018     return ilp32_p ? "elf32-littleaarch64" : "elf64-littleaarch64";
8019 }
8020
8021 void
8022 aarch64elf_frob_symbol (symbolS * symp, int *puntp)
8023 {
8024   elf_frob_symbol (symp, puntp);
8025 }
8026 #endif
8027
8028 /* MD interface: Finalization.  */
8029
8030 /* A good place to do this, although this was probably not intended
8031    for this kind of use.  We need to dump the literal pool before
8032    references are made to a null symbol pointer.  */
8033
8034 void
8035 aarch64_cleanup (void)
8036 {
8037   literal_pool *pool;
8038
8039   for (pool = list_of_pools; pool; pool = pool->next)
8040     {
8041       /* Put it at the end of the relevant section.  */
8042       subseg_set (pool->section, pool->sub_section);
8043       s_ltorg (0);
8044     }
8045 }
8046
8047 #ifdef OBJ_ELF
8048 /* Remove any excess mapping symbols generated for alignment frags in
8049    SEC.  We may have created a mapping symbol before a zero byte
8050    alignment; remove it if there's a mapping symbol after the
8051    alignment.  */
8052 static void
8053 check_mapping_symbols (bfd * abfd ATTRIBUTE_UNUSED, asection * sec,
8054                        void *dummy ATTRIBUTE_UNUSED)
8055 {
8056   segment_info_type *seginfo = seg_info (sec);
8057   fragS *fragp;
8058
8059   if (seginfo == NULL || seginfo->frchainP == NULL)
8060     return;
8061
8062   for (fragp = seginfo->frchainP->frch_root;
8063        fragp != NULL; fragp = fragp->fr_next)
8064     {
8065       symbolS *sym = fragp->tc_frag_data.last_map;
8066       fragS *next = fragp->fr_next;
8067
8068       /* Variable-sized frags have been converted to fixed size by
8069          this point.  But if this was variable-sized to start with,
8070          there will be a fixed-size frag after it.  So don't handle
8071          next == NULL.  */
8072       if (sym == NULL || next == NULL)
8073         continue;
8074
8075       if (S_GET_VALUE (sym) < next->fr_address)
8076         /* Not at the end of this frag.  */
8077         continue;
8078       know (S_GET_VALUE (sym) == next->fr_address);
8079
8080       do
8081         {
8082           if (next->tc_frag_data.first_map != NULL)
8083             {
8084               /* Next frag starts with a mapping symbol.  Discard this
8085                  one.  */
8086               symbol_remove (sym, &symbol_rootP, &symbol_lastP);
8087               break;
8088             }
8089
8090           if (next->fr_next == NULL)
8091             {
8092               /* This mapping symbol is at the end of the section.  Discard
8093                  it.  */
8094               know (next->fr_fix == 0 && next->fr_var == 0);
8095               symbol_remove (sym, &symbol_rootP, &symbol_lastP);
8096               break;
8097             }
8098
8099           /* As long as we have empty frags without any mapping symbols,
8100              keep looking.  */
8101           /* If the next frag is non-empty and does not start with a
8102              mapping symbol, then this mapping symbol is required.  */
8103           if (next->fr_address != next->fr_next->fr_address)
8104             break;
8105
8106           next = next->fr_next;
8107         }
8108       while (next != NULL);
8109     }
8110 }
8111 #endif
8112
8113 /* Adjust the symbol table.  */
8114
8115 void
8116 aarch64_adjust_symtab (void)
8117 {
8118 #ifdef OBJ_ELF
8119   /* Remove any overlapping mapping symbols generated by alignment frags.  */
8120   bfd_map_over_sections (stdoutput, check_mapping_symbols, (char *) 0);
8121   /* Now do generic ELF adjustments.  */
8122   elf_adjust_symtab ();
8123 #endif
8124 }
8125
8126 static void
8127 checked_hash_insert (struct hash_control *table, const char *key, void *value)
8128 {
8129   const char *hash_err;
8130
8131   hash_err = hash_insert (table, key, value);
8132   if (hash_err)
8133     printf ("Internal Error:  Can't hash %s\n", key);
8134 }
8135
8136 static void
8137 fill_instruction_hash_table (void)
8138 {
8139   aarch64_opcode *opcode = aarch64_opcode_table;
8140
8141   while (opcode->name != NULL)
8142     {
8143       templates *templ, *new_templ;
8144       templ = hash_find (aarch64_ops_hsh, opcode->name);
8145
8146       new_templ = XNEW (templates);
8147       new_templ->opcode = opcode;
8148       new_templ->next = NULL;
8149
8150       if (!templ)
8151         checked_hash_insert (aarch64_ops_hsh, opcode->name, (void *) new_templ);
8152       else
8153         {
8154           new_templ->next = templ->next;
8155           templ->next = new_templ;
8156         }
8157       ++opcode;
8158     }
8159 }
8160
8161 static inline void
8162 convert_to_upper (char *dst, const char *src, size_t num)
8163 {
8164   unsigned int i;
8165   for (i = 0; i < num && *src != '\0'; ++i, ++dst, ++src)
8166     *dst = TOUPPER (*src);
8167   *dst = '\0';
8168 }
8169
8170 /* Assume STR point to a lower-case string, allocate, convert and return
8171    the corresponding upper-case string.  */
8172 static inline const char*
8173 get_upper_str (const char *str)
8174 {
8175   char *ret;
8176   size_t len = strlen (str);
8177   ret = XNEWVEC (char, len + 1);
8178   convert_to_upper (ret, str, len);
8179   return ret;
8180 }
8181
8182 /* MD interface: Initialization.  */
8183
8184 void
8185 md_begin (void)
8186 {
8187   unsigned mach;
8188   unsigned int i;
8189
8190   if ((aarch64_ops_hsh = hash_new ()) == NULL
8191       || (aarch64_cond_hsh = hash_new ()) == NULL
8192       || (aarch64_shift_hsh = hash_new ()) == NULL
8193       || (aarch64_sys_regs_hsh = hash_new ()) == NULL
8194       || (aarch64_pstatefield_hsh = hash_new ()) == NULL
8195       || (aarch64_sys_regs_ic_hsh = hash_new ()) == NULL
8196       || (aarch64_sys_regs_dc_hsh = hash_new ()) == NULL
8197       || (aarch64_sys_regs_at_hsh = hash_new ()) == NULL
8198       || (aarch64_sys_regs_tlbi_hsh = hash_new ()) == NULL
8199       || (aarch64_reg_hsh = hash_new ()) == NULL
8200       || (aarch64_barrier_opt_hsh = hash_new ()) == NULL
8201       || (aarch64_nzcv_hsh = hash_new ()) == NULL
8202       || (aarch64_pldop_hsh = hash_new ()) == NULL
8203       || (aarch64_hint_opt_hsh = hash_new ()) == NULL)
8204     as_fatal (_("virtual memory exhausted"));
8205
8206   fill_instruction_hash_table ();
8207
8208   for (i = 0; aarch64_sys_regs[i].name != NULL; ++i)
8209     checked_hash_insert (aarch64_sys_regs_hsh, aarch64_sys_regs[i].name,
8210                          (void *) (aarch64_sys_regs + i));
8211
8212   for (i = 0; aarch64_pstatefields[i].name != NULL; ++i)
8213     checked_hash_insert (aarch64_pstatefield_hsh,
8214                          aarch64_pstatefields[i].name,
8215                          (void *) (aarch64_pstatefields + i));
8216
8217   for (i = 0; aarch64_sys_regs_ic[i].name != NULL; i++)
8218     checked_hash_insert (aarch64_sys_regs_ic_hsh,
8219                          aarch64_sys_regs_ic[i].name,
8220                          (void *) (aarch64_sys_regs_ic + i));
8221
8222   for (i = 0; aarch64_sys_regs_dc[i].name != NULL; i++)
8223     checked_hash_insert (aarch64_sys_regs_dc_hsh,
8224                          aarch64_sys_regs_dc[i].name,
8225                          (void *) (aarch64_sys_regs_dc + i));
8226
8227   for (i = 0; aarch64_sys_regs_at[i].name != NULL; i++)
8228     checked_hash_insert (aarch64_sys_regs_at_hsh,
8229                          aarch64_sys_regs_at[i].name,
8230                          (void *) (aarch64_sys_regs_at + i));
8231
8232   for (i = 0; aarch64_sys_regs_tlbi[i].name != NULL; i++)
8233     checked_hash_insert (aarch64_sys_regs_tlbi_hsh,
8234                          aarch64_sys_regs_tlbi[i].name,
8235                          (void *) (aarch64_sys_regs_tlbi + i));
8236
8237   for (i = 0; i < ARRAY_SIZE (reg_names); i++)
8238     checked_hash_insert (aarch64_reg_hsh, reg_names[i].name,
8239                          (void *) (reg_names + i));
8240
8241   for (i = 0; i < ARRAY_SIZE (nzcv_names); i++)
8242     checked_hash_insert (aarch64_nzcv_hsh, nzcv_names[i].template,
8243                          (void *) (nzcv_names + i));
8244
8245   for (i = 0; aarch64_operand_modifiers[i].name != NULL; i++)
8246     {
8247       const char *name = aarch64_operand_modifiers[i].name;
8248       checked_hash_insert (aarch64_shift_hsh, name,
8249                            (void *) (aarch64_operand_modifiers + i));
8250       /* Also hash the name in the upper case.  */
8251       checked_hash_insert (aarch64_shift_hsh, get_upper_str (name),
8252                            (void *) (aarch64_operand_modifiers + i));
8253     }
8254
8255   for (i = 0; i < ARRAY_SIZE (aarch64_conds); i++)
8256     {
8257       unsigned int j;
8258       /* A condition code may have alias(es), e.g. "cc", "lo" and "ul" are
8259          the same condition code.  */
8260       for (j = 0; j < ARRAY_SIZE (aarch64_conds[i].names); ++j)
8261         {
8262           const char *name = aarch64_conds[i].names[j];
8263           if (name == NULL)
8264             break;
8265           checked_hash_insert (aarch64_cond_hsh, name,
8266                                (void *) (aarch64_conds + i));
8267           /* Also hash the name in the upper case.  */
8268           checked_hash_insert (aarch64_cond_hsh, get_upper_str (name),
8269                                (void *) (aarch64_conds + i));
8270         }
8271     }
8272
8273   for (i = 0; i < ARRAY_SIZE (aarch64_barrier_options); i++)
8274     {
8275       const char *name = aarch64_barrier_options[i].name;
8276       /* Skip xx00 - the unallocated values of option.  */
8277       if ((i & 0x3) == 0)
8278         continue;
8279       checked_hash_insert (aarch64_barrier_opt_hsh, name,
8280                            (void *) (aarch64_barrier_options + i));
8281       /* Also hash the name in the upper case.  */
8282       checked_hash_insert (aarch64_barrier_opt_hsh, get_upper_str (name),
8283                            (void *) (aarch64_barrier_options + i));
8284     }
8285
8286   for (i = 0; i < ARRAY_SIZE (aarch64_prfops); i++)
8287     {
8288       const char* name = aarch64_prfops[i].name;
8289       /* Skip the unallocated hint encodings.  */
8290       if (name == NULL)
8291         continue;
8292       checked_hash_insert (aarch64_pldop_hsh, name,
8293                            (void *) (aarch64_prfops + i));
8294       /* Also hash the name in the upper case.  */
8295       checked_hash_insert (aarch64_pldop_hsh, get_upper_str (name),
8296                            (void *) (aarch64_prfops + i));
8297     }
8298
8299   for (i = 0; aarch64_hint_options[i].name != NULL; i++)
8300     {
8301       const char* name = aarch64_hint_options[i].name;
8302
8303       checked_hash_insert (aarch64_hint_opt_hsh, name,
8304                            (void *) (aarch64_hint_options + i));
8305       /* Also hash the name in the upper case.  */
8306       checked_hash_insert (aarch64_pldop_hsh, get_upper_str (name),
8307                            (void *) (aarch64_hint_options + i));
8308     }
8309
8310   /* Set the cpu variant based on the command-line options.  */
8311   if (!mcpu_cpu_opt)
8312     mcpu_cpu_opt = march_cpu_opt;
8313
8314   if (!mcpu_cpu_opt)
8315     mcpu_cpu_opt = &cpu_default;
8316
8317   cpu_variant = *mcpu_cpu_opt;
8318
8319   /* Record the CPU type.  */
8320   mach = ilp32_p ? bfd_mach_aarch64_ilp32 : bfd_mach_aarch64;
8321
8322   bfd_set_arch_mach (stdoutput, TARGET_ARCH, mach);
8323 }
8324
8325 /* Command line processing.  */
8326
8327 const char *md_shortopts = "m:";
8328
8329 #ifdef AARCH64_BI_ENDIAN
8330 #define OPTION_EB (OPTION_MD_BASE + 0)
8331 #define OPTION_EL (OPTION_MD_BASE + 1)
8332 #else
8333 #if TARGET_BYTES_BIG_ENDIAN
8334 #define OPTION_EB (OPTION_MD_BASE + 0)
8335 #else
8336 #define OPTION_EL (OPTION_MD_BASE + 1)
8337 #endif
8338 #endif
8339
8340 struct option md_longopts[] = {
8341 #ifdef OPTION_EB
8342   {"EB", no_argument, NULL, OPTION_EB},
8343 #endif
8344 #ifdef OPTION_EL
8345   {"EL", no_argument, NULL, OPTION_EL},
8346 #endif
8347   {NULL, no_argument, NULL, 0}
8348 };
8349
8350 size_t md_longopts_size = sizeof (md_longopts);
8351
8352 struct aarch64_option_table
8353 {
8354   const char *option;                   /* Option name to match.  */
8355   const char *help;                     /* Help information.  */
8356   int *var;                     /* Variable to change.  */
8357   int value;                    /* What to change it to.  */
8358   char *deprecated;             /* If non-null, print this message.  */
8359 };
8360
8361 static struct aarch64_option_table aarch64_opts[] = {
8362   {"mbig-endian", N_("assemble for big-endian"), &target_big_endian, 1, NULL},
8363   {"mlittle-endian", N_("assemble for little-endian"), &target_big_endian, 0,
8364    NULL},
8365 #ifdef DEBUG_AARCH64
8366   {"mdebug-dump", N_("temporary switch for dumping"), &debug_dump, 1, NULL},
8367 #endif /* DEBUG_AARCH64 */
8368   {"mverbose-error", N_("output verbose error messages"), &verbose_error_p, 1,
8369    NULL},
8370   {"mno-verbose-error", N_("do not output verbose error messages"),
8371    &verbose_error_p, 0, NULL},
8372   {NULL, NULL, NULL, 0, NULL}
8373 };
8374
8375 struct aarch64_cpu_option_table
8376 {
8377   const char *name;
8378   const aarch64_feature_set value;
8379   /* The canonical name of the CPU, or NULL to use NAME converted to upper
8380      case.  */
8381   const char *canonical_name;
8382 };
8383
8384 /* This list should, at a minimum, contain all the cpu names
8385    recognized by GCC.  */
8386 static const struct aarch64_cpu_option_table aarch64_cpus[] = {
8387   {"all", AARCH64_ANY, NULL},
8388   {"cortex-a35", AARCH64_FEATURE (AARCH64_ARCH_V8,
8389                                   AARCH64_FEATURE_CRC), "Cortex-A35"},
8390   {"cortex-a53", AARCH64_FEATURE (AARCH64_ARCH_V8,
8391                                   AARCH64_FEATURE_CRC), "Cortex-A53"},
8392   {"cortex-a57", AARCH64_FEATURE (AARCH64_ARCH_V8,
8393                                   AARCH64_FEATURE_CRC), "Cortex-A57"},
8394   {"cortex-a72", AARCH64_FEATURE (AARCH64_ARCH_V8,
8395                                   AARCH64_FEATURE_CRC), "Cortex-A72"},
8396   {"cortex-a73", AARCH64_FEATURE (AARCH64_ARCH_V8,
8397                                   AARCH64_FEATURE_CRC), "Cortex-A73"},
8398   {"exynos-m1", AARCH64_FEATURE (AARCH64_ARCH_V8,
8399                                  AARCH64_FEATURE_CRC | AARCH64_FEATURE_CRYPTO),
8400                                 "Samsung Exynos M1"},
8401   {"falkor", AARCH64_FEATURE (AARCH64_ARCH_V8,
8402                               AARCH64_FEATURE_CRC | AARCH64_FEATURE_CRYPTO),
8403    "Qualcomm Falkor"},
8404   {"qdf24xx", AARCH64_FEATURE (AARCH64_ARCH_V8,
8405                                AARCH64_FEATURE_CRC | AARCH64_FEATURE_CRYPTO),
8406    "Qualcomm QDF24XX"},
8407   {"thunderx", AARCH64_FEATURE (AARCH64_ARCH_V8,
8408                                 AARCH64_FEATURE_CRC | AARCH64_FEATURE_CRYPTO),
8409    "Cavium ThunderX"},
8410   {"vulcan", AARCH64_FEATURE (AARCH64_ARCH_V8_1,
8411                               AARCH64_FEATURE_CRYPTO),
8412   "Broadcom Vulcan"},
8413   /* The 'xgene-1' name is an older name for 'xgene1', which was used
8414      in earlier releases and is superseded by 'xgene1' in all
8415      tools.  */
8416   {"xgene-1", AARCH64_ARCH_V8, "APM X-Gene 1"},
8417   {"xgene1", AARCH64_ARCH_V8, "APM X-Gene 1"},
8418   {"xgene2", AARCH64_FEATURE (AARCH64_ARCH_V8,
8419                               AARCH64_FEATURE_CRC), "APM X-Gene 2"},
8420   {"generic", AARCH64_ARCH_V8, NULL},
8421
8422   {NULL, AARCH64_ARCH_NONE, NULL}
8423 };
8424
8425 struct aarch64_arch_option_table
8426 {
8427   const char *name;
8428   const aarch64_feature_set value;
8429 };
8430
8431 /* This list should, at a minimum, contain all the architecture names
8432    recognized by GCC.  */
8433 static const struct aarch64_arch_option_table aarch64_archs[] = {
8434   {"all", AARCH64_ANY},
8435   {"armv8-a", AARCH64_ARCH_V8},
8436   {"armv8.1-a", AARCH64_ARCH_V8_1},
8437   {"armv8.2-a", AARCH64_ARCH_V8_2},
8438   {"armv8.3-a", AARCH64_ARCH_V8_3},
8439   {NULL, AARCH64_ARCH_NONE}
8440 };
8441
8442 /* ISA extensions.  */
8443 struct aarch64_option_cpu_value_table
8444 {
8445   const char *name;
8446   const aarch64_feature_set value;
8447   const aarch64_feature_set require; /* Feature dependencies.  */
8448 };
8449
8450 static const struct aarch64_option_cpu_value_table aarch64_features[] = {
8451   {"crc",               AARCH64_FEATURE (AARCH64_FEATURE_CRC, 0),
8452                         AARCH64_ARCH_NONE},
8453   {"crypto",            AARCH64_FEATURE (AARCH64_FEATURE_CRYPTO, 0),
8454                         AARCH64_FEATURE (AARCH64_FEATURE_SIMD, 0)},
8455   {"fp",                AARCH64_FEATURE (AARCH64_FEATURE_FP, 0),
8456                         AARCH64_ARCH_NONE},
8457   {"lse",               AARCH64_FEATURE (AARCH64_FEATURE_LSE, 0),
8458                         AARCH64_ARCH_NONE},
8459   {"simd",              AARCH64_FEATURE (AARCH64_FEATURE_SIMD, 0),
8460                         AARCH64_FEATURE (AARCH64_FEATURE_FP, 0)},
8461   {"pan",               AARCH64_FEATURE (AARCH64_FEATURE_PAN, 0),
8462                         AARCH64_ARCH_NONE},
8463   {"lor",               AARCH64_FEATURE (AARCH64_FEATURE_LOR, 0),
8464                         AARCH64_ARCH_NONE},
8465   {"ras",               AARCH64_FEATURE (AARCH64_FEATURE_RAS, 0),
8466                         AARCH64_ARCH_NONE},
8467   {"rdma",              AARCH64_FEATURE (AARCH64_FEATURE_RDMA, 0),
8468                         AARCH64_FEATURE (AARCH64_FEATURE_SIMD, 0)},
8469   {"fp16",              AARCH64_FEATURE (AARCH64_FEATURE_F16, 0),
8470                         AARCH64_FEATURE (AARCH64_FEATURE_FP, 0)},
8471   {"profile",           AARCH64_FEATURE (AARCH64_FEATURE_PROFILE, 0),
8472                         AARCH64_ARCH_NONE},
8473   {"sve",               AARCH64_FEATURE (AARCH64_FEATURE_SVE, 0),
8474                         AARCH64_FEATURE (AARCH64_FEATURE_F16
8475                                          | AARCH64_FEATURE_SIMD
8476                                          | AARCH64_FEATURE_COMPNUM, 0)},
8477   {"compnum",           AARCH64_FEATURE (AARCH64_FEATURE_COMPNUM, 0),
8478                         AARCH64_FEATURE (AARCH64_FEATURE_F16
8479                                          | AARCH64_FEATURE_SIMD, 0)},
8480   {"rcpc",              AARCH64_FEATURE (AARCH64_FEATURE_RCPC, 0),
8481                         AARCH64_ARCH_NONE},
8482   {NULL,                AARCH64_ARCH_NONE, AARCH64_ARCH_NONE},
8483 };
8484
8485 struct aarch64_long_option_table
8486 {
8487   const char *option;                   /* Substring to match.  */
8488   const char *help;                     /* Help information.  */
8489   int (*func) (const char *subopt);     /* Function to decode sub-option.  */
8490   char *deprecated;             /* If non-null, print this message.  */
8491 };
8492
8493 /* Transitive closure of features depending on set.  */
8494 static aarch64_feature_set
8495 aarch64_feature_disable_set (aarch64_feature_set set)
8496 {
8497   const struct aarch64_option_cpu_value_table *opt;
8498   aarch64_feature_set prev = 0;
8499
8500   while (prev != set) {
8501     prev = set;
8502     for (opt = aarch64_features; opt->name != NULL; opt++)
8503       if (AARCH64_CPU_HAS_ANY_FEATURES (opt->require, set))
8504         AARCH64_MERGE_FEATURE_SETS (set, set, opt->value);
8505   }
8506   return set;
8507 }
8508
8509 /* Transitive closure of dependencies of set.  */
8510 static aarch64_feature_set
8511 aarch64_feature_enable_set (aarch64_feature_set set)
8512 {
8513   const struct aarch64_option_cpu_value_table *opt;
8514   aarch64_feature_set prev = 0;
8515
8516   while (prev != set) {
8517     prev = set;
8518     for (opt = aarch64_features; opt->name != NULL; opt++)
8519       if (AARCH64_CPU_HAS_FEATURE (set, opt->value))
8520         AARCH64_MERGE_FEATURE_SETS (set, set, opt->require);
8521   }
8522   return set;
8523 }
8524
8525 static int
8526 aarch64_parse_features (const char *str, const aarch64_feature_set **opt_p,
8527                         bfd_boolean ext_only)
8528 {
8529   /* We insist on extensions being added before being removed.  We achieve
8530      this by using the ADDING_VALUE variable to indicate whether we are
8531      adding an extension (1) or removing it (0) and only allowing it to
8532      change in the order -1 -> 1 -> 0.  */
8533   int adding_value = -1;
8534   aarch64_feature_set *ext_set = XNEW (aarch64_feature_set);
8535
8536   /* Copy the feature set, so that we can modify it.  */
8537   *ext_set = **opt_p;
8538   *opt_p = ext_set;
8539
8540   while (str != NULL && *str != 0)
8541     {
8542       const struct aarch64_option_cpu_value_table *opt;
8543       const char *ext = NULL;
8544       int optlen;
8545
8546       if (!ext_only)
8547         {
8548           if (*str != '+')
8549             {
8550               as_bad (_("invalid architectural extension"));
8551               return 0;
8552             }
8553
8554           ext = strchr (++str, '+');
8555         }
8556
8557       if (ext != NULL)
8558         optlen = ext - str;
8559       else
8560         optlen = strlen (str);
8561
8562       if (optlen >= 2 && strncmp (str, "no", 2) == 0)
8563         {
8564           if (adding_value != 0)
8565             adding_value = 0;
8566           optlen -= 2;
8567           str += 2;
8568         }
8569       else if (optlen > 0)
8570         {
8571           if (adding_value == -1)
8572             adding_value = 1;
8573           else if (adding_value != 1)
8574             {
8575               as_bad (_("must specify extensions to add before specifying "
8576                         "those to remove"));
8577               return FALSE;
8578             }
8579         }
8580
8581       if (optlen == 0)
8582         {
8583           as_bad (_("missing architectural extension"));
8584           return 0;
8585         }
8586
8587       gas_assert (adding_value != -1);
8588
8589       for (opt = aarch64_features; opt->name != NULL; opt++)
8590         if (strncmp (opt->name, str, optlen) == 0)
8591           {
8592             aarch64_feature_set set;
8593
8594             /* Add or remove the extension.  */
8595             if (adding_value)
8596               {
8597                 set = aarch64_feature_enable_set (opt->value);
8598                 AARCH64_MERGE_FEATURE_SETS (*ext_set, *ext_set, set);
8599               }
8600             else
8601               {
8602                 set = aarch64_feature_disable_set (opt->value);
8603                 AARCH64_CLEAR_FEATURE (*ext_set, *ext_set, set);
8604               }
8605             break;
8606           }
8607
8608       if (opt->name == NULL)
8609         {
8610           as_bad (_("unknown architectural extension `%s'"), str);
8611           return 0;
8612         }
8613
8614       str = ext;
8615     };
8616
8617   return 1;
8618 }
8619
8620 static int
8621 aarch64_parse_cpu (const char *str)
8622 {
8623   const struct aarch64_cpu_option_table *opt;
8624   const char *ext = strchr (str, '+');
8625   size_t optlen;
8626
8627   if (ext != NULL)
8628     optlen = ext - str;
8629   else
8630     optlen = strlen (str);
8631
8632   if (optlen == 0)
8633     {
8634       as_bad (_("missing cpu name `%s'"), str);
8635       return 0;
8636     }
8637
8638   for (opt = aarch64_cpus; opt->name != NULL; opt++)
8639     if (strlen (opt->name) == optlen && strncmp (str, opt->name, optlen) == 0)
8640       {
8641         mcpu_cpu_opt = &opt->value;
8642         if (ext != NULL)
8643           return aarch64_parse_features (ext, &mcpu_cpu_opt, FALSE);
8644
8645         return 1;
8646       }
8647
8648   as_bad (_("unknown cpu `%s'"), str);
8649   return 0;
8650 }
8651
8652 static int
8653 aarch64_parse_arch (const char *str)
8654 {
8655   const struct aarch64_arch_option_table *opt;
8656   const char *ext = strchr (str, '+');
8657   size_t optlen;
8658
8659   if (ext != NULL)
8660     optlen = ext - str;
8661   else
8662     optlen = strlen (str);
8663
8664   if (optlen == 0)
8665     {
8666       as_bad (_("missing architecture name `%s'"), str);
8667       return 0;
8668     }
8669
8670   for (opt = aarch64_archs; opt->name != NULL; opt++)
8671     if (strlen (opt->name) == optlen && strncmp (str, opt->name, optlen) == 0)
8672       {
8673         march_cpu_opt = &opt->value;
8674         if (ext != NULL)
8675           return aarch64_parse_features (ext, &march_cpu_opt, FALSE);
8676
8677         return 1;
8678       }
8679
8680   as_bad (_("unknown architecture `%s'\n"), str);
8681   return 0;
8682 }
8683
8684 /* ABIs.  */
8685 struct aarch64_option_abi_value_table
8686 {
8687   const char *name;
8688   enum aarch64_abi_type value;
8689 };
8690
8691 static const struct aarch64_option_abi_value_table aarch64_abis[] = {
8692   {"ilp32",             AARCH64_ABI_ILP32},
8693   {"lp64",              AARCH64_ABI_LP64},
8694 };
8695
8696 static int
8697 aarch64_parse_abi (const char *str)
8698 {
8699   unsigned int i;
8700
8701   if (str[0] == '\0')
8702     {
8703       as_bad (_("missing abi name `%s'"), str);
8704       return 0;
8705     }
8706
8707   for (i = 0; i < ARRAY_SIZE (aarch64_abis); i++)
8708     if (strcmp (str, aarch64_abis[i].name) == 0)
8709       {
8710         aarch64_abi = aarch64_abis[i].value;
8711         return 1;
8712       }
8713
8714   as_bad (_("unknown abi `%s'\n"), str);
8715   return 0;
8716 }
8717
8718 static struct aarch64_long_option_table aarch64_long_opts[] = {
8719 #ifdef OBJ_ELF
8720   {"mabi=", N_("<abi name>\t  specify for ABI <abi name>"),
8721    aarch64_parse_abi, NULL},
8722 #endif /* OBJ_ELF */
8723   {"mcpu=", N_("<cpu name>\t  assemble for CPU <cpu name>"),
8724    aarch64_parse_cpu, NULL},
8725   {"march=", N_("<arch name>\t  assemble for architecture <arch name>"),
8726    aarch64_parse_arch, NULL},
8727   {NULL, NULL, 0, NULL}
8728 };
8729
8730 int
8731 md_parse_option (int c, const char *arg)
8732 {
8733   struct aarch64_option_table *opt;
8734   struct aarch64_long_option_table *lopt;
8735
8736   switch (c)
8737     {
8738 #ifdef OPTION_EB
8739     case OPTION_EB:
8740       target_big_endian = 1;
8741       break;
8742 #endif
8743
8744 #ifdef OPTION_EL
8745     case OPTION_EL:
8746       target_big_endian = 0;
8747       break;
8748 #endif
8749
8750     case 'a':
8751       /* Listing option.  Just ignore these, we don't support additional
8752          ones.  */
8753       return 0;
8754
8755     default:
8756       for (opt = aarch64_opts; opt->option != NULL; opt++)
8757         {
8758           if (c == opt->option[0]
8759               && ((arg == NULL && opt->option[1] == 0)
8760                   || streq (arg, opt->option + 1)))
8761             {
8762               /* If the option is deprecated, tell the user.  */
8763               if (opt->deprecated != NULL)
8764                 as_tsktsk (_("option `-%c%s' is deprecated: %s"), c,
8765                            arg ? arg : "", _(opt->deprecated));
8766
8767               if (opt->var != NULL)
8768                 *opt->var = opt->value;
8769
8770               return 1;
8771             }
8772         }
8773
8774       for (lopt = aarch64_long_opts; lopt->option != NULL; lopt++)
8775         {
8776           /* These options are expected to have an argument.  */
8777           if (c == lopt->option[0]
8778               && arg != NULL
8779               && strncmp (arg, lopt->option + 1,
8780                           strlen (lopt->option + 1)) == 0)
8781             {
8782               /* If the option is deprecated, tell the user.  */
8783               if (lopt->deprecated != NULL)
8784                 as_tsktsk (_("option `-%c%s' is deprecated: %s"), c, arg,
8785                            _(lopt->deprecated));
8786
8787               /* Call the sup-option parser.  */
8788               return lopt->func (arg + strlen (lopt->option) - 1);
8789             }
8790         }
8791
8792       return 0;
8793     }
8794
8795   return 1;
8796 }
8797
8798 void
8799 md_show_usage (FILE * fp)
8800 {
8801   struct aarch64_option_table *opt;
8802   struct aarch64_long_option_table *lopt;
8803
8804   fprintf (fp, _(" AArch64-specific assembler options:\n"));
8805
8806   for (opt = aarch64_opts; opt->option != NULL; opt++)
8807     if (opt->help != NULL)
8808       fprintf (fp, "  -%-23s%s\n", opt->option, _(opt->help));
8809
8810   for (lopt = aarch64_long_opts; lopt->option != NULL; lopt++)
8811     if (lopt->help != NULL)
8812       fprintf (fp, "  -%s%s\n", lopt->option, _(lopt->help));
8813
8814 #ifdef OPTION_EB
8815   fprintf (fp, _("\
8816   -EB                     assemble code for a big-endian cpu\n"));
8817 #endif
8818
8819 #ifdef OPTION_EL
8820   fprintf (fp, _("\
8821   -EL                     assemble code for a little-endian cpu\n"));
8822 #endif
8823 }
8824
8825 /* Parse a .cpu directive.  */
8826
8827 static void
8828 s_aarch64_cpu (int ignored ATTRIBUTE_UNUSED)
8829 {
8830   const struct aarch64_cpu_option_table *opt;
8831   char saved_char;
8832   char *name;
8833   char *ext;
8834   size_t optlen;
8835
8836   name = input_line_pointer;
8837   while (*input_line_pointer && !ISSPACE (*input_line_pointer))
8838     input_line_pointer++;
8839   saved_char = *input_line_pointer;
8840   *input_line_pointer = 0;
8841
8842   ext = strchr (name, '+');
8843
8844   if (ext != NULL)
8845     optlen = ext - name;
8846   else
8847     optlen = strlen (name);
8848
8849   /* Skip the first "all" entry.  */
8850   for (opt = aarch64_cpus + 1; opt->name != NULL; opt++)
8851     if (strlen (opt->name) == optlen
8852         && strncmp (name, opt->name, optlen) == 0)
8853       {
8854         mcpu_cpu_opt = &opt->value;
8855         if (ext != NULL)
8856           if (!aarch64_parse_features (ext, &mcpu_cpu_opt, FALSE))
8857             return;
8858
8859         cpu_variant = *mcpu_cpu_opt;
8860
8861         *input_line_pointer = saved_char;
8862         demand_empty_rest_of_line ();
8863         return;
8864       }
8865   as_bad (_("unknown cpu `%s'"), name);
8866   *input_line_pointer = saved_char;
8867   ignore_rest_of_line ();
8868 }
8869
8870
8871 /* Parse a .arch directive.  */
8872
8873 static void
8874 s_aarch64_arch (int ignored ATTRIBUTE_UNUSED)
8875 {
8876   const struct aarch64_arch_option_table *opt;
8877   char saved_char;
8878   char *name;
8879   char *ext;
8880   size_t optlen;
8881
8882   name = input_line_pointer;
8883   while (*input_line_pointer && !ISSPACE (*input_line_pointer))
8884     input_line_pointer++;
8885   saved_char = *input_line_pointer;
8886   *input_line_pointer = 0;
8887
8888   ext = strchr (name, '+');
8889
8890   if (ext != NULL)
8891     optlen = ext - name;
8892   else
8893     optlen = strlen (name);
8894
8895   /* Skip the first "all" entry.  */
8896   for (opt = aarch64_archs + 1; opt->name != NULL; opt++)
8897     if (strlen (opt->name) == optlen
8898         && strncmp (name, opt->name, optlen) == 0)
8899       {
8900         mcpu_cpu_opt = &opt->value;
8901         if (ext != NULL)
8902           if (!aarch64_parse_features (ext, &mcpu_cpu_opt, FALSE))
8903             return;
8904
8905         cpu_variant = *mcpu_cpu_opt;
8906
8907         *input_line_pointer = saved_char;
8908         demand_empty_rest_of_line ();
8909         return;
8910       }
8911
8912   as_bad (_("unknown architecture `%s'\n"), name);
8913   *input_line_pointer = saved_char;
8914   ignore_rest_of_line ();
8915 }
8916
8917 /* Parse a .arch_extension directive.  */
8918
8919 static void
8920 s_aarch64_arch_extension (int ignored ATTRIBUTE_UNUSED)
8921 {
8922   char saved_char;
8923   char *ext = input_line_pointer;;
8924
8925   while (*input_line_pointer && !ISSPACE (*input_line_pointer))
8926     input_line_pointer++;
8927   saved_char = *input_line_pointer;
8928   *input_line_pointer = 0;
8929
8930   if (!aarch64_parse_features (ext, &mcpu_cpu_opt, TRUE))
8931     return;
8932
8933   cpu_variant = *mcpu_cpu_opt;
8934
8935   *input_line_pointer = saved_char;
8936   demand_empty_rest_of_line ();
8937 }
8938
8939 /* Copy symbol information.  */
8940
8941 void
8942 aarch64_copy_symbol_attributes (symbolS * dest, symbolS * src)
8943 {
8944   AARCH64_GET_FLAG (dest) = AARCH64_GET_FLAG (src);
8945 }
This page took 0.526008 seconds and 4 git commands to generate.