1 //===- ARMAsmParser.cpp - Parse ARM assembly to MCInst instructions -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "ARMFeatures.h"
11 #include "Utils/ARMBaseInfo.h"
12 #include "MCTargetDesc/ARMAddressingModes.h"
13 #include "MCTargetDesc/ARMBaseInfo.h"
14 #include "MCTargetDesc/ARMMCExpr.h"
15 #include "MCTargetDesc/ARMMCTargetDesc.h"
16 #include "llvm/ADT/APFloat.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/MC/MCInst.h"
29 #include "llvm/MC/MCInstrDesc.h"
30 #include "llvm/MC/MCInstrInfo.h"
31 #include "llvm/MC/MCObjectFileInfo.h"
32 #include "llvm/MC/MCParser/MCAsmLexer.h"
33 #include "llvm/MC/MCParser/MCAsmParser.h"
34 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
35 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
36 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
37 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
38 #include "llvm/MC/MCRegisterInfo.h"
39 #include "llvm/MC/MCSection.h"
40 #include "llvm/MC/MCStreamer.h"
41 #include "llvm/MC/MCSubtargetInfo.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/MC/SubtargetFeature.h"
44 #include "llvm/Support/ARMBuildAttributes.h"
45 #include "llvm/Support/ARMEHABI.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Compiler.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/SMLoc.h"
52 #include "llvm/Support/TargetParser.h"
53 #include "llvm/Support/TargetRegistry.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include <algorithm>
56 #include <cassert>
57 #include <cstddef>
58 #include <cstdint>
59 #include <iterator>
60 #include <limits>
61 #include <memory>
62 #include <string>
63 #include <utility>
64 #include <vector>
65 
66 using namespace llvm;
67 
68 namespace {
69 
70 enum class ImplicitItModeTy { Always, Never, ARMOnly, ThumbOnly };
71 
72 static cl::opt<ImplicitItModeTy> ImplicitItMode(
73     "arm-implicit-it", cl::init(ImplicitItModeTy::ARMOnly),
74     cl::desc("Allow conditional instructions outdside of an IT block"),
75     cl::values(clEnumValN(ImplicitItModeTy::Always, "always",
76                           "Accept in both ISAs, emit implicit ITs in Thumb"),
77                clEnumValN(ImplicitItModeTy::Never, "never",
78                           "Warn in ARM, reject in Thumb"),
79                clEnumValN(ImplicitItModeTy::ARMOnly, "arm",
80                           "Accept in ARM, reject in Thumb"),
81                clEnumValN(ImplicitItModeTy::ThumbOnly, "thumb",
82                           "Warn in ARM, emit implicit ITs in Thumb")));
83 
84 static cl::opt<bool> AddBuildAttributes("arm-add-build-attributes",
85                                         cl::init(false));
86 
87 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
88 
89 class UnwindContext {
90   using Locs = SmallVector<SMLoc, 4>;
91 
92   MCAsmParser &Parser;
93   Locs FnStartLocs;
94   Locs CantUnwindLocs;
95   Locs PersonalityLocs;
96   Locs PersonalityIndexLocs;
97   Locs HandlerDataLocs;
98   int FPReg;
99 
100 public:
101   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
102 
103   bool hasFnStart() const { return !FnStartLocs.empty(); }
104   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
105   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
106 
107   bool hasPersonality() const {
108     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
109   }
110 
111   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
112   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
113   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
114   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
115   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
116 
117   void saveFPReg(int Reg) { FPReg = Reg; }
118   int getFPReg() const { return FPReg; }
119 
120   void emitFnStartLocNotes() const {
121     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
122          FI != FE; ++FI)
123       Parser.Note(*FI, ".fnstart was specified here");
124   }
125 
126   void emitCantUnwindLocNotes() const {
127     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
128                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
129       Parser.Note(*UI, ".cantunwind was specified here");
130   }
131 
132   void emitHandlerDataLocNotes() const {
133     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
134                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
135       Parser.Note(*HI, ".handlerdata was specified here");
136   }
137 
138   void emitPersonalityLocNotes() const {
139     for (Locs::const_iterator PI = PersonalityLocs.begin(),
140                               PE = PersonalityLocs.end(),
141                               PII = PersonalityIndexLocs.begin(),
142                               PIE = PersonalityIndexLocs.end();
143          PI != PE || PII != PIE;) {
144       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
145         Parser.Note(*PI++, ".personality was specified here");
146       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
147         Parser.Note(*PII++, ".personalityindex was specified here");
148       else
149         llvm_unreachable(".personality and .personalityindex cannot be "
150                          "at the same location");
151     }
152   }
153 
154   void reset() {
155     FnStartLocs = Locs();
156     CantUnwindLocs = Locs();
157     PersonalityLocs = Locs();
158     HandlerDataLocs = Locs();
159     PersonalityIndexLocs = Locs();
160     FPReg = ARM::SP;
161   }
162 };
163 
164 class ARMAsmParser : public MCTargetAsmParser {
165   const MCInstrInfo &MII;
166   const MCRegisterInfo *MRI;
167   UnwindContext UC;
168 
169   ARMTargetStreamer &getTargetStreamer() {
170     assert(getParser().getStreamer().getTargetStreamer() &&
171            "do not have a target streamer");
172     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
173     return static_cast<ARMTargetStreamer &>(TS);
174   }
175 
176   // Map of register aliases registers via the .req directive.
177   StringMap<unsigned> RegisterReqs;
178 
179   bool NextSymbolIsThumb;
180 
181   bool useImplicitITThumb() const {
182     return ImplicitItMode == ImplicitItModeTy::Always ||
183            ImplicitItMode == ImplicitItModeTy::ThumbOnly;
184   }
185 
186   bool useImplicitITARM() const {
187     return ImplicitItMode == ImplicitItModeTy::Always ||
188            ImplicitItMode == ImplicitItModeTy::ARMOnly;
189   }
190 
191   struct {
192     ARMCC::CondCodes Cond;    // Condition for IT block.
193     unsigned Mask:4;          // Condition mask for instructions.
194                               // Starting at first 1 (from lsb).
195                               //   '1'  condition as indicated in IT.
196                               //   '0'  inverse of condition (else).
197                               // Count of instructions in IT block is
198                               // 4 - trailingzeroes(mask)
199                               // Note that this does not have the same encoding
200                               // as in the IT instruction, which also depends
201                               // on the low bit of the condition code.
202 
203     unsigned CurPosition;     // Current position in parsing of IT
204                               // block. In range [0,4], with 0 being the IT
205                               // instruction itself. Initialized according to
206                               // count of instructions in block.  ~0U if no
207                               // active IT block.
208 
209     bool IsExplicit;          // true  - The IT instruction was present in the
210                               //         input, we should not modify it.
211                               // false - The IT instruction was added
212                               //         implicitly, we can extend it if that
213                               //         would be legal.
214   } ITState;
215 
216   SmallVector<MCInst, 4> PendingConditionalInsts;
217 
218   void flushPendingInstructions(MCStreamer &Out) override {
219     if (!inImplicitITBlock()) {
220       assert(PendingConditionalInsts.size() == 0);
221       return;
222     }
223 
224     // Emit the IT instruction
225     unsigned Mask = getITMaskEncoding();
226     MCInst ITInst;
227     ITInst.setOpcode(ARM::t2IT);
228     ITInst.addOperand(MCOperand::createImm(ITState.Cond));
229     ITInst.addOperand(MCOperand::createImm(Mask));
230     Out.EmitInstruction(ITInst, getSTI());
231 
232     // Emit the conditonal instructions
233     assert(PendingConditionalInsts.size() <= 4);
234     for (const MCInst &Inst : PendingConditionalInsts) {
235       Out.EmitInstruction(Inst, getSTI());
236     }
237     PendingConditionalInsts.clear();
238 
239     // Clear the IT state
240     ITState.Mask = 0;
241     ITState.CurPosition = ~0U;
242   }
243 
244   bool inITBlock() { return ITState.CurPosition != ~0U; }
245   bool inExplicitITBlock() { return inITBlock() && ITState.IsExplicit; }
246   bool inImplicitITBlock() { return inITBlock() && !ITState.IsExplicit; }
247 
248   bool lastInITBlock() {
249     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
250   }
251 
252   void forwardITPosition() {
253     if (!inITBlock()) return;
254     // Move to the next instruction in the IT block, if there is one. If not,
255     // mark the block as done, except for implicit IT blocks, which we leave
256     // open until we find an instruction that can't be added to it.
257     unsigned TZ = countTrailingZeros(ITState.Mask);
258     if (++ITState.CurPosition == 5 - TZ && ITState.IsExplicit)
259       ITState.CurPosition = ~0U; // Done with the IT block after this.
260   }
261 
262   // Rewind the state of the current IT block, removing the last slot from it.
263   void rewindImplicitITPosition() {
264     assert(inImplicitITBlock());
265     assert(ITState.CurPosition > 1);
266     ITState.CurPosition--;
267     unsigned TZ = countTrailingZeros(ITState.Mask);
268     unsigned NewMask = 0;
269     NewMask |= ITState.Mask & (0xC << TZ);
270     NewMask |= 0x2 << TZ;
271     ITState.Mask = NewMask;
272   }
273 
274   // Rewind the state of the current IT block, removing the last slot from it.
275   // If we were at the first slot, this closes the IT block.
276   void discardImplicitITBlock() {
277     assert(inImplicitITBlock());
278     assert(ITState.CurPosition == 1);
279     ITState.CurPosition = ~0U;
280   }
281 
282   // Return the low-subreg of a given Q register.
283   unsigned getDRegFromQReg(unsigned QReg) const {
284     return MRI->getSubReg(QReg, ARM::dsub_0);
285   }
286 
287   // Get the encoding of the IT mask, as it will appear in an IT instruction.
288   unsigned getITMaskEncoding() {
289     assert(inITBlock());
290     unsigned Mask = ITState.Mask;
291     unsigned TZ = countTrailingZeros(Mask);
292     if ((ITState.Cond & 1) == 0) {
293       assert(Mask && TZ <= 3 && "illegal IT mask value!");
294       Mask ^= (0xE << TZ) & 0xF;
295     }
296     return Mask;
297   }
298 
299   // Get the condition code corresponding to the current IT block slot.
300   ARMCC::CondCodes currentITCond() {
301     unsigned MaskBit;
302     if (ITState.CurPosition == 1)
303       MaskBit = 1;
304     else
305       MaskBit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
306 
307     return MaskBit ? ITState.Cond : ARMCC::getOppositeCondition(ITState.Cond);
308   }
309 
310   // Invert the condition of the current IT block slot without changing any
311   // other slots in the same block.
312   void invertCurrentITCondition() {
313     if (ITState.CurPosition == 1) {
314       ITState.Cond = ARMCC::getOppositeCondition(ITState.Cond);
315     } else {
316       ITState.Mask ^= 1 << (5 - ITState.CurPosition);
317     }
318   }
319 
320   // Returns true if the current IT block is full (all 4 slots used).
321   bool isITBlockFull() {
322     return inITBlock() && (ITState.Mask & 1);
323   }
324 
325   // Extend the current implicit IT block to have one more slot with the given
326   // condition code.
327   void extendImplicitITBlock(ARMCC::CondCodes Cond) {
328     assert(inImplicitITBlock());
329     assert(!isITBlockFull());
330     assert(Cond == ITState.Cond ||
331            Cond == ARMCC::getOppositeCondition(ITState.Cond));
332     unsigned TZ = countTrailingZeros(ITState.Mask);
333     unsigned NewMask = 0;
334     // Keep any existing condition bits.
335     NewMask |= ITState.Mask & (0xE << TZ);
336     // Insert the new condition bit.
337     NewMask |= (Cond == ITState.Cond) << TZ;
338     // Move the trailing 1 down one bit.
339     NewMask |= 1 << (TZ - 1);
340     ITState.Mask = NewMask;
341   }
342 
343   // Create a new implicit IT block with a dummy condition code.
344   void startImplicitITBlock() {
345     assert(!inITBlock());
346     ITState.Cond = ARMCC::AL;
347     ITState.Mask = 8;
348     ITState.CurPosition = 1;
349     ITState.IsExplicit = false;
350   }
351 
352   // Create a new explicit IT block with the given condition and mask. The mask
353   // should be in the parsed format, with a 1 implying 't', regardless of the
354   // low bit of the condition.
355   void startExplicitITBlock(ARMCC::CondCodes Cond, unsigned Mask) {
356     assert(!inITBlock());
357     ITState.Cond = Cond;
358     ITState.Mask = Mask;
359     ITState.CurPosition = 0;
360     ITState.IsExplicit = true;
361   }
362 
363   void Note(SMLoc L, const Twine &Msg, SMRange Range = None) {
364     return getParser().Note(L, Msg, Range);
365   }
366 
367   bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) {
368     return getParser().Warning(L, Msg, Range);
369   }
370 
371   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None) {
372     return getParser().Error(L, Msg, Range);
373   }
374 
375   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
376                            unsigned ListNo, bool IsARPop = false);
377   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
378                            unsigned ListNo);
379 
380   int tryParseRegister();
381   bool tryParseRegisterWithWriteBack(OperandVector &);
382   int tryParseShiftRegister(OperandVector &);
383   bool parseRegisterList(OperandVector &);
384   bool parseMemory(OperandVector &);
385   bool parseOperand(OperandVector &, StringRef Mnemonic);
386   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
387   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
388                               unsigned &ShiftAmount);
389   bool parseLiteralValues(unsigned Size, SMLoc L);
390   bool parseDirectiveThumb(SMLoc L);
391   bool parseDirectiveARM(SMLoc L);
392   bool parseDirectiveThumbFunc(SMLoc L);
393   bool parseDirectiveCode(SMLoc L);
394   bool parseDirectiveSyntax(SMLoc L);
395   bool parseDirectiveReq(StringRef Name, SMLoc L);
396   bool parseDirectiveUnreq(SMLoc L);
397   bool parseDirectiveArch(SMLoc L);
398   bool parseDirectiveEabiAttr(SMLoc L);
399   bool parseDirectiveCPU(SMLoc L);
400   bool parseDirectiveFPU(SMLoc L);
401   bool parseDirectiveFnStart(SMLoc L);
402   bool parseDirectiveFnEnd(SMLoc L);
403   bool parseDirectiveCantUnwind(SMLoc L);
404   bool parseDirectivePersonality(SMLoc L);
405   bool parseDirectiveHandlerData(SMLoc L);
406   bool parseDirectiveSetFP(SMLoc L);
407   bool parseDirectivePad(SMLoc L);
408   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
409   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
410   bool parseDirectiveLtorg(SMLoc L);
411   bool parseDirectiveEven(SMLoc L);
412   bool parseDirectivePersonalityIndex(SMLoc L);
413   bool parseDirectiveUnwindRaw(SMLoc L);
414   bool parseDirectiveTLSDescSeq(SMLoc L);
415   bool parseDirectiveMovSP(SMLoc L);
416   bool parseDirectiveObjectArch(SMLoc L);
417   bool parseDirectiveArchExtension(SMLoc L);
418   bool parseDirectiveAlign(SMLoc L);
419   bool parseDirectiveThumbSet(SMLoc L);
420 
421   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
422                           bool &CarrySetting, unsigned &ProcessorIMod,
423                           StringRef &ITMask);
424   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
425                              bool &CanAcceptCarrySet,
426                              bool &CanAcceptPredicationCode);
427 
428   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
429                                      OperandVector &Operands);
430   bool isThumb() const {
431     // FIXME: Can tablegen auto-generate this?
432     return getSTI().getFeatureBits()[ARM::ModeThumb];
433   }
434 
435   bool isThumbOne() const {
436     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
437   }
438 
439   bool isThumbTwo() const {
440     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
441   }
442 
443   bool hasThumb() const {
444     return getSTI().getFeatureBits()[ARM::HasV4TOps];
445   }
446 
447   bool hasThumb2() const {
448     return getSTI().getFeatureBits()[ARM::FeatureThumb2];
449   }
450 
451   bool hasV6Ops() const {
452     return getSTI().getFeatureBits()[ARM::HasV6Ops];
453   }
454 
455   bool hasV6T2Ops() const {
456     return getSTI().getFeatureBits()[ARM::HasV6T2Ops];
457   }
458 
459   bool hasV6MOps() const {
460     return getSTI().getFeatureBits()[ARM::HasV6MOps];
461   }
462 
463   bool hasV7Ops() const {
464     return getSTI().getFeatureBits()[ARM::HasV7Ops];
465   }
466 
467   bool hasV8Ops() const {
468     return getSTI().getFeatureBits()[ARM::HasV8Ops];
469   }
470 
471   bool hasV8MBaseline() const {
472     return getSTI().getFeatureBits()[ARM::HasV8MBaselineOps];
473   }
474 
475   bool hasV8MMainline() const {
476     return getSTI().getFeatureBits()[ARM::HasV8MMainlineOps];
477   }
478 
479   bool has8MSecExt() const {
480     return getSTI().getFeatureBits()[ARM::Feature8MSecExt];
481   }
482 
483   bool hasARM() const {
484     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
485   }
486 
487   bool hasDSP() const {
488     return getSTI().getFeatureBits()[ARM::FeatureDSP];
489   }
490 
491   bool hasD16() const {
492     return getSTI().getFeatureBits()[ARM::FeatureD16];
493   }
494 
495   bool hasV8_1aOps() const {
496     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
497   }
498 
499   bool hasRAS() const {
500     return getSTI().getFeatureBits()[ARM::FeatureRAS];
501   }
502 
503   void SwitchMode() {
504     MCSubtargetInfo &STI = copySTI();
505     uint64_t FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
506     setAvailableFeatures(FB);
507   }
508 
509   void FixModeAfterArchChange(bool WasThumb, SMLoc Loc);
510 
511   bool isMClass() const {
512     return getSTI().getFeatureBits()[ARM::FeatureMClass];
513   }
514 
515   /// @name Auto-generated Match Functions
516   /// {
517 
518 #define GET_ASSEMBLER_HEADER
519 #include "ARMGenAsmMatcher.inc"
520 
521   /// }
522 
523   OperandMatchResultTy parseITCondCode(OperandVector &);
524   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
525   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
526   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
527   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
528   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
529   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
530   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
531   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
532   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
533                                    int High);
534   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
535     return parsePKHImm(O, "lsl", 0, 31);
536   }
537   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
538     return parsePKHImm(O, "asr", 1, 32);
539   }
540   OperandMatchResultTy parseSetEndImm(OperandVector &);
541   OperandMatchResultTy parseShifterImm(OperandVector &);
542   OperandMatchResultTy parseRotImm(OperandVector &);
543   OperandMatchResultTy parseModImm(OperandVector &);
544   OperandMatchResultTy parseBitfield(OperandVector &);
545   OperandMatchResultTy parsePostIdxReg(OperandVector &);
546   OperandMatchResultTy parseAM3Offset(OperandVector &);
547   OperandMatchResultTy parseFPImm(OperandVector &);
548   OperandMatchResultTy parseVectorList(OperandVector &);
549   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
550                                        SMLoc &EndLoc);
551 
552   // Asm Match Converter Methods
553   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
554   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
555 
556   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
557   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
558   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
559   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
560   bool isITBlockTerminator(MCInst &Inst) const;
561 
562 public:
563   enum ARMMatchResultTy {
564     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
565     Match_RequiresNotITBlock,
566     Match_RequiresV6,
567     Match_RequiresThumb2,
568     Match_RequiresV8,
569     Match_RequiresFlagSetting,
570 #define GET_OPERAND_DIAGNOSTIC_TYPES
571 #include "ARMGenAsmMatcher.inc"
572 
573   };
574 
575   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
576                const MCInstrInfo &MII, const MCTargetOptions &Options)
577     : MCTargetAsmParser(Options, STI), MII(MII), UC(Parser) {
578     MCAsmParserExtension::Initialize(Parser);
579 
580     // Cache the MCRegisterInfo.
581     MRI = getContext().getRegisterInfo();
582 
583     // Initialize the set of available features.
584     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
585 
586     // Add build attributes based on the selected target.
587     if (AddBuildAttributes)
588       getTargetStreamer().emitTargetAttributes(STI);
589 
590     // Not in an ITBlock to start with.
591     ITState.CurPosition = ~0U;
592 
593     NextSymbolIsThumb = false;
594   }
595 
596   // Implementation of the MCTargetAsmParser interface:
597   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
598   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
599                         SMLoc NameLoc, OperandVector &Operands) override;
600   bool ParseDirective(AsmToken DirectiveID) override;
601 
602   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
603                                       unsigned Kind) override;
604   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
605 
606   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
607                                OperandVector &Operands, MCStreamer &Out,
608                                uint64_t &ErrorInfo,
609                                bool MatchingInlineAsm) override;
610   unsigned MatchInstruction(OperandVector &Operands, MCInst &Inst,
611                             uint64_t &ErrorInfo, bool MatchingInlineAsm,
612                             bool &EmitInITBlock, MCStreamer &Out);
613   void onLabelParsed(MCSymbol *Symbol) override;
614 };
615 
616 /// ARMOperand - Instances of this class represent a parsed ARM machine
617 /// operand.
618 class ARMOperand : public MCParsedAsmOperand {
619   enum KindTy {
620     k_CondCode,
621     k_CCOut,
622     k_ITCondMask,
623     k_CoprocNum,
624     k_CoprocReg,
625     k_CoprocOption,
626     k_Immediate,
627     k_MemBarrierOpt,
628     k_InstSyncBarrierOpt,
629     k_Memory,
630     k_PostIndexRegister,
631     k_MSRMask,
632     k_BankedReg,
633     k_ProcIFlags,
634     k_VectorIndex,
635     k_Register,
636     k_RegisterList,
637     k_DPRRegisterList,
638     k_SPRRegisterList,
639     k_VectorList,
640     k_VectorListAllLanes,
641     k_VectorListIndexed,
642     k_ShiftedRegister,
643     k_ShiftedImmediate,
644     k_ShifterImmediate,
645     k_RotateImmediate,
646     k_ModifiedImmediate,
647     k_ConstantPoolImmediate,
648     k_BitfieldDescriptor,
649     k_Token,
650   } Kind;
651 
652   SMLoc StartLoc, EndLoc, AlignmentLoc;
653   SmallVector<unsigned, 8> Registers;
654 
655   struct CCOp {
656     ARMCC::CondCodes Val;
657   };
658 
659   struct CopOp {
660     unsigned Val;
661   };
662 
663   struct CoprocOptionOp {
664     unsigned Val;
665   };
666 
667   struct ITMaskOp {
668     unsigned Mask:4;
669   };
670 
671   struct MBOptOp {
672     ARM_MB::MemBOpt Val;
673   };
674 
675   struct ISBOptOp {
676     ARM_ISB::InstSyncBOpt Val;
677   };
678 
679   struct IFlagsOp {
680     ARM_PROC::IFlags Val;
681   };
682 
683   struct MMaskOp {
684     unsigned Val;
685   };
686 
687   struct BankedRegOp {
688     unsigned Val;
689   };
690 
691   struct TokOp {
692     const char *Data;
693     unsigned Length;
694   };
695 
696   struct RegOp {
697     unsigned RegNum;
698   };
699 
700   // A vector register list is a sequential list of 1 to 4 registers.
701   struct VectorListOp {
702     unsigned RegNum;
703     unsigned Count;
704     unsigned LaneIndex;
705     bool isDoubleSpaced;
706   };
707 
708   struct VectorIndexOp {
709     unsigned Val;
710   };
711 
712   struct ImmOp {
713     const MCExpr *Val;
714   };
715 
716   /// Combined record for all forms of ARM address expressions.
717   struct MemoryOp {
718     unsigned BaseRegNum;
719     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
720     // was specified.
721     const MCConstantExpr *OffsetImm;  // Offset immediate value
722     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
723     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
724     unsigned ShiftImm;        // shift for OffsetReg.
725     unsigned Alignment;       // 0 = no alignment specified
726     // n = alignment in bytes (2, 4, 8, 16, or 32)
727     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
728   };
729 
730   struct PostIdxRegOp {
731     unsigned RegNum;
732     bool isAdd;
733     ARM_AM::ShiftOpc ShiftTy;
734     unsigned ShiftImm;
735   };
736 
737   struct ShifterImmOp {
738     bool isASR;
739     unsigned Imm;
740   };
741 
742   struct RegShiftedRegOp {
743     ARM_AM::ShiftOpc ShiftTy;
744     unsigned SrcReg;
745     unsigned ShiftReg;
746     unsigned ShiftImm;
747   };
748 
749   struct RegShiftedImmOp {
750     ARM_AM::ShiftOpc ShiftTy;
751     unsigned SrcReg;
752     unsigned ShiftImm;
753   };
754 
755   struct RotImmOp {
756     unsigned Imm;
757   };
758 
759   struct ModImmOp {
760     unsigned Bits;
761     unsigned Rot;
762   };
763 
764   struct BitfieldOp {
765     unsigned LSB;
766     unsigned Width;
767   };
768 
769   union {
770     struct CCOp CC;
771     struct CopOp Cop;
772     struct CoprocOptionOp CoprocOption;
773     struct MBOptOp MBOpt;
774     struct ISBOptOp ISBOpt;
775     struct ITMaskOp ITMask;
776     struct IFlagsOp IFlags;
777     struct MMaskOp MMask;
778     struct BankedRegOp BankedReg;
779     struct TokOp Tok;
780     struct RegOp Reg;
781     struct VectorListOp VectorList;
782     struct VectorIndexOp VectorIndex;
783     struct ImmOp Imm;
784     struct MemoryOp Memory;
785     struct PostIdxRegOp PostIdxReg;
786     struct ShifterImmOp ShifterImm;
787     struct RegShiftedRegOp RegShiftedReg;
788     struct RegShiftedImmOp RegShiftedImm;
789     struct RotImmOp RotImm;
790     struct ModImmOp ModImm;
791     struct BitfieldOp Bitfield;
792   };
793 
794 public:
795   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
796 
797   /// getStartLoc - Get the location of the first token of this operand.
798   SMLoc getStartLoc() const override { return StartLoc; }
799 
800   /// getEndLoc - Get the location of the last token of this operand.
801   SMLoc getEndLoc() const override { return EndLoc; }
802 
803   /// getLocRange - Get the range between the first and last token of this
804   /// operand.
805   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
806 
807   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
808   SMLoc getAlignmentLoc() const {
809     assert(Kind == k_Memory && "Invalid access!");
810     return AlignmentLoc;
811   }
812 
813   ARMCC::CondCodes getCondCode() const {
814     assert(Kind == k_CondCode && "Invalid access!");
815     return CC.Val;
816   }
817 
818   unsigned getCoproc() const {
819     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
820     return Cop.Val;
821   }
822 
823   StringRef getToken() const {
824     assert(Kind == k_Token && "Invalid access!");
825     return StringRef(Tok.Data, Tok.Length);
826   }
827 
828   unsigned getReg() const override {
829     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
830     return Reg.RegNum;
831   }
832 
833   const SmallVectorImpl<unsigned> &getRegList() const {
834     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
835             Kind == k_SPRRegisterList) && "Invalid access!");
836     return Registers;
837   }
838 
839   const MCExpr *getImm() const {
840     assert(isImm() && "Invalid access!");
841     return Imm.Val;
842   }
843 
844   const MCExpr *getConstantPoolImm() const {
845     assert(isConstantPoolImm() && "Invalid access!");
846     return Imm.Val;
847   }
848 
849   unsigned getVectorIndex() const {
850     assert(Kind == k_VectorIndex && "Invalid access!");
851     return VectorIndex.Val;
852   }
853 
854   ARM_MB::MemBOpt getMemBarrierOpt() const {
855     assert(Kind == k_MemBarrierOpt && "Invalid access!");
856     return MBOpt.Val;
857   }
858 
859   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
860     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
861     return ISBOpt.Val;
862   }
863 
864   ARM_PROC::IFlags getProcIFlags() const {
865     assert(Kind == k_ProcIFlags && "Invalid access!");
866     return IFlags.Val;
867   }
868 
869   unsigned getMSRMask() const {
870     assert(Kind == k_MSRMask && "Invalid access!");
871     return MMask.Val;
872   }
873 
874   unsigned getBankedReg() const {
875     assert(Kind == k_BankedReg && "Invalid access!");
876     return BankedReg.Val;
877   }
878 
879   bool isCoprocNum() const { return Kind == k_CoprocNum; }
880   bool isCoprocReg() const { return Kind == k_CoprocReg; }
881   bool isCoprocOption() const { return Kind == k_CoprocOption; }
882   bool isCondCode() const { return Kind == k_CondCode; }
883   bool isCCOut() const { return Kind == k_CCOut; }
884   bool isITMask() const { return Kind == k_ITCondMask; }
885   bool isITCondCode() const { return Kind == k_CondCode; }
886   bool isImm() const override {
887     return Kind == k_Immediate;
888   }
889 
890   bool isARMBranchTarget() const {
891     if (!isImm()) return false;
892 
893     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
894       return CE->getValue() % 4 == 0;
895     return true;
896   }
897 
898 
899   bool isThumbBranchTarget() const {
900     if (!isImm()) return false;
901 
902     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
903       return CE->getValue() % 2 == 0;
904     return true;
905   }
906 
907   // checks whether this operand is an unsigned offset which fits is a field
908   // of specified width and scaled by a specific number of bits
909   template<unsigned width, unsigned scale>
910   bool isUnsignedOffset() const {
911     if (!isImm()) return false;
912     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
913     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
914       int64_t Val = CE->getValue();
915       int64_t Align = 1LL << scale;
916       int64_t Max = Align * ((1LL << width) - 1);
917       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
918     }
919     return false;
920   }
921 
922   // checks whether this operand is an signed offset which fits is a field
923   // of specified width and scaled by a specific number of bits
924   template<unsigned width, unsigned scale>
925   bool isSignedOffset() const {
926     if (!isImm()) return false;
927     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
928     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
929       int64_t Val = CE->getValue();
930       int64_t Align = 1LL << scale;
931       int64_t Max = Align * ((1LL << (width-1)) - 1);
932       int64_t Min = -Align * (1LL << (width-1));
933       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
934     }
935     return false;
936   }
937 
938   // checks whether this operand is a memory operand computed as an offset
939   // applied to PC. the offset may have 8 bits of magnitude and is represented
940   // with two bits of shift. textually it may be either [pc, #imm], #imm or
941   // relocable expression...
942   bool isThumbMemPC() const {
943     int64_t Val = 0;
944     if (isImm()) {
945       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
946       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
947       if (!CE) return false;
948       Val = CE->getValue();
949     }
950     else if (isMem()) {
951       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
952       if(Memory.BaseRegNum != ARM::PC) return false;
953       Val = Memory.OffsetImm->getValue();
954     }
955     else return false;
956     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
957   }
958 
959   bool isFPImm() const {
960     if (!isImm()) return false;
961     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
962     if (!CE) return false;
963     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
964     return Val != -1;
965   }
966 
967   template<int64_t N, int64_t M>
968   bool isImmediate() const {
969     if (!isImm()) return false;
970     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
971     if (!CE) return false;
972     int64_t Value = CE->getValue();
973     return Value >= N && Value <= M;
974   }
975 
976   template<int64_t N, int64_t M>
977   bool isImmediateS4() const {
978     if (!isImm()) return false;
979     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
980     if (!CE) return false;
981     int64_t Value = CE->getValue();
982     return ((Value & 3) == 0) && Value >= N && Value <= M;
983   }
984 
985   bool isFBits16() const {
986     return isImmediate<0, 17>();
987   }
988   bool isFBits32() const {
989     return isImmediate<1, 33>();
990   }
991   bool isImm8s4() const {
992     return isImmediateS4<-1020, 1020>();
993   }
994   bool isImm0_1020s4() const {
995     return isImmediateS4<0, 1020>();
996   }
997   bool isImm0_508s4() const {
998     return isImmediateS4<0, 508>();
999   }
1000   bool isImm0_508s4Neg() const {
1001     if (!isImm()) return false;
1002     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1003     if (!CE) return false;
1004     int64_t Value = -CE->getValue();
1005     // explicitly exclude zero. we want that to use the normal 0_508 version.
1006     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
1007   }
1008 
1009   bool isImm0_4095Neg() const {
1010     if (!isImm()) return false;
1011     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1012     if (!CE) return false;
1013     int64_t Value = -CE->getValue();
1014     return Value > 0 && Value < 4096;
1015   }
1016 
1017   bool isImm0_7() const {
1018     return isImmediate<0, 7>();
1019   }
1020 
1021   bool isImm1_16() const {
1022     return isImmediate<1, 16>();
1023   }
1024 
1025   bool isImm1_32() const {
1026     return isImmediate<1, 32>();
1027   }
1028 
1029   bool isImm8_255() const {
1030     return isImmediate<8, 255>();
1031   }
1032 
1033   bool isImm256_65535Expr() const {
1034     if (!isImm()) return false;
1035     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1036     // If it's not a constant expression, it'll generate a fixup and be
1037     // handled later.
1038     if (!CE) return true;
1039     int64_t Value = CE->getValue();
1040     return Value >= 256 && Value < 65536;
1041   }
1042 
1043   bool isImm0_65535Expr() const {
1044     if (!isImm()) return false;
1045     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1046     // If it's not a constant expression, it'll generate a fixup and be
1047     // handled later.
1048     if (!CE) return true;
1049     int64_t Value = CE->getValue();
1050     return Value >= 0 && Value < 65536;
1051   }
1052 
1053   bool isImm24bit() const {
1054     return isImmediate<0, 0xffffff + 1>();
1055   }
1056 
1057   bool isImmThumbSR() const {
1058     return isImmediate<1, 33>();
1059   }
1060 
1061   bool isPKHLSLImm() const {
1062     return isImmediate<0, 32>();
1063   }
1064 
1065   bool isPKHASRImm() const {
1066     return isImmediate<0, 33>();
1067   }
1068 
1069   bool isAdrLabel() const {
1070     // If we have an immediate that's not a constant, treat it as a label
1071     // reference needing a fixup.
1072     if (isImm() && !isa<MCConstantExpr>(getImm()))
1073       return true;
1074 
1075     // If it is a constant, it must fit into a modified immediate encoding.
1076     if (!isImm()) return false;
1077     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1078     if (!CE) return false;
1079     int64_t Value = CE->getValue();
1080     return (ARM_AM::getSOImmVal(Value) != -1 ||
1081             ARM_AM::getSOImmVal(-Value) != -1);
1082   }
1083 
1084   bool isT2SOImm() const {
1085     // If we have an immediate that's not a constant, treat it as an expression
1086     // needing a fixup.
1087     if (isImm() && !isa<MCConstantExpr>(getImm())) {
1088       // We want to avoid matching :upper16: and :lower16: as we want these
1089       // expressions to match in isImm0_65535Expr()
1090       const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(getImm());
1091       return (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
1092                              ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16));
1093     }
1094     if (!isImm()) return false;
1095     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1096     if (!CE) return false;
1097     int64_t Value = CE->getValue();
1098     return ARM_AM::getT2SOImmVal(Value) != -1;
1099   }
1100 
1101   bool isT2SOImmNot() const {
1102     if (!isImm()) return false;
1103     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1104     if (!CE) return false;
1105     int64_t Value = CE->getValue();
1106     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1107       ARM_AM::getT2SOImmVal(~Value) != -1;
1108   }
1109 
1110   bool isT2SOImmNeg() const {
1111     if (!isImm()) return false;
1112     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1113     if (!CE) return false;
1114     int64_t Value = CE->getValue();
1115     // Only use this when not representable as a plain so_imm.
1116     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1117       ARM_AM::getT2SOImmVal(-Value) != -1;
1118   }
1119 
1120   bool isSetEndImm() const {
1121     if (!isImm()) return false;
1122     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1123     if (!CE) return false;
1124     int64_t Value = CE->getValue();
1125     return Value == 1 || Value == 0;
1126   }
1127 
1128   bool isReg() const override { return Kind == k_Register; }
1129   bool isRegList() const { return Kind == k_RegisterList; }
1130   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1131   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1132   bool isToken() const override { return Kind == k_Token; }
1133   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1134   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1135   bool isMem() const override { return Kind == k_Memory; }
1136   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1137   bool isRegShiftedReg() const { return Kind == k_ShiftedRegister; }
1138   bool isRegShiftedImm() const { return Kind == k_ShiftedImmediate; }
1139   bool isRotImm() const { return Kind == k_RotateImmediate; }
1140   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1141 
1142   bool isModImmNot() const {
1143     if (!isImm()) return false;
1144     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1145     if (!CE) return false;
1146     int64_t Value = CE->getValue();
1147     return ARM_AM::getSOImmVal(~Value) != -1;
1148   }
1149 
1150   bool isModImmNeg() const {
1151     if (!isImm()) return false;
1152     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1153     if (!CE) return false;
1154     int64_t Value = CE->getValue();
1155     return ARM_AM::getSOImmVal(Value) == -1 &&
1156       ARM_AM::getSOImmVal(-Value) != -1;
1157   }
1158 
1159   bool isThumbModImmNeg1_7() const {
1160     if (!isImm()) return false;
1161     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1162     if (!CE) return false;
1163     int32_t Value = -(int32_t)CE->getValue();
1164     return 0 < Value && Value < 8;
1165   }
1166 
1167   bool isThumbModImmNeg8_255() const {
1168     if (!isImm()) return false;
1169     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1170     if (!CE) return false;
1171     int32_t Value = -(int32_t)CE->getValue();
1172     return 7 < Value && Value < 256;
1173   }
1174 
1175   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
1176   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1177   bool isPostIdxRegShifted() const { return Kind == k_PostIndexRegister; }
1178   bool isPostIdxReg() const {
1179     return Kind == k_PostIndexRegister && PostIdxReg.ShiftTy ==ARM_AM::no_shift;
1180   }
1181   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1182     if (!isMem())
1183       return false;
1184     // No offset of any kind.
1185     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1186      (alignOK || Memory.Alignment == Alignment);
1187   }
1188   bool isMemPCRelImm12() const {
1189     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1190       return false;
1191     // Base register must be PC.
1192     if (Memory.BaseRegNum != ARM::PC)
1193       return false;
1194     // Immediate offset in range [-4095, 4095].
1195     if (!Memory.OffsetImm) return true;
1196     int64_t Val = Memory.OffsetImm->getValue();
1197     return (Val > -4096 && Val < 4096) ||
1198            (Val == std::numeric_limits<int32_t>::min());
1199   }
1200 
1201   bool isAlignedMemory() const {
1202     return isMemNoOffset(true);
1203   }
1204 
1205   bool isAlignedMemoryNone() const {
1206     return isMemNoOffset(false, 0);
1207   }
1208 
1209   bool isDupAlignedMemoryNone() const {
1210     return isMemNoOffset(false, 0);
1211   }
1212 
1213   bool isAlignedMemory16() const {
1214     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1215       return true;
1216     return isMemNoOffset(false, 0);
1217   }
1218 
1219   bool isDupAlignedMemory16() const {
1220     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1221       return true;
1222     return isMemNoOffset(false, 0);
1223   }
1224 
1225   bool isAlignedMemory32() const {
1226     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1227       return true;
1228     return isMemNoOffset(false, 0);
1229   }
1230 
1231   bool isDupAlignedMemory32() const {
1232     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1233       return true;
1234     return isMemNoOffset(false, 0);
1235   }
1236 
1237   bool isAlignedMemory64() const {
1238     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1239       return true;
1240     return isMemNoOffset(false, 0);
1241   }
1242 
1243   bool isDupAlignedMemory64() const {
1244     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1245       return true;
1246     return isMemNoOffset(false, 0);
1247   }
1248 
1249   bool isAlignedMemory64or128() const {
1250     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1251       return true;
1252     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1253       return true;
1254     return isMemNoOffset(false, 0);
1255   }
1256 
1257   bool isDupAlignedMemory64or128() const {
1258     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1259       return true;
1260     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1261       return true;
1262     return isMemNoOffset(false, 0);
1263   }
1264 
1265   bool isAlignedMemory64or128or256() const {
1266     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1267       return true;
1268     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1269       return true;
1270     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1271       return true;
1272     return isMemNoOffset(false, 0);
1273   }
1274 
1275   bool isAddrMode2() const {
1276     if (!isMem() || Memory.Alignment != 0) return false;
1277     // Check for register offset.
1278     if (Memory.OffsetRegNum) return true;
1279     // Immediate offset in range [-4095, 4095].
1280     if (!Memory.OffsetImm) return true;
1281     int64_t Val = Memory.OffsetImm->getValue();
1282     return Val > -4096 && Val < 4096;
1283   }
1284 
1285   bool isAM2OffsetImm() const {
1286     if (!isImm()) return false;
1287     // Immediate offset in range [-4095, 4095].
1288     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1289     if (!CE) return false;
1290     int64_t Val = CE->getValue();
1291     return (Val == std::numeric_limits<int32_t>::min()) ||
1292            (Val > -4096 && Val < 4096);
1293   }
1294 
1295   bool isAddrMode3() const {
1296     // If we have an immediate that's not a constant, treat it as a label
1297     // reference needing a fixup. If it is a constant, it's something else
1298     // and we reject it.
1299     if (isImm() && !isa<MCConstantExpr>(getImm()))
1300       return true;
1301     if (!isMem() || Memory.Alignment != 0) return false;
1302     // No shifts are legal for AM3.
1303     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1304     // Check for register offset.
1305     if (Memory.OffsetRegNum) return true;
1306     // Immediate offset in range [-255, 255].
1307     if (!Memory.OffsetImm) return true;
1308     int64_t Val = Memory.OffsetImm->getValue();
1309     // The #-0 offset is encoded as std::numeric_limits<int32_t>::min(), and we
1310     // have to check for this too.
1311     return (Val > -256 && Val < 256) ||
1312            Val == std::numeric_limits<int32_t>::min();
1313   }
1314 
1315   bool isAM3Offset() const {
1316     if (Kind != k_Immediate && Kind != k_PostIndexRegister)
1317       return false;
1318     if (Kind == k_PostIndexRegister)
1319       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
1320     // Immediate offset in range [-255, 255].
1321     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1322     if (!CE) return false;
1323     int64_t Val = CE->getValue();
1324     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1325     return (Val > -256 && Val < 256) ||
1326            Val == std::numeric_limits<int32_t>::min();
1327   }
1328 
1329   bool isAddrMode5() const {
1330     // If we have an immediate that's not a constant, treat it as a label
1331     // reference needing a fixup. If it is a constant, it's something else
1332     // and we reject it.
1333     if (isImm() && !isa<MCConstantExpr>(getImm()))
1334       return true;
1335     if (!isMem() || Memory.Alignment != 0) return false;
1336     // Check for register offset.
1337     if (Memory.OffsetRegNum) return false;
1338     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1339     if (!Memory.OffsetImm) return true;
1340     int64_t Val = Memory.OffsetImm->getValue();
1341     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1342       Val == std::numeric_limits<int32_t>::min();
1343   }
1344 
1345   bool isAddrMode5FP16() const {
1346     // If we have an immediate that's not a constant, treat it as a label
1347     // reference needing a fixup. If it is a constant, it's something else
1348     // and we reject it.
1349     if (isImm() && !isa<MCConstantExpr>(getImm()))
1350       return true;
1351     if (!isMem() || Memory.Alignment != 0) return false;
1352     // Check for register offset.
1353     if (Memory.OffsetRegNum) return false;
1354     // Immediate offset in range [-510, 510] and a multiple of 2.
1355     if (!Memory.OffsetImm) return true;
1356     int64_t Val = Memory.OffsetImm->getValue();
1357     return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) ||
1358            Val == std::numeric_limits<int32_t>::min();
1359   }
1360 
1361   bool isMemTBB() const {
1362     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1363         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1364       return false;
1365     return true;
1366   }
1367 
1368   bool isMemTBH() const {
1369     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1370         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1371         Memory.Alignment != 0 )
1372       return false;
1373     return true;
1374   }
1375 
1376   bool isMemRegOffset() const {
1377     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1378       return false;
1379     return true;
1380   }
1381 
1382   bool isT2MemRegOffset() const {
1383     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1384         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1385       return false;
1386     // Only lsl #{0, 1, 2, 3} allowed.
1387     if (Memory.ShiftType == ARM_AM::no_shift)
1388       return true;
1389     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1390       return false;
1391     return true;
1392   }
1393 
1394   bool isMemThumbRR() const {
1395     // Thumb reg+reg addressing is simple. Just two registers, a base and
1396     // an offset. No shifts, negations or any other complicating factors.
1397     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1398         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1399       return false;
1400     return isARMLowRegister(Memory.BaseRegNum) &&
1401       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1402   }
1403 
1404   bool isMemThumbRIs4() const {
1405     if (!isMem() || Memory.OffsetRegNum != 0 ||
1406         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1407       return false;
1408     // Immediate offset, multiple of 4 in range [0, 124].
1409     if (!Memory.OffsetImm) return true;
1410     int64_t Val = Memory.OffsetImm->getValue();
1411     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1412   }
1413 
1414   bool isMemThumbRIs2() const {
1415     if (!isMem() || Memory.OffsetRegNum != 0 ||
1416         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1417       return false;
1418     // Immediate offset, multiple of 4 in range [0, 62].
1419     if (!Memory.OffsetImm) return true;
1420     int64_t Val = Memory.OffsetImm->getValue();
1421     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1422   }
1423 
1424   bool isMemThumbRIs1() const {
1425     if (!isMem() || Memory.OffsetRegNum != 0 ||
1426         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1427       return false;
1428     // Immediate offset in range [0, 31].
1429     if (!Memory.OffsetImm) return true;
1430     int64_t Val = Memory.OffsetImm->getValue();
1431     return Val >= 0 && Val <= 31;
1432   }
1433 
1434   bool isMemThumbSPI() const {
1435     if (!isMem() || Memory.OffsetRegNum != 0 ||
1436         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1437       return false;
1438     // Immediate offset, multiple of 4 in range [0, 1020].
1439     if (!Memory.OffsetImm) return true;
1440     int64_t Val = Memory.OffsetImm->getValue();
1441     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1442   }
1443 
1444   bool isMemImm8s4Offset() const {
1445     // If we have an immediate that's not a constant, treat it as a label
1446     // reference needing a fixup. If it is a constant, it's something else
1447     // and we reject it.
1448     if (isImm() && !isa<MCConstantExpr>(getImm()))
1449       return true;
1450     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1451       return false;
1452     // Immediate offset a multiple of 4 in range [-1020, 1020].
1453     if (!Memory.OffsetImm) return true;
1454     int64_t Val = Memory.OffsetImm->getValue();
1455     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1456     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) ||
1457            Val == std::numeric_limits<int32_t>::min();
1458   }
1459 
1460   bool isMemImm0_1020s4Offset() const {
1461     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1462       return false;
1463     // Immediate offset a multiple of 4 in range [0, 1020].
1464     if (!Memory.OffsetImm) return true;
1465     int64_t Val = Memory.OffsetImm->getValue();
1466     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1467   }
1468 
1469   bool isMemImm8Offset() const {
1470     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1471       return false;
1472     // Base reg of PC isn't allowed for these encodings.
1473     if (Memory.BaseRegNum == ARM::PC) return false;
1474     // Immediate offset in range [-255, 255].
1475     if (!Memory.OffsetImm) return true;
1476     int64_t Val = Memory.OffsetImm->getValue();
1477     return (Val == std::numeric_limits<int32_t>::min()) ||
1478            (Val > -256 && Val < 256);
1479   }
1480 
1481   bool isMemPosImm8Offset() const {
1482     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1483       return false;
1484     // Immediate offset in range [0, 255].
1485     if (!Memory.OffsetImm) return true;
1486     int64_t Val = Memory.OffsetImm->getValue();
1487     return Val >= 0 && Val < 256;
1488   }
1489 
1490   bool isMemNegImm8Offset() const {
1491     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1492       return false;
1493     // Base reg of PC isn't allowed for these encodings.
1494     if (Memory.BaseRegNum == ARM::PC) return false;
1495     // Immediate offset in range [-255, -1].
1496     if (!Memory.OffsetImm) return false;
1497     int64_t Val = Memory.OffsetImm->getValue();
1498     return (Val == std::numeric_limits<int32_t>::min()) ||
1499            (Val > -256 && Val < 0);
1500   }
1501 
1502   bool isMemUImm12Offset() const {
1503     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1504       return false;
1505     // Immediate offset in range [0, 4095].
1506     if (!Memory.OffsetImm) return true;
1507     int64_t Val = Memory.OffsetImm->getValue();
1508     return (Val >= 0 && Val < 4096);
1509   }
1510 
1511   bool isMemImm12Offset() const {
1512     // If we have an immediate that's not a constant, treat it as a label
1513     // reference needing a fixup. If it is a constant, it's something else
1514     // and we reject it.
1515 
1516     if (isImm() && !isa<MCConstantExpr>(getImm()))
1517       return true;
1518 
1519     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1520       return false;
1521     // Immediate offset in range [-4095, 4095].
1522     if (!Memory.OffsetImm) return true;
1523     int64_t Val = Memory.OffsetImm->getValue();
1524     return (Val > -4096 && Val < 4096) ||
1525            (Val == std::numeric_limits<int32_t>::min());
1526   }
1527 
1528   bool isConstPoolAsmImm() const {
1529     // Delay processing of Constant Pool Immediate, this will turn into
1530     // a constant. Match no other operand
1531     return (isConstantPoolImm());
1532   }
1533 
1534   bool isPostIdxImm8() const {
1535     if (!isImm()) return false;
1536     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1537     if (!CE) return false;
1538     int64_t Val = CE->getValue();
1539     return (Val > -256 && Val < 256) ||
1540            (Val == std::numeric_limits<int32_t>::min());
1541   }
1542 
1543   bool isPostIdxImm8s4() const {
1544     if (!isImm()) return false;
1545     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1546     if (!CE) return false;
1547     int64_t Val = CE->getValue();
1548     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1549            (Val == std::numeric_limits<int32_t>::min());
1550   }
1551 
1552   bool isMSRMask() const { return Kind == k_MSRMask; }
1553   bool isBankedReg() const { return Kind == k_BankedReg; }
1554   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1555 
1556   // NEON operands.
1557   bool isSingleSpacedVectorList() const {
1558     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1559   }
1560 
1561   bool isDoubleSpacedVectorList() const {
1562     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1563   }
1564 
1565   bool isVecListOneD() const {
1566     if (!isSingleSpacedVectorList()) return false;
1567     return VectorList.Count == 1;
1568   }
1569 
1570   bool isVecListDPair() const {
1571     if (!isSingleSpacedVectorList()) return false;
1572     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1573               .contains(VectorList.RegNum));
1574   }
1575 
1576   bool isVecListThreeD() const {
1577     if (!isSingleSpacedVectorList()) return false;
1578     return VectorList.Count == 3;
1579   }
1580 
1581   bool isVecListFourD() const {
1582     if (!isSingleSpacedVectorList()) return false;
1583     return VectorList.Count == 4;
1584   }
1585 
1586   bool isVecListDPairSpaced() const {
1587     if (Kind != k_VectorList) return false;
1588     if (isSingleSpacedVectorList()) return false;
1589     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1590               .contains(VectorList.RegNum));
1591   }
1592 
1593   bool isVecListThreeQ() const {
1594     if (!isDoubleSpacedVectorList()) return false;
1595     return VectorList.Count == 3;
1596   }
1597 
1598   bool isVecListFourQ() const {
1599     if (!isDoubleSpacedVectorList()) return false;
1600     return VectorList.Count == 4;
1601   }
1602 
1603   bool isSingleSpacedVectorAllLanes() const {
1604     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1605   }
1606 
1607   bool isDoubleSpacedVectorAllLanes() const {
1608     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1609   }
1610 
1611   bool isVecListOneDAllLanes() const {
1612     if (!isSingleSpacedVectorAllLanes()) return false;
1613     return VectorList.Count == 1;
1614   }
1615 
1616   bool isVecListDPairAllLanes() const {
1617     if (!isSingleSpacedVectorAllLanes()) return false;
1618     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1619               .contains(VectorList.RegNum));
1620   }
1621 
1622   bool isVecListDPairSpacedAllLanes() const {
1623     if (!isDoubleSpacedVectorAllLanes()) return false;
1624     return VectorList.Count == 2;
1625   }
1626 
1627   bool isVecListThreeDAllLanes() const {
1628     if (!isSingleSpacedVectorAllLanes()) return false;
1629     return VectorList.Count == 3;
1630   }
1631 
1632   bool isVecListThreeQAllLanes() const {
1633     if (!isDoubleSpacedVectorAllLanes()) return false;
1634     return VectorList.Count == 3;
1635   }
1636 
1637   bool isVecListFourDAllLanes() const {
1638     if (!isSingleSpacedVectorAllLanes()) return false;
1639     return VectorList.Count == 4;
1640   }
1641 
1642   bool isVecListFourQAllLanes() const {
1643     if (!isDoubleSpacedVectorAllLanes()) return false;
1644     return VectorList.Count == 4;
1645   }
1646 
1647   bool isSingleSpacedVectorIndexed() const {
1648     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1649   }
1650 
1651   bool isDoubleSpacedVectorIndexed() const {
1652     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1653   }
1654 
1655   bool isVecListOneDByteIndexed() const {
1656     if (!isSingleSpacedVectorIndexed()) return false;
1657     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1658   }
1659 
1660   bool isVecListOneDHWordIndexed() const {
1661     if (!isSingleSpacedVectorIndexed()) return false;
1662     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1663   }
1664 
1665   bool isVecListOneDWordIndexed() const {
1666     if (!isSingleSpacedVectorIndexed()) return false;
1667     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1668   }
1669 
1670   bool isVecListTwoDByteIndexed() const {
1671     if (!isSingleSpacedVectorIndexed()) return false;
1672     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1673   }
1674 
1675   bool isVecListTwoDHWordIndexed() const {
1676     if (!isSingleSpacedVectorIndexed()) return false;
1677     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1678   }
1679 
1680   bool isVecListTwoQWordIndexed() const {
1681     if (!isDoubleSpacedVectorIndexed()) return false;
1682     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1683   }
1684 
1685   bool isVecListTwoQHWordIndexed() const {
1686     if (!isDoubleSpacedVectorIndexed()) return false;
1687     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1688   }
1689 
1690   bool isVecListTwoDWordIndexed() const {
1691     if (!isSingleSpacedVectorIndexed()) return false;
1692     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1693   }
1694 
1695   bool isVecListThreeDByteIndexed() const {
1696     if (!isSingleSpacedVectorIndexed()) return false;
1697     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1698   }
1699 
1700   bool isVecListThreeDHWordIndexed() const {
1701     if (!isSingleSpacedVectorIndexed()) return false;
1702     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1703   }
1704 
1705   bool isVecListThreeQWordIndexed() const {
1706     if (!isDoubleSpacedVectorIndexed()) return false;
1707     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1708   }
1709 
1710   bool isVecListThreeQHWordIndexed() const {
1711     if (!isDoubleSpacedVectorIndexed()) return false;
1712     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1713   }
1714 
1715   bool isVecListThreeDWordIndexed() const {
1716     if (!isSingleSpacedVectorIndexed()) return false;
1717     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1718   }
1719 
1720   bool isVecListFourDByteIndexed() const {
1721     if (!isSingleSpacedVectorIndexed()) return false;
1722     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1723   }
1724 
1725   bool isVecListFourDHWordIndexed() const {
1726     if (!isSingleSpacedVectorIndexed()) return false;
1727     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1728   }
1729 
1730   bool isVecListFourQWordIndexed() const {
1731     if (!isDoubleSpacedVectorIndexed()) return false;
1732     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1733   }
1734 
1735   bool isVecListFourQHWordIndexed() const {
1736     if (!isDoubleSpacedVectorIndexed()) return false;
1737     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1738   }
1739 
1740   bool isVecListFourDWordIndexed() const {
1741     if (!isSingleSpacedVectorIndexed()) return false;
1742     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1743   }
1744 
1745   bool isVectorIndex8() const {
1746     if (Kind != k_VectorIndex) return false;
1747     return VectorIndex.Val < 8;
1748   }
1749 
1750   bool isVectorIndex16() const {
1751     if (Kind != k_VectorIndex) return false;
1752     return VectorIndex.Val < 4;
1753   }
1754 
1755   bool isVectorIndex32() const {
1756     if (Kind != k_VectorIndex) return false;
1757     return VectorIndex.Val < 2;
1758   }
1759 
1760   bool isNEONi8splat() const {
1761     if (!isImm()) return false;
1762     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1763     // Must be a constant.
1764     if (!CE) return false;
1765     int64_t Value = CE->getValue();
1766     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1767     // value.
1768     return Value >= 0 && Value < 256;
1769   }
1770 
1771   bool isNEONi16splat() const {
1772     if (isNEONByteReplicate(2))
1773       return false; // Leave that for bytes replication and forbid by default.
1774     if (!isImm())
1775       return false;
1776     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1777     // Must be a constant.
1778     if (!CE) return false;
1779     unsigned Value = CE->getValue();
1780     return ARM_AM::isNEONi16splat(Value);
1781   }
1782 
1783   bool isNEONi16splatNot() const {
1784     if (!isImm())
1785       return false;
1786     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1787     // Must be a constant.
1788     if (!CE) return false;
1789     unsigned Value = CE->getValue();
1790     return ARM_AM::isNEONi16splat(~Value & 0xffff);
1791   }
1792 
1793   bool isNEONi32splat() const {
1794     if (isNEONByteReplicate(4))
1795       return false; // Leave that for bytes replication and forbid by default.
1796     if (!isImm())
1797       return false;
1798     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1799     // Must be a constant.
1800     if (!CE) return false;
1801     unsigned Value = CE->getValue();
1802     return ARM_AM::isNEONi32splat(Value);
1803   }
1804 
1805   bool isNEONi32splatNot() const {
1806     if (!isImm())
1807       return false;
1808     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1809     // Must be a constant.
1810     if (!CE) return false;
1811     unsigned Value = CE->getValue();
1812     return ARM_AM::isNEONi32splat(~Value);
1813   }
1814 
1815   bool isNEONByteReplicate(unsigned NumBytes) const {
1816     if (!isImm())
1817       return false;
1818     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1819     // Must be a constant.
1820     if (!CE)
1821       return false;
1822     int64_t Value = CE->getValue();
1823     if (!Value)
1824       return false; // Don't bother with zero.
1825 
1826     unsigned char B = Value & 0xff;
1827     for (unsigned i = 1; i < NumBytes; ++i) {
1828       Value >>= 8;
1829       if ((Value & 0xff) != B)
1830         return false;
1831     }
1832     return true;
1833   }
1834 
1835   bool isNEONi16ByteReplicate() const { return isNEONByteReplicate(2); }
1836   bool isNEONi32ByteReplicate() const { return isNEONByteReplicate(4); }
1837 
1838   bool isNEONi32vmov() const {
1839     if (isNEONByteReplicate(4))
1840       return false; // Let it to be classified as byte-replicate case.
1841     if (!isImm())
1842       return false;
1843     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1844     // Must be a constant.
1845     if (!CE)
1846       return false;
1847     int64_t Value = CE->getValue();
1848     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1849     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1850     // FIXME: This is probably wrong and a copy and paste from previous example
1851     return (Value >= 0 && Value < 256) ||
1852       (Value >= 0x0100 && Value <= 0xff00) ||
1853       (Value >= 0x010000 && Value <= 0xff0000) ||
1854       (Value >= 0x01000000 && Value <= 0xff000000) ||
1855       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1856       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1857   }
1858 
1859   bool isNEONi32vmovNeg() const {
1860     if (!isImm()) return false;
1861     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1862     // Must be a constant.
1863     if (!CE) return false;
1864     int64_t Value = ~CE->getValue();
1865     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1866     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1867     // FIXME: This is probably wrong and a copy and paste from previous example
1868     return (Value >= 0 && Value < 256) ||
1869       (Value >= 0x0100 && Value <= 0xff00) ||
1870       (Value >= 0x010000 && Value <= 0xff0000) ||
1871       (Value >= 0x01000000 && Value <= 0xff000000) ||
1872       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1873       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1874   }
1875 
1876   bool isNEONi64splat() const {
1877     if (!isImm()) return false;
1878     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1879     // Must be a constant.
1880     if (!CE) return false;
1881     uint64_t Value = CE->getValue();
1882     // i64 value with each byte being either 0 or 0xff.
1883     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
1884       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1885     return true;
1886   }
1887 
1888   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1889     // Add as immediates when possible.  Null MCExpr = 0.
1890     if (!Expr)
1891       Inst.addOperand(MCOperand::createImm(0));
1892     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1893       Inst.addOperand(MCOperand::createImm(CE->getValue()));
1894     else
1895       Inst.addOperand(MCOperand::createExpr(Expr));
1896   }
1897 
1898   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
1899     assert(N == 1 && "Invalid number of operands!");
1900     addExpr(Inst, getImm());
1901   }
1902 
1903   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
1904     assert(N == 1 && "Invalid number of operands!");
1905     addExpr(Inst, getImm());
1906   }
1907 
1908   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
1909     assert(N == 2 && "Invalid number of operands!");
1910     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1911     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
1912     Inst.addOperand(MCOperand::createReg(RegNum));
1913   }
1914 
1915   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
1916     assert(N == 1 && "Invalid number of operands!");
1917     Inst.addOperand(MCOperand::createImm(getCoproc()));
1918   }
1919 
1920   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
1921     assert(N == 1 && "Invalid number of operands!");
1922     Inst.addOperand(MCOperand::createImm(getCoproc()));
1923   }
1924 
1925   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
1926     assert(N == 1 && "Invalid number of operands!");
1927     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
1928   }
1929 
1930   void addITMaskOperands(MCInst &Inst, unsigned N) const {
1931     assert(N == 1 && "Invalid number of operands!");
1932     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
1933   }
1934 
1935   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
1936     assert(N == 1 && "Invalid number of operands!");
1937     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1938   }
1939 
1940   void addCCOutOperands(MCInst &Inst, unsigned N) const {
1941     assert(N == 1 && "Invalid number of operands!");
1942     Inst.addOperand(MCOperand::createReg(getReg()));
1943   }
1944 
1945   void addRegOperands(MCInst &Inst, unsigned N) const {
1946     assert(N == 1 && "Invalid number of operands!");
1947     Inst.addOperand(MCOperand::createReg(getReg()));
1948   }
1949 
1950   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
1951     assert(N == 3 && "Invalid number of operands!");
1952     assert(isRegShiftedReg() &&
1953            "addRegShiftedRegOperands() on non-RegShiftedReg!");
1954     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
1955     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
1956     Inst.addOperand(MCOperand::createImm(
1957       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
1958   }
1959 
1960   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
1961     assert(N == 2 && "Invalid number of operands!");
1962     assert(isRegShiftedImm() &&
1963            "addRegShiftedImmOperands() on non-RegShiftedImm!");
1964     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
1965     // Shift of #32 is encoded as 0 where permitted
1966     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
1967     Inst.addOperand(MCOperand::createImm(
1968       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
1969   }
1970 
1971   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
1972     assert(N == 1 && "Invalid number of operands!");
1973     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
1974                                          ShifterImm.Imm));
1975   }
1976 
1977   void addRegListOperands(MCInst &Inst, unsigned N) const {
1978     assert(N == 1 && "Invalid number of operands!");
1979     const SmallVectorImpl<unsigned> &RegList = getRegList();
1980     for (SmallVectorImpl<unsigned>::const_iterator
1981            I = RegList.begin(), E = RegList.end(); I != E; ++I)
1982       Inst.addOperand(MCOperand::createReg(*I));
1983   }
1984 
1985   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
1986     addRegListOperands(Inst, N);
1987   }
1988 
1989   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
1990     addRegListOperands(Inst, N);
1991   }
1992 
1993   void addRotImmOperands(MCInst &Inst, unsigned N) const {
1994     assert(N == 1 && "Invalid number of operands!");
1995     // Encoded as val>>3. The printer handles display as 8, 16, 24.
1996     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
1997   }
1998 
1999   void addModImmOperands(MCInst &Inst, unsigned N) const {
2000     assert(N == 1 && "Invalid number of operands!");
2001 
2002     // Support for fixups (MCFixup)
2003     if (isImm())
2004       return addImmOperands(Inst, N);
2005 
2006     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
2007   }
2008 
2009   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
2010     assert(N == 1 && "Invalid number of operands!");
2011     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2012     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
2013     Inst.addOperand(MCOperand::createImm(Enc));
2014   }
2015 
2016   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
2017     assert(N == 1 && "Invalid number of operands!");
2018     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2019     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
2020     Inst.addOperand(MCOperand::createImm(Enc));
2021   }
2022 
2023   void addThumbModImmNeg8_255Operands(MCInst &Inst, unsigned N) const {
2024     assert(N == 1 && "Invalid number of operands!");
2025     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2026     uint32_t Val = -CE->getValue();
2027     Inst.addOperand(MCOperand::createImm(Val));
2028   }
2029 
2030   void addThumbModImmNeg1_7Operands(MCInst &Inst, unsigned N) const {
2031     assert(N == 1 && "Invalid number of operands!");
2032     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2033     uint32_t Val = -CE->getValue();
2034     Inst.addOperand(MCOperand::createImm(Val));
2035   }
2036 
2037   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
2038     assert(N == 1 && "Invalid number of operands!");
2039     // Munge the lsb/width into a bitfield mask.
2040     unsigned lsb = Bitfield.LSB;
2041     unsigned width = Bitfield.Width;
2042     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
2043     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
2044                       (32 - (lsb + width)));
2045     Inst.addOperand(MCOperand::createImm(Mask));
2046   }
2047 
2048   void addImmOperands(MCInst &Inst, unsigned N) const {
2049     assert(N == 1 && "Invalid number of operands!");
2050     addExpr(Inst, getImm());
2051   }
2052 
2053   void addFBits16Operands(MCInst &Inst, unsigned N) const {
2054     assert(N == 1 && "Invalid number of operands!");
2055     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2056     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
2057   }
2058 
2059   void addFBits32Operands(MCInst &Inst, unsigned N) const {
2060     assert(N == 1 && "Invalid number of operands!");
2061     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2062     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
2063   }
2064 
2065   void addFPImmOperands(MCInst &Inst, unsigned N) const {
2066     assert(N == 1 && "Invalid number of operands!");
2067     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2068     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
2069     Inst.addOperand(MCOperand::createImm(Val));
2070   }
2071 
2072   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
2073     assert(N == 1 && "Invalid number of operands!");
2074     // FIXME: We really want to scale the value here, but the LDRD/STRD
2075     // instruction don't encode operands that way yet.
2076     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2077     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2078   }
2079 
2080   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
2081     assert(N == 1 && "Invalid number of operands!");
2082     // The immediate is scaled by four in the encoding and is stored
2083     // in the MCInst as such. Lop off the low two bits here.
2084     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2085     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2086   }
2087 
2088   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
2089     assert(N == 1 && "Invalid number of operands!");
2090     // The immediate is scaled by four in the encoding and is stored
2091     // in the MCInst as such. Lop off the low two bits here.
2092     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2093     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
2094   }
2095 
2096   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
2097     assert(N == 1 && "Invalid number of operands!");
2098     // The immediate is scaled by four in the encoding and is stored
2099     // in the MCInst as such. Lop off the low two bits here.
2100     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2101     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2102   }
2103 
2104   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
2105     assert(N == 1 && "Invalid number of operands!");
2106     // The constant encodes as the immediate-1, and we store in the instruction
2107     // the bits as encoded, so subtract off one here.
2108     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2109     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2110   }
2111 
2112   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
2113     assert(N == 1 && "Invalid number of operands!");
2114     // The constant encodes as the immediate-1, and we store in the instruction
2115     // the bits as encoded, so subtract off one here.
2116     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2117     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2118   }
2119 
2120   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
2121     assert(N == 1 && "Invalid number of operands!");
2122     // The constant encodes as the immediate, except for 32, which encodes as
2123     // zero.
2124     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2125     unsigned Imm = CE->getValue();
2126     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
2127   }
2128 
2129   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
2130     assert(N == 1 && "Invalid number of operands!");
2131     // An ASR value of 32 encodes as 0, so that's how we want to add it to
2132     // the instruction as well.
2133     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2134     int Val = CE->getValue();
2135     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
2136   }
2137 
2138   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2139     assert(N == 1 && "Invalid number of operands!");
2140     // The operand is actually a t2_so_imm, but we have its bitwise
2141     // negation in the assembly source, so twiddle it here.
2142     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2143     Inst.addOperand(MCOperand::createImm(~(uint32_t)CE->getValue()));
2144   }
2145 
2146   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2147     assert(N == 1 && "Invalid number of operands!");
2148     // The operand is actually a t2_so_imm, but we have its
2149     // negation in the assembly source, so twiddle it here.
2150     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2151     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2152   }
2153 
2154   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2155     assert(N == 1 && "Invalid number of operands!");
2156     // The operand is actually an imm0_4095, but we have its
2157     // negation in the assembly source, so twiddle it here.
2158     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2159     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
2160   }
2161 
2162   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2163     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2164       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2165       return;
2166     }
2167 
2168     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2169     assert(SR && "Unknown value type!");
2170     Inst.addOperand(MCOperand::createExpr(SR));
2171   }
2172 
2173   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2174     assert(N == 1 && "Invalid number of operands!");
2175     if (isImm()) {
2176       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2177       if (CE) {
2178         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2179         return;
2180       }
2181 
2182       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2183 
2184       assert(SR && "Unknown value type!");
2185       Inst.addOperand(MCOperand::createExpr(SR));
2186       return;
2187     }
2188 
2189     assert(isMem()  && "Unknown value type!");
2190     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2191     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
2192   }
2193 
2194   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2195     assert(N == 1 && "Invalid number of operands!");
2196     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2197   }
2198 
2199   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2200     assert(N == 1 && "Invalid number of operands!");
2201     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2202   }
2203 
2204   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2205     assert(N == 1 && "Invalid number of operands!");
2206     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2207   }
2208 
2209   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2210     assert(N == 1 && "Invalid number of operands!");
2211     int32_t Imm = Memory.OffsetImm->getValue();
2212     Inst.addOperand(MCOperand::createImm(Imm));
2213   }
2214 
2215   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2216     assert(N == 1 && "Invalid number of operands!");
2217     assert(isImm() && "Not an immediate!");
2218 
2219     // If we have an immediate that's not a constant, treat it as a label
2220     // reference needing a fixup.
2221     if (!isa<MCConstantExpr>(getImm())) {
2222       Inst.addOperand(MCOperand::createExpr(getImm()));
2223       return;
2224     }
2225 
2226     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2227     int Val = CE->getValue();
2228     Inst.addOperand(MCOperand::createImm(Val));
2229   }
2230 
2231   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2232     assert(N == 2 && "Invalid number of operands!");
2233     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2234     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2235   }
2236 
2237   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2238     addAlignedMemoryOperands(Inst, N);
2239   }
2240 
2241   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2242     addAlignedMemoryOperands(Inst, N);
2243   }
2244 
2245   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2246     addAlignedMemoryOperands(Inst, N);
2247   }
2248 
2249   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2250     addAlignedMemoryOperands(Inst, N);
2251   }
2252 
2253   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2254     addAlignedMemoryOperands(Inst, N);
2255   }
2256 
2257   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2258     addAlignedMemoryOperands(Inst, N);
2259   }
2260 
2261   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2262     addAlignedMemoryOperands(Inst, N);
2263   }
2264 
2265   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2266     addAlignedMemoryOperands(Inst, N);
2267   }
2268 
2269   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2270     addAlignedMemoryOperands(Inst, N);
2271   }
2272 
2273   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2274     addAlignedMemoryOperands(Inst, N);
2275   }
2276 
2277   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2278     addAlignedMemoryOperands(Inst, N);
2279   }
2280 
2281   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2282     assert(N == 3 && "Invalid number of operands!");
2283     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2284     if (!Memory.OffsetRegNum) {
2285       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2286       // Special case for #-0
2287       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2288       if (Val < 0) Val = -Val;
2289       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2290     } else {
2291       // For register offset, we encode the shift type and negation flag
2292       // here.
2293       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2294                               Memory.ShiftImm, Memory.ShiftType);
2295     }
2296     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2297     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2298     Inst.addOperand(MCOperand::createImm(Val));
2299   }
2300 
2301   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2302     assert(N == 2 && "Invalid number of operands!");
2303     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2304     assert(CE && "non-constant AM2OffsetImm operand!");
2305     int32_t Val = CE->getValue();
2306     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2307     // Special case for #-0
2308     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2309     if (Val < 0) Val = -Val;
2310     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2311     Inst.addOperand(MCOperand::createReg(0));
2312     Inst.addOperand(MCOperand::createImm(Val));
2313   }
2314 
2315   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2316     assert(N == 3 && "Invalid number of operands!");
2317     // If we have an immediate that's not a constant, treat it as a label
2318     // reference needing a fixup. If it is a constant, it's something else
2319     // and we reject it.
2320     if (isImm()) {
2321       Inst.addOperand(MCOperand::createExpr(getImm()));
2322       Inst.addOperand(MCOperand::createReg(0));
2323       Inst.addOperand(MCOperand::createImm(0));
2324       return;
2325     }
2326 
2327     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2328     if (!Memory.OffsetRegNum) {
2329       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2330       // Special case for #-0
2331       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2332       if (Val < 0) Val = -Val;
2333       Val = ARM_AM::getAM3Opc(AddSub, Val);
2334     } else {
2335       // For register offset, we encode the shift type and negation flag
2336       // here.
2337       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2338     }
2339     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2340     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2341     Inst.addOperand(MCOperand::createImm(Val));
2342   }
2343 
2344   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2345     assert(N == 2 && "Invalid number of operands!");
2346     if (Kind == k_PostIndexRegister) {
2347       int32_t Val =
2348         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2349       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2350       Inst.addOperand(MCOperand::createImm(Val));
2351       return;
2352     }
2353 
2354     // Constant offset.
2355     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2356     int32_t Val = CE->getValue();
2357     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2358     // Special case for #-0
2359     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2360     if (Val < 0) Val = -Val;
2361     Val = ARM_AM::getAM3Opc(AddSub, Val);
2362     Inst.addOperand(MCOperand::createReg(0));
2363     Inst.addOperand(MCOperand::createImm(Val));
2364   }
2365 
2366   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2367     assert(N == 2 && "Invalid number of operands!");
2368     // If we have an immediate that's not a constant, treat it as a label
2369     // reference needing a fixup. If it is a constant, it's something else
2370     // and we reject it.
2371     if (isImm()) {
2372       Inst.addOperand(MCOperand::createExpr(getImm()));
2373       Inst.addOperand(MCOperand::createImm(0));
2374       return;
2375     }
2376 
2377     // The lower two bits are always zero and as such are not encoded.
2378     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2379     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2380     // Special case for #-0
2381     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2382     if (Val < 0) Val = -Val;
2383     Val = ARM_AM::getAM5Opc(AddSub, Val);
2384     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2385     Inst.addOperand(MCOperand::createImm(Val));
2386   }
2387 
2388   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
2389     assert(N == 2 && "Invalid number of operands!");
2390     // If we have an immediate that's not a constant, treat it as a label
2391     // reference needing a fixup. If it is a constant, it's something else
2392     // and we reject it.
2393     if (isImm()) {
2394       Inst.addOperand(MCOperand::createExpr(getImm()));
2395       Inst.addOperand(MCOperand::createImm(0));
2396       return;
2397     }
2398 
2399     // The lower bit is always zero and as such is not encoded.
2400     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 2 : 0;
2401     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2402     // Special case for #-0
2403     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2404     if (Val < 0) Val = -Val;
2405     Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
2406     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2407     Inst.addOperand(MCOperand::createImm(Val));
2408   }
2409 
2410   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2411     assert(N == 2 && "Invalid number of operands!");
2412     // If we have an immediate that's not a constant, treat it as a label
2413     // reference needing a fixup. If it is a constant, it's something else
2414     // and we reject it.
2415     if (isImm()) {
2416       Inst.addOperand(MCOperand::createExpr(getImm()));
2417       Inst.addOperand(MCOperand::createImm(0));
2418       return;
2419     }
2420 
2421     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2422     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2423     Inst.addOperand(MCOperand::createImm(Val));
2424   }
2425 
2426   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2427     assert(N == 2 && "Invalid number of operands!");
2428     // The lower two bits are always zero and as such are not encoded.
2429     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2430     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2431     Inst.addOperand(MCOperand::createImm(Val));
2432   }
2433 
2434   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2435     assert(N == 2 && "Invalid number of operands!");
2436     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2437     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2438     Inst.addOperand(MCOperand::createImm(Val));
2439   }
2440 
2441   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2442     addMemImm8OffsetOperands(Inst, N);
2443   }
2444 
2445   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2446     addMemImm8OffsetOperands(Inst, N);
2447   }
2448 
2449   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2450     assert(N == 2 && "Invalid number of operands!");
2451     // If this is an immediate, it's a label reference.
2452     if (isImm()) {
2453       addExpr(Inst, getImm());
2454       Inst.addOperand(MCOperand::createImm(0));
2455       return;
2456     }
2457 
2458     // Otherwise, it's a normal memory reg+offset.
2459     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2460     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2461     Inst.addOperand(MCOperand::createImm(Val));
2462   }
2463 
2464   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2465     assert(N == 2 && "Invalid number of operands!");
2466     // If this is an immediate, it's a label reference.
2467     if (isImm()) {
2468       addExpr(Inst, getImm());
2469       Inst.addOperand(MCOperand::createImm(0));
2470       return;
2471     }
2472 
2473     // Otherwise, it's a normal memory reg+offset.
2474     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2475     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2476     Inst.addOperand(MCOperand::createImm(Val));
2477   }
2478 
2479   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
2480     assert(N == 1 && "Invalid number of operands!");
2481     // This is container for the immediate that we will create the constant
2482     // pool from
2483     addExpr(Inst, getConstantPoolImm());
2484     return;
2485   }
2486 
2487   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2488     assert(N == 2 && "Invalid number of operands!");
2489     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2490     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2491   }
2492 
2493   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2494     assert(N == 2 && "Invalid number of operands!");
2495     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2496     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2497   }
2498 
2499   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2500     assert(N == 3 && "Invalid number of operands!");
2501     unsigned Val =
2502       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2503                         Memory.ShiftImm, Memory.ShiftType);
2504     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2505     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2506     Inst.addOperand(MCOperand::createImm(Val));
2507   }
2508 
2509   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2510     assert(N == 3 && "Invalid number of operands!");
2511     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2512     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2513     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
2514   }
2515 
2516   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
2517     assert(N == 2 && "Invalid number of operands!");
2518     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2519     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2520   }
2521 
2522   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2523     assert(N == 2 && "Invalid number of operands!");
2524     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2525     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2526     Inst.addOperand(MCOperand::createImm(Val));
2527   }
2528 
2529   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2530     assert(N == 2 && "Invalid number of operands!");
2531     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2532     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2533     Inst.addOperand(MCOperand::createImm(Val));
2534   }
2535 
2536   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2537     assert(N == 2 && "Invalid number of operands!");
2538     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2539     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2540     Inst.addOperand(MCOperand::createImm(Val));
2541   }
2542 
2543   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2544     assert(N == 2 && "Invalid number of operands!");
2545     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2546     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2547     Inst.addOperand(MCOperand::createImm(Val));
2548   }
2549 
2550   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2551     assert(N == 1 && "Invalid number of operands!");
2552     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2553     assert(CE && "non-constant post-idx-imm8 operand!");
2554     int Imm = CE->getValue();
2555     bool isAdd = Imm >= 0;
2556     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
2557     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2558     Inst.addOperand(MCOperand::createImm(Imm));
2559   }
2560 
2561   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2562     assert(N == 1 && "Invalid number of operands!");
2563     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2564     assert(CE && "non-constant post-idx-imm8s4 operand!");
2565     int Imm = CE->getValue();
2566     bool isAdd = Imm >= 0;
2567     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
2568     // Immediate is scaled by 4.
2569     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2570     Inst.addOperand(MCOperand::createImm(Imm));
2571   }
2572 
2573   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2574     assert(N == 2 && "Invalid number of operands!");
2575     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2576     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
2577   }
2578 
2579   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2580     assert(N == 2 && "Invalid number of operands!");
2581     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2582     // The sign, shift type, and shift amount are encoded in a single operand
2583     // using the AM2 encoding helpers.
2584     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2585     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2586                                      PostIdxReg.ShiftTy);
2587     Inst.addOperand(MCOperand::createImm(Imm));
2588   }
2589 
2590   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2591     assert(N == 1 && "Invalid number of operands!");
2592     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
2593   }
2594 
2595   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2596     assert(N == 1 && "Invalid number of operands!");
2597     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
2598   }
2599 
2600   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2601     assert(N == 1 && "Invalid number of operands!");
2602     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
2603   }
2604 
2605   void addVecListOperands(MCInst &Inst, unsigned N) const {
2606     assert(N == 1 && "Invalid number of operands!");
2607     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2608   }
2609 
2610   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
2611     assert(N == 2 && "Invalid number of operands!");
2612     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2613     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
2614   }
2615 
2616   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
2617     assert(N == 1 && "Invalid number of operands!");
2618     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2619   }
2620 
2621   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
2622     assert(N == 1 && "Invalid number of operands!");
2623     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2624   }
2625 
2626   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
2627     assert(N == 1 && "Invalid number of operands!");
2628     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2629   }
2630 
2631   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
2632     assert(N == 1 && "Invalid number of operands!");
2633     // The immediate encodes the type of constant as well as the value.
2634     // Mask in that this is an i8 splat.
2635     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2636     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
2637   }
2638 
2639   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
2640     assert(N == 1 && "Invalid number of operands!");
2641     // The immediate encodes the type of constant as well as the value.
2642     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2643     unsigned Value = CE->getValue();
2644     Value = ARM_AM::encodeNEONi16splat(Value);
2645     Inst.addOperand(MCOperand::createImm(Value));
2646   }
2647 
2648   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
2649     assert(N == 1 && "Invalid number of operands!");
2650     // The immediate encodes the type of constant as well as the value.
2651     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2652     unsigned Value = CE->getValue();
2653     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
2654     Inst.addOperand(MCOperand::createImm(Value));
2655   }
2656 
2657   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
2658     assert(N == 1 && "Invalid number of operands!");
2659     // The immediate encodes the type of constant as well as the value.
2660     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2661     unsigned Value = CE->getValue();
2662     Value = ARM_AM::encodeNEONi32splat(Value);
2663     Inst.addOperand(MCOperand::createImm(Value));
2664   }
2665 
2666   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
2667     assert(N == 1 && "Invalid number of operands!");
2668     // The immediate encodes the type of constant as well as the value.
2669     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2670     unsigned Value = CE->getValue();
2671     Value = ARM_AM::encodeNEONi32splat(~Value);
2672     Inst.addOperand(MCOperand::createImm(Value));
2673   }
2674 
2675   void addNEONinvByteReplicateOperands(MCInst &Inst, unsigned N) const {
2676     assert(N == 1 && "Invalid number of operands!");
2677     // The immediate encodes the type of constant as well as the value.
2678     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2679     unsigned Value = CE->getValue();
2680     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2681             Inst.getOpcode() == ARM::VMOVv16i8) &&
2682            "All vmvn instructions that wants to replicate non-zero byte "
2683            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2684     unsigned B = ((~Value) & 0xff);
2685     B |= 0xe00; // cmode = 0b1110
2686     Inst.addOperand(MCOperand::createImm(B));
2687   }
2688 
2689   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
2690     assert(N == 1 && "Invalid number of operands!");
2691     // The immediate encodes the type of constant as well as the value.
2692     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2693     unsigned Value = CE->getValue();
2694     if (Value >= 256 && Value <= 0xffff)
2695       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2696     else if (Value > 0xffff && Value <= 0xffffff)
2697       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2698     else if (Value > 0xffffff)
2699       Value = (Value >> 24) | 0x600;
2700     Inst.addOperand(MCOperand::createImm(Value));
2701   }
2702 
2703   void addNEONvmovByteReplicateOperands(MCInst &Inst, unsigned N) const {
2704     assert(N == 1 && "Invalid number of operands!");
2705     // The immediate encodes the type of constant as well as the value.
2706     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2707     unsigned Value = CE->getValue();
2708     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2709             Inst.getOpcode() == ARM::VMOVv16i8) &&
2710            "All instructions that wants to replicate non-zero byte "
2711            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2712     unsigned B = Value & 0xff;
2713     B |= 0xe00; // cmode = 0b1110
2714     Inst.addOperand(MCOperand::createImm(B));
2715   }
2716 
2717   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
2718     assert(N == 1 && "Invalid number of operands!");
2719     // The immediate encodes the type of constant as well as the value.
2720     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2721     unsigned Value = ~CE->getValue();
2722     if (Value >= 256 && Value <= 0xffff)
2723       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2724     else if (Value > 0xffff && Value <= 0xffffff)
2725       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2726     else if (Value > 0xffffff)
2727       Value = (Value >> 24) | 0x600;
2728     Inst.addOperand(MCOperand::createImm(Value));
2729   }
2730 
2731   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
2732     assert(N == 1 && "Invalid number of operands!");
2733     // The immediate encodes the type of constant as well as the value.
2734     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2735     uint64_t Value = CE->getValue();
2736     unsigned Imm = 0;
2737     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
2738       Imm |= (Value & 1) << i;
2739     }
2740     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
2741   }
2742 
2743   void print(raw_ostream &OS) const override;
2744 
2745   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
2746     auto Op = make_unique<ARMOperand>(k_ITCondMask);
2747     Op->ITMask.Mask = Mask;
2748     Op->StartLoc = S;
2749     Op->EndLoc = S;
2750     return Op;
2751   }
2752 
2753   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
2754                                                     SMLoc S) {
2755     auto Op = make_unique<ARMOperand>(k_CondCode);
2756     Op->CC.Val = CC;
2757     Op->StartLoc = S;
2758     Op->EndLoc = S;
2759     return Op;
2760   }
2761 
2762   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
2763     auto Op = make_unique<ARMOperand>(k_CoprocNum);
2764     Op->Cop.Val = CopVal;
2765     Op->StartLoc = S;
2766     Op->EndLoc = S;
2767     return Op;
2768   }
2769 
2770   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
2771     auto Op = make_unique<ARMOperand>(k_CoprocReg);
2772     Op->Cop.Val = CopVal;
2773     Op->StartLoc = S;
2774     Op->EndLoc = S;
2775     return Op;
2776   }
2777 
2778   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
2779                                                         SMLoc E) {
2780     auto Op = make_unique<ARMOperand>(k_CoprocOption);
2781     Op->Cop.Val = Val;
2782     Op->StartLoc = S;
2783     Op->EndLoc = E;
2784     return Op;
2785   }
2786 
2787   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
2788     auto Op = make_unique<ARMOperand>(k_CCOut);
2789     Op->Reg.RegNum = RegNum;
2790     Op->StartLoc = S;
2791     Op->EndLoc = S;
2792     return Op;
2793   }
2794 
2795   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
2796     auto Op = make_unique<ARMOperand>(k_Token);
2797     Op->Tok.Data = Str.data();
2798     Op->Tok.Length = Str.size();
2799     Op->StartLoc = S;
2800     Op->EndLoc = S;
2801     return Op;
2802   }
2803 
2804   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
2805                                                SMLoc E) {
2806     auto Op = make_unique<ARMOperand>(k_Register);
2807     Op->Reg.RegNum = RegNum;
2808     Op->StartLoc = S;
2809     Op->EndLoc = E;
2810     return Op;
2811   }
2812 
2813   static std::unique_ptr<ARMOperand>
2814   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2815                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
2816                         SMLoc E) {
2817     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
2818     Op->RegShiftedReg.ShiftTy = ShTy;
2819     Op->RegShiftedReg.SrcReg = SrcReg;
2820     Op->RegShiftedReg.ShiftReg = ShiftReg;
2821     Op->RegShiftedReg.ShiftImm = ShiftImm;
2822     Op->StartLoc = S;
2823     Op->EndLoc = E;
2824     return Op;
2825   }
2826 
2827   static std::unique_ptr<ARMOperand>
2828   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2829                          unsigned ShiftImm, SMLoc S, SMLoc E) {
2830     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
2831     Op->RegShiftedImm.ShiftTy = ShTy;
2832     Op->RegShiftedImm.SrcReg = SrcReg;
2833     Op->RegShiftedImm.ShiftImm = ShiftImm;
2834     Op->StartLoc = S;
2835     Op->EndLoc = E;
2836     return Op;
2837   }
2838 
2839   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
2840                                                       SMLoc S, SMLoc E) {
2841     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
2842     Op->ShifterImm.isASR = isASR;
2843     Op->ShifterImm.Imm = Imm;
2844     Op->StartLoc = S;
2845     Op->EndLoc = E;
2846     return Op;
2847   }
2848 
2849   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
2850                                                   SMLoc E) {
2851     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
2852     Op->RotImm.Imm = Imm;
2853     Op->StartLoc = S;
2854     Op->EndLoc = E;
2855     return Op;
2856   }
2857 
2858   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
2859                                                   SMLoc S, SMLoc E) {
2860     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
2861     Op->ModImm.Bits = Bits;
2862     Op->ModImm.Rot = Rot;
2863     Op->StartLoc = S;
2864     Op->EndLoc = E;
2865     return Op;
2866   }
2867 
2868   static std::unique_ptr<ARMOperand>
2869   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
2870     auto Op = make_unique<ARMOperand>(k_ConstantPoolImmediate);
2871     Op->Imm.Val = Val;
2872     Op->StartLoc = S;
2873     Op->EndLoc = E;
2874     return Op;
2875   }
2876 
2877   static std::unique_ptr<ARMOperand>
2878   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
2879     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
2880     Op->Bitfield.LSB = LSB;
2881     Op->Bitfield.Width = Width;
2882     Op->StartLoc = S;
2883     Op->EndLoc = E;
2884     return Op;
2885   }
2886 
2887   static std::unique_ptr<ARMOperand>
2888   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
2889                 SMLoc StartLoc, SMLoc EndLoc) {
2890     assert(Regs.size() > 0 && "RegList contains no registers?");
2891     KindTy Kind = k_RegisterList;
2892 
2893     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().second))
2894       Kind = k_DPRRegisterList;
2895     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
2896              contains(Regs.front().second))
2897       Kind = k_SPRRegisterList;
2898 
2899     // Sort based on the register encoding values.
2900     array_pod_sort(Regs.begin(), Regs.end());
2901 
2902     auto Op = make_unique<ARMOperand>(Kind);
2903     for (SmallVectorImpl<std::pair<unsigned, unsigned>>::const_iterator
2904            I = Regs.begin(), E = Regs.end(); I != E; ++I)
2905       Op->Registers.push_back(I->second);
2906     Op->StartLoc = StartLoc;
2907     Op->EndLoc = EndLoc;
2908     return Op;
2909   }
2910 
2911   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
2912                                                       unsigned Count,
2913                                                       bool isDoubleSpaced,
2914                                                       SMLoc S, SMLoc E) {
2915     auto Op = make_unique<ARMOperand>(k_VectorList);
2916     Op->VectorList.RegNum = RegNum;
2917     Op->VectorList.Count = Count;
2918     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2919     Op->StartLoc = S;
2920     Op->EndLoc = E;
2921     return Op;
2922   }
2923 
2924   static std::unique_ptr<ARMOperand>
2925   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
2926                            SMLoc S, SMLoc E) {
2927     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
2928     Op->VectorList.RegNum = RegNum;
2929     Op->VectorList.Count = Count;
2930     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2931     Op->StartLoc = S;
2932     Op->EndLoc = E;
2933     return Op;
2934   }
2935 
2936   static std::unique_ptr<ARMOperand>
2937   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
2938                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
2939     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
2940     Op->VectorList.RegNum = RegNum;
2941     Op->VectorList.Count = Count;
2942     Op->VectorList.LaneIndex = Index;
2943     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2944     Op->StartLoc = S;
2945     Op->EndLoc = E;
2946     return Op;
2947   }
2948 
2949   static std::unique_ptr<ARMOperand>
2950   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
2951     auto Op = make_unique<ARMOperand>(k_VectorIndex);
2952     Op->VectorIndex.Val = Idx;
2953     Op->StartLoc = S;
2954     Op->EndLoc = E;
2955     return Op;
2956   }
2957 
2958   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
2959                                                SMLoc E) {
2960     auto Op = make_unique<ARMOperand>(k_Immediate);
2961     Op->Imm.Val = Val;
2962     Op->StartLoc = S;
2963     Op->EndLoc = E;
2964     return Op;
2965   }
2966 
2967   static std::unique_ptr<ARMOperand>
2968   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
2969             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
2970             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
2971             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
2972     auto Op = make_unique<ARMOperand>(k_Memory);
2973     Op->Memory.BaseRegNum = BaseRegNum;
2974     Op->Memory.OffsetImm = OffsetImm;
2975     Op->Memory.OffsetRegNum = OffsetRegNum;
2976     Op->Memory.ShiftType = ShiftType;
2977     Op->Memory.ShiftImm = ShiftImm;
2978     Op->Memory.Alignment = Alignment;
2979     Op->Memory.isNegative = isNegative;
2980     Op->StartLoc = S;
2981     Op->EndLoc = E;
2982     Op->AlignmentLoc = AlignmentLoc;
2983     return Op;
2984   }
2985 
2986   static std::unique_ptr<ARMOperand>
2987   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
2988                    unsigned ShiftImm, SMLoc S, SMLoc E) {
2989     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
2990     Op->PostIdxReg.RegNum = RegNum;
2991     Op->PostIdxReg.isAdd = isAdd;
2992     Op->PostIdxReg.ShiftTy = ShiftTy;
2993     Op->PostIdxReg.ShiftImm = ShiftImm;
2994     Op->StartLoc = S;
2995     Op->EndLoc = E;
2996     return Op;
2997   }
2998 
2999   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
3000                                                          SMLoc S) {
3001     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
3002     Op->MBOpt.Val = Opt;
3003     Op->StartLoc = S;
3004     Op->EndLoc = S;
3005     return Op;
3006   }
3007 
3008   static std::unique_ptr<ARMOperand>
3009   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
3010     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
3011     Op->ISBOpt.Val = Opt;
3012     Op->StartLoc = S;
3013     Op->EndLoc = S;
3014     return Op;
3015   }
3016 
3017   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
3018                                                       SMLoc S) {
3019     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
3020     Op->IFlags.Val = IFlags;
3021     Op->StartLoc = S;
3022     Op->EndLoc = S;
3023     return Op;
3024   }
3025 
3026   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
3027     auto Op = make_unique<ARMOperand>(k_MSRMask);
3028     Op->MMask.Val = MMask;
3029     Op->StartLoc = S;
3030     Op->EndLoc = S;
3031     return Op;
3032   }
3033 
3034   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
3035     auto Op = make_unique<ARMOperand>(k_BankedReg);
3036     Op->BankedReg.Val = Reg;
3037     Op->StartLoc = S;
3038     Op->EndLoc = S;
3039     return Op;
3040   }
3041 };
3042 
3043 } // end anonymous namespace.
3044 
3045 void ARMOperand::print(raw_ostream &OS) const {
3046   switch (Kind) {
3047   case k_CondCode:
3048     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
3049     break;
3050   case k_CCOut:
3051     OS << "<ccout " << getReg() << ">";
3052     break;
3053   case k_ITCondMask: {
3054     static const char *const MaskStr[] = {
3055       "()", "(t)", "(e)", "(tt)", "(et)", "(te)", "(ee)", "(ttt)", "(ett)",
3056       "(tet)", "(eet)", "(tte)", "(ete)", "(tee)", "(eee)"
3057     };
3058     assert((ITMask.Mask & 0xf) == ITMask.Mask);
3059     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
3060     break;
3061   }
3062   case k_CoprocNum:
3063     OS << "<coprocessor number: " << getCoproc() << ">";
3064     break;
3065   case k_CoprocReg:
3066     OS << "<coprocessor register: " << getCoproc() << ">";
3067     break;
3068   case k_CoprocOption:
3069     OS << "<coprocessor option: " << CoprocOption.Val << ">";
3070     break;
3071   case k_MSRMask:
3072     OS << "<mask: " << getMSRMask() << ">";
3073     break;
3074   case k_BankedReg:
3075     OS << "<banked reg: " << getBankedReg() << ">";
3076     break;
3077   case k_Immediate:
3078     OS << *getImm();
3079     break;
3080   case k_MemBarrierOpt:
3081     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
3082     break;
3083   case k_InstSyncBarrierOpt:
3084     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
3085     break;
3086   case k_Memory:
3087     OS << "<memory "
3088        << " base:" << Memory.BaseRegNum;
3089     OS << ">";
3090     break;
3091   case k_PostIndexRegister:
3092     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
3093        << PostIdxReg.RegNum;
3094     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
3095       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
3096          << PostIdxReg.ShiftImm;
3097     OS << ">";
3098     break;
3099   case k_ProcIFlags: {
3100     OS << "<ARM_PROC::";
3101     unsigned IFlags = getProcIFlags();
3102     for (int i=2; i >= 0; --i)
3103       if (IFlags & (1 << i))
3104         OS << ARM_PROC::IFlagsToString(1 << i);
3105     OS << ">";
3106     break;
3107   }
3108   case k_Register:
3109     OS << "<register " << getReg() << ">";
3110     break;
3111   case k_ShifterImmediate:
3112     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
3113        << " #" << ShifterImm.Imm << ">";
3114     break;
3115   case k_ShiftedRegister:
3116     OS << "<so_reg_reg "
3117        << RegShiftedReg.SrcReg << " "
3118        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy)
3119        << " " << RegShiftedReg.ShiftReg << ">";
3120     break;
3121   case k_ShiftedImmediate:
3122     OS << "<so_reg_imm "
3123        << RegShiftedImm.SrcReg << " "
3124        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy)
3125        << " #" << RegShiftedImm.ShiftImm << ">";
3126     break;
3127   case k_RotateImmediate:
3128     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
3129     break;
3130   case k_ModifiedImmediate:
3131     OS << "<mod_imm #" << ModImm.Bits << ", #"
3132        <<  ModImm.Rot << ")>";
3133     break;
3134   case k_ConstantPoolImmediate:
3135     OS << "<constant_pool_imm #" << *getConstantPoolImm();
3136     break;
3137   case k_BitfieldDescriptor:
3138     OS << "<bitfield " << "lsb: " << Bitfield.LSB
3139        << ", width: " << Bitfield.Width << ">";
3140     break;
3141   case k_RegisterList:
3142   case k_DPRRegisterList:
3143   case k_SPRRegisterList: {
3144     OS << "<register_list ";
3145 
3146     const SmallVectorImpl<unsigned> &RegList = getRegList();
3147     for (SmallVectorImpl<unsigned>::const_iterator
3148            I = RegList.begin(), E = RegList.end(); I != E; ) {
3149       OS << *I;
3150       if (++I < E) OS << ", ";
3151     }
3152 
3153     OS << ">";
3154     break;
3155   }
3156   case k_VectorList:
3157     OS << "<vector_list " << VectorList.Count << " * "
3158        << VectorList.RegNum << ">";
3159     break;
3160   case k_VectorListAllLanes:
3161     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
3162        << VectorList.RegNum << ">";
3163     break;
3164   case k_VectorListIndexed:
3165     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
3166        << VectorList.Count << " * " << VectorList.RegNum << ">";
3167     break;
3168   case k_Token:
3169     OS << "'" << getToken() << "'";
3170     break;
3171   case k_VectorIndex:
3172     OS << "<vectorindex " << getVectorIndex() << ">";
3173     break;
3174   }
3175 }
3176 
3177 /// @name Auto-generated Match Functions
3178 /// {
3179 
3180 static unsigned MatchRegisterName(StringRef Name);
3181 
3182 /// }
3183 
3184 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
3185                                  SMLoc &StartLoc, SMLoc &EndLoc) {
3186   const AsmToken &Tok = getParser().getTok();
3187   StartLoc = Tok.getLoc();
3188   EndLoc = Tok.getEndLoc();
3189   RegNo = tryParseRegister();
3190 
3191   return (RegNo == (unsigned)-1);
3192 }
3193 
3194 /// Try to parse a register name.  The token must be an Identifier when called,
3195 /// and if it is a register name the token is eaten and the register number is
3196 /// returned.  Otherwise return -1.
3197 int ARMAsmParser::tryParseRegister() {
3198   MCAsmParser &Parser = getParser();
3199   const AsmToken &Tok = Parser.getTok();
3200   if (Tok.isNot(AsmToken::Identifier)) return -1;
3201 
3202   std::string lowerCase = Tok.getString().lower();
3203   unsigned RegNum = MatchRegisterName(lowerCase);
3204   if (!RegNum) {
3205     RegNum = StringSwitch<unsigned>(lowerCase)
3206       .Case("r13", ARM::SP)
3207       .Case("r14", ARM::LR)
3208       .Case("r15", ARM::PC)
3209       .Case("ip", ARM::R12)
3210       // Additional register name aliases for 'gas' compatibility.
3211       .Case("a1", ARM::R0)
3212       .Case("a2", ARM::R1)
3213       .Case("a3", ARM::R2)
3214       .Case("a4", ARM::R3)
3215       .Case("v1", ARM::R4)
3216       .Case("v2", ARM::R5)
3217       .Case("v3", ARM::R6)
3218       .Case("v4", ARM::R7)
3219       .Case("v5", ARM::R8)
3220       .Case("v6", ARM::R9)
3221       .Case("v7", ARM::R10)
3222       .Case("v8", ARM::R11)
3223       .Case("sb", ARM::R9)
3224       .Case("sl", ARM::R10)
3225       .Case("fp", ARM::R11)
3226       .Default(0);
3227   }
3228   if (!RegNum) {
3229     // Check for aliases registered via .req. Canonicalize to lower case.
3230     // That's more consistent since register names are case insensitive, and
3231     // it's how the original entry was passed in from MC/MCParser/AsmParser.
3232     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
3233     // If no match, return failure.
3234     if (Entry == RegisterReqs.end())
3235       return -1;
3236     Parser.Lex(); // Eat identifier token.
3237     return Entry->getValue();
3238   }
3239 
3240   // Some FPUs only have 16 D registers, so D16-D31 are invalid
3241   if (hasD16() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
3242     return -1;
3243 
3244   Parser.Lex(); // Eat identifier token.
3245 
3246   return RegNum;
3247 }
3248 
3249 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
3250 // If a recoverable error occurs, return 1. If an irrecoverable error
3251 // occurs, return -1. An irrecoverable error is one where tokens have been
3252 // consumed in the process of trying to parse the shifter (i.e., when it is
3253 // indeed a shifter operand, but malformed).
3254 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
3255   MCAsmParser &Parser = getParser();
3256   SMLoc S = Parser.getTok().getLoc();
3257   const AsmToken &Tok = Parser.getTok();
3258   if (Tok.isNot(AsmToken::Identifier))
3259     return -1;
3260 
3261   std::string lowerCase = Tok.getString().lower();
3262   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
3263       .Case("asl", ARM_AM::lsl)
3264       .Case("lsl", ARM_AM::lsl)
3265       .Case("lsr", ARM_AM::lsr)
3266       .Case("asr", ARM_AM::asr)
3267       .Case("ror", ARM_AM::ror)
3268       .Case("rrx", ARM_AM::rrx)
3269       .Default(ARM_AM::no_shift);
3270 
3271   if (ShiftTy == ARM_AM::no_shift)
3272     return 1;
3273 
3274   Parser.Lex(); // Eat the operator.
3275 
3276   // The source register for the shift has already been added to the
3277   // operand list, so we need to pop it off and combine it into the shifted
3278   // register operand instead.
3279   std::unique_ptr<ARMOperand> PrevOp(
3280       (ARMOperand *)Operands.pop_back_val().release());
3281   if (!PrevOp->isReg())
3282     return Error(PrevOp->getStartLoc(), "shift must be of a register");
3283   int SrcReg = PrevOp->getReg();
3284 
3285   SMLoc EndLoc;
3286   int64_t Imm = 0;
3287   int ShiftReg = 0;
3288   if (ShiftTy == ARM_AM::rrx) {
3289     // RRX Doesn't have an explicit shift amount. The encoder expects
3290     // the shift register to be the same as the source register. Seems odd,
3291     // but OK.
3292     ShiftReg = SrcReg;
3293   } else {
3294     // Figure out if this is shifted by a constant or a register (for non-RRX).
3295     if (Parser.getTok().is(AsmToken::Hash) ||
3296         Parser.getTok().is(AsmToken::Dollar)) {
3297       Parser.Lex(); // Eat hash.
3298       SMLoc ImmLoc = Parser.getTok().getLoc();
3299       const MCExpr *ShiftExpr = nullptr;
3300       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
3301         Error(ImmLoc, "invalid immediate shift value");
3302         return -1;
3303       }
3304       // The expression must be evaluatable as an immediate.
3305       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
3306       if (!CE) {
3307         Error(ImmLoc, "invalid immediate shift value");
3308         return -1;
3309       }
3310       // Range check the immediate.
3311       // lsl, ror: 0 <= imm <= 31
3312       // lsr, asr: 0 <= imm <= 32
3313       Imm = CE->getValue();
3314       if (Imm < 0 ||
3315           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
3316           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
3317         Error(ImmLoc, "immediate shift value out of range");
3318         return -1;
3319       }
3320       // shift by zero is a nop. Always send it through as lsl.
3321       // ('as' compatibility)
3322       if (Imm == 0)
3323         ShiftTy = ARM_AM::lsl;
3324     } else if (Parser.getTok().is(AsmToken::Identifier)) {
3325       SMLoc L = Parser.getTok().getLoc();
3326       EndLoc = Parser.getTok().getEndLoc();
3327       ShiftReg = tryParseRegister();
3328       if (ShiftReg == -1) {
3329         Error(L, "expected immediate or register in shift operand");
3330         return -1;
3331       }
3332     } else {
3333       Error(Parser.getTok().getLoc(),
3334             "expected immediate or register in shift operand");
3335       return -1;
3336     }
3337   }
3338 
3339   if (ShiftReg && ShiftTy != ARM_AM::rrx)
3340     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
3341                                                          ShiftReg, Imm,
3342                                                          S, EndLoc));
3343   else
3344     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
3345                                                           S, EndLoc));
3346 
3347   return 0;
3348 }
3349 
3350 /// Try to parse a register name.  The token must be an Identifier when called.
3351 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3352 /// if there is a "writeback". 'true' if it's not a register.
3353 ///
3354 /// TODO this is likely to change to allow different register types and or to
3355 /// parse for a specific register type.
3356 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3357   MCAsmParser &Parser = getParser();
3358   const AsmToken &RegTok = Parser.getTok();
3359   int RegNo = tryParseRegister();
3360   if (RegNo == -1)
3361     return true;
3362 
3363   Operands.push_back(ARMOperand::CreateReg(RegNo, RegTok.getLoc(),
3364                                            RegTok.getEndLoc()));
3365 
3366   const AsmToken &ExclaimTok = Parser.getTok();
3367   if (ExclaimTok.is(AsmToken::Exclaim)) {
3368     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3369                                                ExclaimTok.getLoc()));
3370     Parser.Lex(); // Eat exclaim token
3371     return false;
3372   }
3373 
3374   // Also check for an index operand. This is only legal for vector registers,
3375   // but that'll get caught OK in operand matching, so we don't need to
3376   // explicitly filter everything else out here.
3377   if (Parser.getTok().is(AsmToken::LBrac)) {
3378     SMLoc SIdx = Parser.getTok().getLoc();
3379     Parser.Lex(); // Eat left bracket token.
3380 
3381     const MCExpr *ImmVal;
3382     if (getParser().parseExpression(ImmVal))
3383       return true;
3384     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3385     if (!MCE)
3386       return TokError("immediate value expected for vector index");
3387 
3388     if (Parser.getTok().isNot(AsmToken::RBrac))
3389       return Error(Parser.getTok().getLoc(), "']' expected");
3390 
3391     SMLoc E = Parser.getTok().getEndLoc();
3392     Parser.Lex(); // Eat right bracket token.
3393 
3394     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3395                                                      SIdx, E,
3396                                                      getContext()));
3397   }
3398 
3399   return false;
3400 }
3401 
3402 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3403 /// instruction with a symbolic operand name.
3404 /// We accept "crN" syntax for GAS compatibility.
3405 /// <operand-name> ::= <prefix><number>
3406 /// If CoprocOp is 'c', then:
3407 ///   <prefix> ::= c | cr
3408 /// If CoprocOp is 'p', then :
3409 ///   <prefix> ::= p
3410 /// <number> ::= integer in range [0, 15]
3411 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3412   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3413   // but efficient.
3414   if (Name.size() < 2 || Name[0] != CoprocOp)
3415     return -1;
3416   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3417 
3418   switch (Name.size()) {
3419   default: return -1;
3420   case 1:
3421     switch (Name[0]) {
3422     default:  return -1;
3423     case '0': return 0;
3424     case '1': return 1;
3425     case '2': return 2;
3426     case '3': return 3;
3427     case '4': return 4;
3428     case '5': return 5;
3429     case '6': return 6;
3430     case '7': return 7;
3431     case '8': return 8;
3432     case '9': return 9;
3433     }
3434   case 2:
3435     if (Name[0] != '1')
3436       return -1;
3437     switch (Name[1]) {
3438     default:  return -1;
3439     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3440     // However, old cores (v5/v6) did use them in that way.
3441     case '0': return 10;
3442     case '1': return 11;
3443     case '2': return 12;
3444     case '3': return 13;
3445     case '4': return 14;
3446     case '5': return 15;
3447     }
3448   }
3449 }
3450 
3451 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3452 OperandMatchResultTy
3453 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3454   MCAsmParser &Parser = getParser();
3455   SMLoc S = Parser.getTok().getLoc();
3456   const AsmToken &Tok = Parser.getTok();
3457   if (!Tok.is(AsmToken::Identifier))
3458     return MatchOperand_NoMatch;
3459   unsigned CC = ARMCondCodeFromString(Tok.getString());
3460   if (CC == ~0U)
3461     return MatchOperand_NoMatch;
3462   Parser.Lex(); // Eat the token.
3463 
3464   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3465 
3466   return MatchOperand_Success;
3467 }
3468 
3469 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3470 /// token must be an Identifier when called, and if it is a coprocessor
3471 /// number, the token is eaten and the operand is added to the operand list.
3472 OperandMatchResultTy
3473 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3474   MCAsmParser &Parser = getParser();
3475   SMLoc S = Parser.getTok().getLoc();
3476   const AsmToken &Tok = Parser.getTok();
3477   if (Tok.isNot(AsmToken::Identifier))
3478     return MatchOperand_NoMatch;
3479 
3480   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
3481   if (Num == -1)
3482     return MatchOperand_NoMatch;
3483   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
3484   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
3485     return MatchOperand_NoMatch;
3486 
3487   Parser.Lex(); // Eat identifier token.
3488   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
3489   return MatchOperand_Success;
3490 }
3491 
3492 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
3493 /// token must be an Identifier when called, and if it is a coprocessor
3494 /// number, the token is eaten and the operand is added to the operand list.
3495 OperandMatchResultTy
3496 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
3497   MCAsmParser &Parser = getParser();
3498   SMLoc S = Parser.getTok().getLoc();
3499   const AsmToken &Tok = Parser.getTok();
3500   if (Tok.isNot(AsmToken::Identifier))
3501     return MatchOperand_NoMatch;
3502 
3503   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
3504   if (Reg == -1)
3505     return MatchOperand_NoMatch;
3506 
3507   Parser.Lex(); // Eat identifier token.
3508   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
3509   return MatchOperand_Success;
3510 }
3511 
3512 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
3513 /// coproc_option : '{' imm0_255 '}'
3514 OperandMatchResultTy
3515 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
3516   MCAsmParser &Parser = getParser();
3517   SMLoc S = Parser.getTok().getLoc();
3518 
3519   // If this isn't a '{', this isn't a coprocessor immediate operand.
3520   if (Parser.getTok().isNot(AsmToken::LCurly))
3521     return MatchOperand_NoMatch;
3522   Parser.Lex(); // Eat the '{'
3523 
3524   const MCExpr *Expr;
3525   SMLoc Loc = Parser.getTok().getLoc();
3526   if (getParser().parseExpression(Expr)) {
3527     Error(Loc, "illegal expression");
3528     return MatchOperand_ParseFail;
3529   }
3530   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3531   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
3532     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
3533     return MatchOperand_ParseFail;
3534   }
3535   int Val = CE->getValue();
3536 
3537   // Check for and consume the closing '}'
3538   if (Parser.getTok().isNot(AsmToken::RCurly))
3539     return MatchOperand_ParseFail;
3540   SMLoc E = Parser.getTok().getEndLoc();
3541   Parser.Lex(); // Eat the '}'
3542 
3543   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
3544   return MatchOperand_Success;
3545 }
3546 
3547 // For register list parsing, we need to map from raw GPR register numbering
3548 // to the enumeration values. The enumeration values aren't sorted by
3549 // register number due to our using "sp", "lr" and "pc" as canonical names.
3550 static unsigned getNextRegister(unsigned Reg) {
3551   // If this is a GPR, we need to do it manually, otherwise we can rely
3552   // on the sort ordering of the enumeration since the other reg-classes
3553   // are sane.
3554   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3555     return Reg + 1;
3556   switch(Reg) {
3557   default: llvm_unreachable("Invalid GPR number!");
3558   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
3559   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
3560   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
3561   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
3562   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
3563   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
3564   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
3565   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
3566   }
3567 }
3568 
3569 /// Parse a register list.
3570 bool ARMAsmParser::parseRegisterList(OperandVector &Operands) {
3571   MCAsmParser &Parser = getParser();
3572   if (Parser.getTok().isNot(AsmToken::LCurly))
3573     return TokError("Token is not a Left Curly Brace");
3574   SMLoc S = Parser.getTok().getLoc();
3575   Parser.Lex(); // Eat '{' token.
3576   SMLoc RegLoc = Parser.getTok().getLoc();
3577 
3578   // Check the first register in the list to see what register class
3579   // this is a list of.
3580   int Reg = tryParseRegister();
3581   if (Reg == -1)
3582     return Error(RegLoc, "register expected");
3583 
3584   // The reglist instructions have at most 16 registers, so reserve
3585   // space for that many.
3586   int EReg = 0;
3587   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
3588 
3589   // Allow Q regs and just interpret them as the two D sub-registers.
3590   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3591     Reg = getDRegFromQReg(Reg);
3592     EReg = MRI->getEncodingValue(Reg);
3593     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3594     ++Reg;
3595   }
3596   const MCRegisterClass *RC;
3597   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3598     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
3599   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
3600     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
3601   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
3602     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
3603   else
3604     return Error(RegLoc, "invalid register in register list");
3605 
3606   // Store the register.
3607   EReg = MRI->getEncodingValue(Reg);
3608   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3609 
3610   // This starts immediately after the first register token in the list,
3611   // so we can see either a comma or a minus (range separator) as a legal
3612   // next token.
3613   while (Parser.getTok().is(AsmToken::Comma) ||
3614          Parser.getTok().is(AsmToken::Minus)) {
3615     if (Parser.getTok().is(AsmToken::Minus)) {
3616       Parser.Lex(); // Eat the minus.
3617       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3618       int EndReg = tryParseRegister();
3619       if (EndReg == -1)
3620         return Error(AfterMinusLoc, "register expected");
3621       // Allow Q regs and just interpret them as the two D sub-registers.
3622       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3623         EndReg = getDRegFromQReg(EndReg) + 1;
3624       // If the register is the same as the start reg, there's nothing
3625       // more to do.
3626       if (Reg == EndReg)
3627         continue;
3628       // The register must be in the same register class as the first.
3629       if (!RC->contains(EndReg))
3630         return Error(AfterMinusLoc, "invalid register in register list");
3631       // Ranges must go from low to high.
3632       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
3633         return Error(AfterMinusLoc, "bad range in register list");
3634 
3635       // Add all the registers in the range to the register list.
3636       while (Reg != EndReg) {
3637         Reg = getNextRegister(Reg);
3638         EReg = MRI->getEncodingValue(Reg);
3639         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3640       }
3641       continue;
3642     }
3643     Parser.Lex(); // Eat the comma.
3644     RegLoc = Parser.getTok().getLoc();
3645     int OldReg = Reg;
3646     const AsmToken RegTok = Parser.getTok();
3647     Reg = tryParseRegister();
3648     if (Reg == -1)
3649       return Error(RegLoc, "register expected");
3650     // Allow Q regs and just interpret them as the two D sub-registers.
3651     bool isQReg = false;
3652     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3653       Reg = getDRegFromQReg(Reg);
3654       isQReg = true;
3655     }
3656     // The register must be in the same register class as the first.
3657     if (!RC->contains(Reg))
3658       return Error(RegLoc, "invalid register in register list");
3659     // List must be monotonically increasing.
3660     if (MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
3661       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3662         Warning(RegLoc, "register list not in ascending order");
3663       else
3664         return Error(RegLoc, "register list not in ascending order");
3665     }
3666     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
3667       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
3668               ") in register list");
3669       continue;
3670     }
3671     // VFP register lists must also be contiguous.
3672     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
3673         Reg != OldReg + 1)
3674       return Error(RegLoc, "non-contiguous register range");
3675     EReg = MRI->getEncodingValue(Reg);
3676     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3677     if (isQReg) {
3678       EReg = MRI->getEncodingValue(++Reg);
3679       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3680     }
3681   }
3682 
3683   if (Parser.getTok().isNot(AsmToken::RCurly))
3684     return Error(Parser.getTok().getLoc(), "'}' expected");
3685   SMLoc E = Parser.getTok().getEndLoc();
3686   Parser.Lex(); // Eat '}' token.
3687 
3688   // Push the register list operand.
3689   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
3690 
3691   // The ARM system instruction variants for LDM/STM have a '^' token here.
3692   if (Parser.getTok().is(AsmToken::Caret)) {
3693     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
3694     Parser.Lex(); // Eat '^' token.
3695   }
3696 
3697   return false;
3698 }
3699 
3700 // Helper function to parse the lane index for vector lists.
3701 OperandMatchResultTy ARMAsmParser::
3702 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
3703   MCAsmParser &Parser = getParser();
3704   Index = 0; // Always return a defined index value.
3705   if (Parser.getTok().is(AsmToken::LBrac)) {
3706     Parser.Lex(); // Eat the '['.
3707     if (Parser.getTok().is(AsmToken::RBrac)) {
3708       // "Dn[]" is the 'all lanes' syntax.
3709       LaneKind = AllLanes;
3710       EndLoc = Parser.getTok().getEndLoc();
3711       Parser.Lex(); // Eat the ']'.
3712       return MatchOperand_Success;
3713     }
3714 
3715     // There's an optional '#' token here. Normally there wouldn't be, but
3716     // inline assemble puts one in, and it's friendly to accept that.
3717     if (Parser.getTok().is(AsmToken::Hash))
3718       Parser.Lex(); // Eat '#' or '$'.
3719 
3720     const MCExpr *LaneIndex;
3721     SMLoc Loc = Parser.getTok().getLoc();
3722     if (getParser().parseExpression(LaneIndex)) {
3723       Error(Loc, "illegal expression");
3724       return MatchOperand_ParseFail;
3725     }
3726     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
3727     if (!CE) {
3728       Error(Loc, "lane index must be empty or an integer");
3729       return MatchOperand_ParseFail;
3730     }
3731     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3732       Error(Parser.getTok().getLoc(), "']' expected");
3733       return MatchOperand_ParseFail;
3734     }
3735     EndLoc = Parser.getTok().getEndLoc();
3736     Parser.Lex(); // Eat the ']'.
3737     int64_t Val = CE->getValue();
3738 
3739     // FIXME: Make this range check context sensitive for .8, .16, .32.
3740     if (Val < 0 || Val > 7) {
3741       Error(Parser.getTok().getLoc(), "lane index out of range");
3742       return MatchOperand_ParseFail;
3743     }
3744     Index = Val;
3745     LaneKind = IndexedLane;
3746     return MatchOperand_Success;
3747   }
3748   LaneKind = NoLanes;
3749   return MatchOperand_Success;
3750 }
3751 
3752 // parse a vector register list
3753 OperandMatchResultTy
3754 ARMAsmParser::parseVectorList(OperandVector &Operands) {
3755   MCAsmParser &Parser = getParser();
3756   VectorLaneTy LaneKind;
3757   unsigned LaneIndex;
3758   SMLoc S = Parser.getTok().getLoc();
3759   // As an extension (to match gas), support a plain D register or Q register
3760   // (without encosing curly braces) as a single or double entry list,
3761   // respectively.
3762   if (Parser.getTok().is(AsmToken::Identifier)) {
3763     SMLoc E = Parser.getTok().getEndLoc();
3764     int Reg = tryParseRegister();
3765     if (Reg == -1)
3766       return MatchOperand_NoMatch;
3767     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
3768       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3769       if (Res != MatchOperand_Success)
3770         return Res;
3771       switch (LaneKind) {
3772       case NoLanes:
3773         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
3774         break;
3775       case AllLanes:
3776         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
3777                                                                 S, E));
3778         break;
3779       case IndexedLane:
3780         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
3781                                                                LaneIndex,
3782                                                                false, S, E));
3783         break;
3784       }
3785       return MatchOperand_Success;
3786     }
3787     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3788       Reg = getDRegFromQReg(Reg);
3789       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3790       if (Res != MatchOperand_Success)
3791         return Res;
3792       switch (LaneKind) {
3793       case NoLanes:
3794         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3795                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3796         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
3797         break;
3798       case AllLanes:
3799         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3800                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3801         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
3802                                                                 S, E));
3803         break;
3804       case IndexedLane:
3805         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
3806                                                                LaneIndex,
3807                                                                false, S, E));
3808         break;
3809       }
3810       return MatchOperand_Success;
3811     }
3812     Error(S, "vector register expected");
3813     return MatchOperand_ParseFail;
3814   }
3815 
3816   if (Parser.getTok().isNot(AsmToken::LCurly))
3817     return MatchOperand_NoMatch;
3818 
3819   Parser.Lex(); // Eat '{' token.
3820   SMLoc RegLoc = Parser.getTok().getLoc();
3821 
3822   int Reg = tryParseRegister();
3823   if (Reg == -1) {
3824     Error(RegLoc, "register expected");
3825     return MatchOperand_ParseFail;
3826   }
3827   unsigned Count = 1;
3828   int Spacing = 0;
3829   unsigned FirstReg = Reg;
3830   // The list is of D registers, but we also allow Q regs and just interpret
3831   // them as the two D sub-registers.
3832   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3833     FirstReg = Reg = getDRegFromQReg(Reg);
3834     Spacing = 1; // double-spacing requires explicit D registers, otherwise
3835                  // it's ambiguous with four-register single spaced.
3836     ++Reg;
3837     ++Count;
3838   }
3839 
3840   SMLoc E;
3841   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
3842     return MatchOperand_ParseFail;
3843 
3844   while (Parser.getTok().is(AsmToken::Comma) ||
3845          Parser.getTok().is(AsmToken::Minus)) {
3846     if (Parser.getTok().is(AsmToken::Minus)) {
3847       if (!Spacing)
3848         Spacing = 1; // Register range implies a single spaced list.
3849       else if (Spacing == 2) {
3850         Error(Parser.getTok().getLoc(),
3851               "sequential registers in double spaced list");
3852         return MatchOperand_ParseFail;
3853       }
3854       Parser.Lex(); // Eat the minus.
3855       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3856       int EndReg = tryParseRegister();
3857       if (EndReg == -1) {
3858         Error(AfterMinusLoc, "register expected");
3859         return MatchOperand_ParseFail;
3860       }
3861       // Allow Q regs and just interpret them as the two D sub-registers.
3862       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3863         EndReg = getDRegFromQReg(EndReg) + 1;
3864       // If the register is the same as the start reg, there's nothing
3865       // more to do.
3866       if (Reg == EndReg)
3867         continue;
3868       // The register must be in the same register class as the first.
3869       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
3870         Error(AfterMinusLoc, "invalid register in register list");
3871         return MatchOperand_ParseFail;
3872       }
3873       // Ranges must go from low to high.
3874       if (Reg > EndReg) {
3875         Error(AfterMinusLoc, "bad range in register list");
3876         return MatchOperand_ParseFail;
3877       }
3878       // Parse the lane specifier if present.
3879       VectorLaneTy NextLaneKind;
3880       unsigned NextLaneIndex;
3881       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3882           MatchOperand_Success)
3883         return MatchOperand_ParseFail;
3884       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3885         Error(AfterMinusLoc, "mismatched lane index in register list");
3886         return MatchOperand_ParseFail;
3887       }
3888 
3889       // Add all the registers in the range to the register list.
3890       Count += EndReg - Reg;
3891       Reg = EndReg;
3892       continue;
3893     }
3894     Parser.Lex(); // Eat the comma.
3895     RegLoc = Parser.getTok().getLoc();
3896     int OldReg = Reg;
3897     Reg = tryParseRegister();
3898     if (Reg == -1) {
3899       Error(RegLoc, "register expected");
3900       return MatchOperand_ParseFail;
3901     }
3902     // vector register lists must be contiguous.
3903     // It's OK to use the enumeration values directly here rather, as the
3904     // VFP register classes have the enum sorted properly.
3905     //
3906     // The list is of D registers, but we also allow Q regs and just interpret
3907     // them as the two D sub-registers.
3908     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3909       if (!Spacing)
3910         Spacing = 1; // Register range implies a single spaced list.
3911       else if (Spacing == 2) {
3912         Error(RegLoc,
3913               "invalid register in double-spaced list (must be 'D' register')");
3914         return MatchOperand_ParseFail;
3915       }
3916       Reg = getDRegFromQReg(Reg);
3917       if (Reg != OldReg + 1) {
3918         Error(RegLoc, "non-contiguous register range");
3919         return MatchOperand_ParseFail;
3920       }
3921       ++Reg;
3922       Count += 2;
3923       // Parse the lane specifier if present.
3924       VectorLaneTy NextLaneKind;
3925       unsigned NextLaneIndex;
3926       SMLoc LaneLoc = Parser.getTok().getLoc();
3927       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3928           MatchOperand_Success)
3929         return MatchOperand_ParseFail;
3930       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3931         Error(LaneLoc, "mismatched lane index in register list");
3932         return MatchOperand_ParseFail;
3933       }
3934       continue;
3935     }
3936     // Normal D register.
3937     // Figure out the register spacing (single or double) of the list if
3938     // we don't know it already.
3939     if (!Spacing)
3940       Spacing = 1 + (Reg == OldReg + 2);
3941 
3942     // Just check that it's contiguous and keep going.
3943     if (Reg != OldReg + Spacing) {
3944       Error(RegLoc, "non-contiguous register range");
3945       return MatchOperand_ParseFail;
3946     }
3947     ++Count;
3948     // Parse the lane specifier if present.
3949     VectorLaneTy NextLaneKind;
3950     unsigned NextLaneIndex;
3951     SMLoc EndLoc = Parser.getTok().getLoc();
3952     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
3953       return MatchOperand_ParseFail;
3954     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3955       Error(EndLoc, "mismatched lane index in register list");
3956       return MatchOperand_ParseFail;
3957     }
3958   }
3959 
3960   if (Parser.getTok().isNot(AsmToken::RCurly)) {
3961     Error(Parser.getTok().getLoc(), "'}' expected");
3962     return MatchOperand_ParseFail;
3963   }
3964   E = Parser.getTok().getEndLoc();
3965   Parser.Lex(); // Eat '}' token.
3966 
3967   switch (LaneKind) {
3968   case NoLanes:
3969     // Two-register operands have been converted to the
3970     // composite register classes.
3971     if (Count == 2) {
3972       const MCRegisterClass *RC = (Spacing == 1) ?
3973         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3974         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3975       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3976     }
3977     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
3978                                                     (Spacing == 2), S, E));
3979     break;
3980   case AllLanes:
3981     // Two-register operands have been converted to the
3982     // composite register classes.
3983     if (Count == 2) {
3984       const MCRegisterClass *RC = (Spacing == 1) ?
3985         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3986         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3987       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3988     }
3989     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
3990                                                             (Spacing == 2),
3991                                                             S, E));
3992     break;
3993   case IndexedLane:
3994     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
3995                                                            LaneIndex,
3996                                                            (Spacing == 2),
3997                                                            S, E));
3998     break;
3999   }
4000   return MatchOperand_Success;
4001 }
4002 
4003 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
4004 OperandMatchResultTy
4005 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
4006   MCAsmParser &Parser = getParser();
4007   SMLoc S = Parser.getTok().getLoc();
4008   const AsmToken &Tok = Parser.getTok();
4009   unsigned Opt;
4010 
4011   if (Tok.is(AsmToken::Identifier)) {
4012     StringRef OptStr = Tok.getString();
4013 
4014     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
4015       .Case("sy",    ARM_MB::SY)
4016       .Case("st",    ARM_MB::ST)
4017       .Case("ld",    ARM_MB::LD)
4018       .Case("sh",    ARM_MB::ISH)
4019       .Case("ish",   ARM_MB::ISH)
4020       .Case("shst",  ARM_MB::ISHST)
4021       .Case("ishst", ARM_MB::ISHST)
4022       .Case("ishld", ARM_MB::ISHLD)
4023       .Case("nsh",   ARM_MB::NSH)
4024       .Case("un",    ARM_MB::NSH)
4025       .Case("nshst", ARM_MB::NSHST)
4026       .Case("nshld", ARM_MB::NSHLD)
4027       .Case("unst",  ARM_MB::NSHST)
4028       .Case("osh",   ARM_MB::OSH)
4029       .Case("oshst", ARM_MB::OSHST)
4030       .Case("oshld", ARM_MB::OSHLD)
4031       .Default(~0U);
4032 
4033     // ishld, oshld, nshld and ld are only available from ARMv8.
4034     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
4035                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
4036       Opt = ~0U;
4037 
4038     if (Opt == ~0U)
4039       return MatchOperand_NoMatch;
4040 
4041     Parser.Lex(); // Eat identifier token.
4042   } else if (Tok.is(AsmToken::Hash) ||
4043              Tok.is(AsmToken::Dollar) ||
4044              Tok.is(AsmToken::Integer)) {
4045     if (Parser.getTok().isNot(AsmToken::Integer))
4046       Parser.Lex(); // Eat '#' or '$'.
4047     SMLoc Loc = Parser.getTok().getLoc();
4048 
4049     const MCExpr *MemBarrierID;
4050     if (getParser().parseExpression(MemBarrierID)) {
4051       Error(Loc, "illegal expression");
4052       return MatchOperand_ParseFail;
4053     }
4054 
4055     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
4056     if (!CE) {
4057       Error(Loc, "constant expression expected");
4058       return MatchOperand_ParseFail;
4059     }
4060 
4061     int Val = CE->getValue();
4062     if (Val & ~0xf) {
4063       Error(Loc, "immediate value out of range");
4064       return MatchOperand_ParseFail;
4065     }
4066 
4067     Opt = ARM_MB::RESERVED_0 + Val;
4068   } else
4069     return MatchOperand_ParseFail;
4070 
4071   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
4072   return MatchOperand_Success;
4073 }
4074 
4075 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
4076 OperandMatchResultTy
4077 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
4078   MCAsmParser &Parser = getParser();
4079   SMLoc S = Parser.getTok().getLoc();
4080   const AsmToken &Tok = Parser.getTok();
4081   unsigned Opt;
4082 
4083   if (Tok.is(AsmToken::Identifier)) {
4084     StringRef OptStr = Tok.getString();
4085 
4086     if (OptStr.equals_lower("sy"))
4087       Opt = ARM_ISB::SY;
4088     else
4089       return MatchOperand_NoMatch;
4090 
4091     Parser.Lex(); // Eat identifier token.
4092   } else if (Tok.is(AsmToken::Hash) ||
4093              Tok.is(AsmToken::Dollar) ||
4094              Tok.is(AsmToken::Integer)) {
4095     if (Parser.getTok().isNot(AsmToken::Integer))
4096       Parser.Lex(); // Eat '#' or '$'.
4097     SMLoc Loc = Parser.getTok().getLoc();
4098 
4099     const MCExpr *ISBarrierID;
4100     if (getParser().parseExpression(ISBarrierID)) {
4101       Error(Loc, "illegal expression");
4102       return MatchOperand_ParseFail;
4103     }
4104 
4105     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
4106     if (!CE) {
4107       Error(Loc, "constant expression expected");
4108       return MatchOperand_ParseFail;
4109     }
4110 
4111     int Val = CE->getValue();
4112     if (Val & ~0xf) {
4113       Error(Loc, "immediate value out of range");
4114       return MatchOperand_ParseFail;
4115     }
4116 
4117     Opt = ARM_ISB::RESERVED_0 + Val;
4118   } else
4119     return MatchOperand_ParseFail;
4120 
4121   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
4122           (ARM_ISB::InstSyncBOpt)Opt, S));
4123   return MatchOperand_Success;
4124 }
4125 
4126 
4127 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
4128 OperandMatchResultTy
4129 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
4130   MCAsmParser &Parser = getParser();
4131   SMLoc S = Parser.getTok().getLoc();
4132   const AsmToken &Tok = Parser.getTok();
4133   if (!Tok.is(AsmToken::Identifier))
4134     return MatchOperand_NoMatch;
4135   StringRef IFlagsStr = Tok.getString();
4136 
4137   // An iflags string of "none" is interpreted to mean that none of the AIF
4138   // bits are set.  Not a terribly useful instruction, but a valid encoding.
4139   unsigned IFlags = 0;
4140   if (IFlagsStr != "none") {
4141         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
4142       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1).lower())
4143         .Case("a", ARM_PROC::A)
4144         .Case("i", ARM_PROC::I)
4145         .Case("f", ARM_PROC::F)
4146         .Default(~0U);
4147 
4148       // If some specific iflag is already set, it means that some letter is
4149       // present more than once, this is not acceptable.
4150       if (Flag == ~0U || (IFlags & Flag))
4151         return MatchOperand_NoMatch;
4152 
4153       IFlags |= Flag;
4154     }
4155   }
4156 
4157   Parser.Lex(); // Eat identifier token.
4158   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
4159   return MatchOperand_Success;
4160 }
4161 
4162 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
4163 OperandMatchResultTy
4164 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
4165   MCAsmParser &Parser = getParser();
4166   SMLoc S = Parser.getTok().getLoc();
4167   const AsmToken &Tok = Parser.getTok();
4168   if (!Tok.is(AsmToken::Identifier))
4169     return MatchOperand_NoMatch;
4170   StringRef Mask = Tok.getString();
4171 
4172   if (isMClass()) {
4173     auto TheReg = ARMSysReg::lookupMClassSysRegByName(Mask.lower());
4174     if (!TheReg || !TheReg->hasRequiredFeatures(getSTI().getFeatureBits()))
4175       return MatchOperand_NoMatch;
4176 
4177     unsigned SYSmvalue = TheReg->Encoding & 0xFFF;
4178 
4179     Parser.Lex(); // Eat identifier token.
4180     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
4181     return MatchOperand_Success;
4182   }
4183 
4184   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
4185   size_t Start = 0, Next = Mask.find('_');
4186   StringRef Flags = "";
4187   std::string SpecReg = Mask.slice(Start, Next).lower();
4188   if (Next != StringRef::npos)
4189     Flags = Mask.slice(Next+1, Mask.size());
4190 
4191   // FlagsVal contains the complete mask:
4192   // 3-0: Mask
4193   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4194   unsigned FlagsVal = 0;
4195 
4196   if (SpecReg == "apsr") {
4197     FlagsVal = StringSwitch<unsigned>(Flags)
4198     .Case("nzcvq",  0x8) // same as CPSR_f
4199     .Case("g",      0x4) // same as CPSR_s
4200     .Case("nzcvqg", 0xc) // same as CPSR_fs
4201     .Default(~0U);
4202 
4203     if (FlagsVal == ~0U) {
4204       if (!Flags.empty())
4205         return MatchOperand_NoMatch;
4206       else
4207         FlagsVal = 8; // No flag
4208     }
4209   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4210     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4211     if (Flags == "all" || Flags == "")
4212       Flags = "fc";
4213     for (int i = 0, e = Flags.size(); i != e; ++i) {
4214       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4215       .Case("c", 1)
4216       .Case("x", 2)
4217       .Case("s", 4)
4218       .Case("f", 8)
4219       .Default(~0U);
4220 
4221       // If some specific flag is already set, it means that some letter is
4222       // present more than once, this is not acceptable.
4223       if (Flag == ~0U || (FlagsVal & Flag))
4224         return MatchOperand_NoMatch;
4225       FlagsVal |= Flag;
4226     }
4227   } else // No match for special register.
4228     return MatchOperand_NoMatch;
4229 
4230   // Special register without flags is NOT equivalent to "fc" flags.
4231   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4232   // two lines would enable gas compatibility at the expense of breaking
4233   // round-tripping.
4234   //
4235   // if (!FlagsVal)
4236   //  FlagsVal = 0x9;
4237 
4238   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4239   if (SpecReg == "spsr")
4240     FlagsVal |= 16;
4241 
4242   Parser.Lex(); // Eat identifier token.
4243   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4244   return MatchOperand_Success;
4245 }
4246 
4247 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4248 /// use in the MRS/MSR instructions added to support virtualization.
4249 OperandMatchResultTy
4250 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4251   MCAsmParser &Parser = getParser();
4252   SMLoc S = Parser.getTok().getLoc();
4253   const AsmToken &Tok = Parser.getTok();
4254   if (!Tok.is(AsmToken::Identifier))
4255     return MatchOperand_NoMatch;
4256   StringRef RegName = Tok.getString();
4257 
4258   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegName.lower());
4259   if (!TheReg)
4260     return MatchOperand_NoMatch;
4261   unsigned Encoding = TheReg->Encoding;
4262 
4263   Parser.Lex(); // Eat identifier token.
4264   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4265   return MatchOperand_Success;
4266 }
4267 
4268 OperandMatchResultTy
4269 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4270                           int High) {
4271   MCAsmParser &Parser = getParser();
4272   const AsmToken &Tok = Parser.getTok();
4273   if (Tok.isNot(AsmToken::Identifier)) {
4274     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4275     return MatchOperand_ParseFail;
4276   }
4277   StringRef ShiftName = Tok.getString();
4278   std::string LowerOp = Op.lower();
4279   std::string UpperOp = Op.upper();
4280   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4281     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4282     return MatchOperand_ParseFail;
4283   }
4284   Parser.Lex(); // Eat shift type token.
4285 
4286   // There must be a '#' and a shift amount.
4287   if (Parser.getTok().isNot(AsmToken::Hash) &&
4288       Parser.getTok().isNot(AsmToken::Dollar)) {
4289     Error(Parser.getTok().getLoc(), "'#' expected");
4290     return MatchOperand_ParseFail;
4291   }
4292   Parser.Lex(); // Eat hash token.
4293 
4294   const MCExpr *ShiftAmount;
4295   SMLoc Loc = Parser.getTok().getLoc();
4296   SMLoc EndLoc;
4297   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4298     Error(Loc, "illegal expression");
4299     return MatchOperand_ParseFail;
4300   }
4301   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4302   if (!CE) {
4303     Error(Loc, "constant expression expected");
4304     return MatchOperand_ParseFail;
4305   }
4306   int Val = CE->getValue();
4307   if (Val < Low || Val > High) {
4308     Error(Loc, "immediate value out of range");
4309     return MatchOperand_ParseFail;
4310   }
4311 
4312   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4313 
4314   return MatchOperand_Success;
4315 }
4316 
4317 OperandMatchResultTy
4318 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4319   MCAsmParser &Parser = getParser();
4320   const AsmToken &Tok = Parser.getTok();
4321   SMLoc S = Tok.getLoc();
4322   if (Tok.isNot(AsmToken::Identifier)) {
4323     Error(S, "'be' or 'le' operand expected");
4324     return MatchOperand_ParseFail;
4325   }
4326   int Val = StringSwitch<int>(Tok.getString().lower())
4327     .Case("be", 1)
4328     .Case("le", 0)
4329     .Default(-1);
4330   Parser.Lex(); // Eat the token.
4331 
4332   if (Val == -1) {
4333     Error(S, "'be' or 'le' operand expected");
4334     return MatchOperand_ParseFail;
4335   }
4336   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4337                                                                   getContext()),
4338                                            S, Tok.getEndLoc()));
4339   return MatchOperand_Success;
4340 }
4341 
4342 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4343 /// instructions. Legal values are:
4344 ///     lsl #n  'n' in [0,31]
4345 ///     asr #n  'n' in [1,32]
4346 ///             n == 32 encoded as n == 0.
4347 OperandMatchResultTy
4348 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4349   MCAsmParser &Parser = getParser();
4350   const AsmToken &Tok = Parser.getTok();
4351   SMLoc S = Tok.getLoc();
4352   if (Tok.isNot(AsmToken::Identifier)) {
4353     Error(S, "shift operator 'asr' or 'lsl' expected");
4354     return MatchOperand_ParseFail;
4355   }
4356   StringRef ShiftName = Tok.getString();
4357   bool isASR;
4358   if (ShiftName == "lsl" || ShiftName == "LSL")
4359     isASR = false;
4360   else if (ShiftName == "asr" || ShiftName == "ASR")
4361     isASR = true;
4362   else {
4363     Error(S, "shift operator 'asr' or 'lsl' expected");
4364     return MatchOperand_ParseFail;
4365   }
4366   Parser.Lex(); // Eat the operator.
4367 
4368   // A '#' and a shift amount.
4369   if (Parser.getTok().isNot(AsmToken::Hash) &&
4370       Parser.getTok().isNot(AsmToken::Dollar)) {
4371     Error(Parser.getTok().getLoc(), "'#' expected");
4372     return MatchOperand_ParseFail;
4373   }
4374   Parser.Lex(); // Eat hash token.
4375   SMLoc ExLoc = Parser.getTok().getLoc();
4376 
4377   const MCExpr *ShiftAmount;
4378   SMLoc EndLoc;
4379   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4380     Error(ExLoc, "malformed shift expression");
4381     return MatchOperand_ParseFail;
4382   }
4383   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4384   if (!CE) {
4385     Error(ExLoc, "shift amount must be an immediate");
4386     return MatchOperand_ParseFail;
4387   }
4388 
4389   int64_t Val = CE->getValue();
4390   if (isASR) {
4391     // Shift amount must be in [1,32]
4392     if (Val < 1 || Val > 32) {
4393       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4394       return MatchOperand_ParseFail;
4395     }
4396     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4397     if (isThumb() && Val == 32) {
4398       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4399       return MatchOperand_ParseFail;
4400     }
4401     if (Val == 32) Val = 0;
4402   } else {
4403     // Shift amount must be in [1,32]
4404     if (Val < 0 || Val > 31) {
4405       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4406       return MatchOperand_ParseFail;
4407     }
4408   }
4409 
4410   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4411 
4412   return MatchOperand_Success;
4413 }
4414 
4415 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4416 /// of instructions. Legal values are:
4417 ///     ror #n  'n' in {0, 8, 16, 24}
4418 OperandMatchResultTy
4419 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4420   MCAsmParser &Parser = getParser();
4421   const AsmToken &Tok = Parser.getTok();
4422   SMLoc S = Tok.getLoc();
4423   if (Tok.isNot(AsmToken::Identifier))
4424     return MatchOperand_NoMatch;
4425   StringRef ShiftName = Tok.getString();
4426   if (ShiftName != "ror" && ShiftName != "ROR")
4427     return MatchOperand_NoMatch;
4428   Parser.Lex(); // Eat the operator.
4429 
4430   // A '#' and a rotate amount.
4431   if (Parser.getTok().isNot(AsmToken::Hash) &&
4432       Parser.getTok().isNot(AsmToken::Dollar)) {
4433     Error(Parser.getTok().getLoc(), "'#' expected");
4434     return MatchOperand_ParseFail;
4435   }
4436   Parser.Lex(); // Eat hash token.
4437   SMLoc ExLoc = Parser.getTok().getLoc();
4438 
4439   const MCExpr *ShiftAmount;
4440   SMLoc EndLoc;
4441   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4442     Error(ExLoc, "malformed rotate expression");
4443     return MatchOperand_ParseFail;
4444   }
4445   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4446   if (!CE) {
4447     Error(ExLoc, "rotate amount must be an immediate");
4448     return MatchOperand_ParseFail;
4449   }
4450 
4451   int64_t Val = CE->getValue();
4452   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4453   // normally, zero is represented in asm by omitting the rotate operand
4454   // entirely.
4455   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4456     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4457     return MatchOperand_ParseFail;
4458   }
4459 
4460   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4461 
4462   return MatchOperand_Success;
4463 }
4464 
4465 OperandMatchResultTy
4466 ARMAsmParser::parseModImm(OperandVector &Operands) {
4467   MCAsmParser &Parser = getParser();
4468   MCAsmLexer &Lexer = getLexer();
4469   int64_t Imm1, Imm2;
4470 
4471   SMLoc S = Parser.getTok().getLoc();
4472 
4473   // 1) A mod_imm operand can appear in the place of a register name:
4474   //   add r0, #mod_imm
4475   //   add r0, r0, #mod_imm
4476   // to correctly handle the latter, we bail out as soon as we see an
4477   // identifier.
4478   //
4479   // 2) Similarly, we do not want to parse into complex operands:
4480   //   mov r0, #mod_imm
4481   //   mov r0, :lower16:(_foo)
4482   if (Parser.getTok().is(AsmToken::Identifier) ||
4483       Parser.getTok().is(AsmToken::Colon))
4484     return MatchOperand_NoMatch;
4485 
4486   // Hash (dollar) is optional as per the ARMARM
4487   if (Parser.getTok().is(AsmToken::Hash) ||
4488       Parser.getTok().is(AsmToken::Dollar)) {
4489     // Avoid parsing into complex operands (#:)
4490     if (Lexer.peekTok().is(AsmToken::Colon))
4491       return MatchOperand_NoMatch;
4492 
4493     // Eat the hash (dollar)
4494     Parser.Lex();
4495   }
4496 
4497   SMLoc Sx1, Ex1;
4498   Sx1 = Parser.getTok().getLoc();
4499   const MCExpr *Imm1Exp;
4500   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4501     Error(Sx1, "malformed expression");
4502     return MatchOperand_ParseFail;
4503   }
4504 
4505   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4506 
4507   if (CE) {
4508     // Immediate must fit within 32-bits
4509     Imm1 = CE->getValue();
4510     int Enc = ARM_AM::getSOImmVal(Imm1);
4511     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4512       // We have a match!
4513       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4514                                                   (Enc & 0xF00) >> 7,
4515                                                   Sx1, Ex1));
4516       return MatchOperand_Success;
4517     }
4518 
4519     // We have parsed an immediate which is not for us, fallback to a plain
4520     // immediate. This can happen for instruction aliases. For an example,
4521     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
4522     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
4523     // instruction with a mod_imm operand. The alias is defined such that the
4524     // parser method is shared, that's why we have to do this here.
4525     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
4526       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4527       return MatchOperand_Success;
4528     }
4529   } else {
4530     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
4531     // MCFixup). Fallback to a plain immediate.
4532     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4533     return MatchOperand_Success;
4534   }
4535 
4536   // From this point onward, we expect the input to be a (#bits, #rot) pair
4537   if (Parser.getTok().isNot(AsmToken::Comma)) {
4538     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
4539     return MatchOperand_ParseFail;
4540   }
4541 
4542   if (Imm1 & ~0xFF) {
4543     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4544     return MatchOperand_ParseFail;
4545   }
4546 
4547   // Eat the comma
4548   Parser.Lex();
4549 
4550   // Repeat for #rot
4551   SMLoc Sx2, Ex2;
4552   Sx2 = Parser.getTok().getLoc();
4553 
4554   // Eat the optional hash (dollar)
4555   if (Parser.getTok().is(AsmToken::Hash) ||
4556       Parser.getTok().is(AsmToken::Dollar))
4557     Parser.Lex();
4558 
4559   const MCExpr *Imm2Exp;
4560   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4561     Error(Sx2, "malformed expression");
4562     return MatchOperand_ParseFail;
4563   }
4564 
4565   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4566 
4567   if (CE) {
4568     Imm2 = CE->getValue();
4569     if (!(Imm2 & ~0x1E)) {
4570       // We have a match!
4571       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4572       return MatchOperand_Success;
4573     }
4574     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4575     return MatchOperand_ParseFail;
4576   } else {
4577     Error(Sx2, "constant expression expected");
4578     return MatchOperand_ParseFail;
4579   }
4580 }
4581 
4582 OperandMatchResultTy
4583 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4584   MCAsmParser &Parser = getParser();
4585   SMLoc S = Parser.getTok().getLoc();
4586   // The bitfield descriptor is really two operands, the LSB and the width.
4587   if (Parser.getTok().isNot(AsmToken::Hash) &&
4588       Parser.getTok().isNot(AsmToken::Dollar)) {
4589     Error(Parser.getTok().getLoc(), "'#' expected");
4590     return MatchOperand_ParseFail;
4591   }
4592   Parser.Lex(); // Eat hash token.
4593 
4594   const MCExpr *LSBExpr;
4595   SMLoc E = Parser.getTok().getLoc();
4596   if (getParser().parseExpression(LSBExpr)) {
4597     Error(E, "malformed immediate expression");
4598     return MatchOperand_ParseFail;
4599   }
4600   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4601   if (!CE) {
4602     Error(E, "'lsb' operand must be an immediate");
4603     return MatchOperand_ParseFail;
4604   }
4605 
4606   int64_t LSB = CE->getValue();
4607   // The LSB must be in the range [0,31]
4608   if (LSB < 0 || LSB > 31) {
4609     Error(E, "'lsb' operand must be in the range [0,31]");
4610     return MatchOperand_ParseFail;
4611   }
4612   E = Parser.getTok().getLoc();
4613 
4614   // Expect another immediate operand.
4615   if (Parser.getTok().isNot(AsmToken::Comma)) {
4616     Error(Parser.getTok().getLoc(), "too few operands");
4617     return MatchOperand_ParseFail;
4618   }
4619   Parser.Lex(); // Eat hash token.
4620   if (Parser.getTok().isNot(AsmToken::Hash) &&
4621       Parser.getTok().isNot(AsmToken::Dollar)) {
4622     Error(Parser.getTok().getLoc(), "'#' expected");
4623     return MatchOperand_ParseFail;
4624   }
4625   Parser.Lex(); // Eat hash token.
4626 
4627   const MCExpr *WidthExpr;
4628   SMLoc EndLoc;
4629   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4630     Error(E, "malformed immediate expression");
4631     return MatchOperand_ParseFail;
4632   }
4633   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4634   if (!CE) {
4635     Error(E, "'width' operand must be an immediate");
4636     return MatchOperand_ParseFail;
4637   }
4638 
4639   int64_t Width = CE->getValue();
4640   // The LSB must be in the range [1,32-lsb]
4641   if (Width < 1 || Width > 32 - LSB) {
4642     Error(E, "'width' operand must be in the range [1,32-lsb]");
4643     return MatchOperand_ParseFail;
4644   }
4645 
4646   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4647 
4648   return MatchOperand_Success;
4649 }
4650 
4651 OperandMatchResultTy
4652 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4653   // Check for a post-index addressing register operand. Specifically:
4654   // postidx_reg := '+' register {, shift}
4655   //              | '-' register {, shift}
4656   //              | register {, shift}
4657 
4658   // This method must return MatchOperand_NoMatch without consuming any tokens
4659   // in the case where there is no match, as other alternatives take other
4660   // parse methods.
4661   MCAsmParser &Parser = getParser();
4662   AsmToken Tok = Parser.getTok();
4663   SMLoc S = Tok.getLoc();
4664   bool haveEaten = false;
4665   bool isAdd = true;
4666   if (Tok.is(AsmToken::Plus)) {
4667     Parser.Lex(); // Eat the '+' token.
4668     haveEaten = true;
4669   } else if (Tok.is(AsmToken::Minus)) {
4670     Parser.Lex(); // Eat the '-' token.
4671     isAdd = false;
4672     haveEaten = true;
4673   }
4674 
4675   SMLoc E = Parser.getTok().getEndLoc();
4676   int Reg = tryParseRegister();
4677   if (Reg == -1) {
4678     if (!haveEaten)
4679       return MatchOperand_NoMatch;
4680     Error(Parser.getTok().getLoc(), "register expected");
4681     return MatchOperand_ParseFail;
4682   }
4683 
4684   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4685   unsigned ShiftImm = 0;
4686   if (Parser.getTok().is(AsmToken::Comma)) {
4687     Parser.Lex(); // Eat the ','.
4688     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4689       return MatchOperand_ParseFail;
4690 
4691     // FIXME: Only approximates end...may include intervening whitespace.
4692     E = Parser.getTok().getLoc();
4693   }
4694 
4695   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4696                                                   ShiftImm, S, E));
4697 
4698   return MatchOperand_Success;
4699 }
4700 
4701 OperandMatchResultTy
4702 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4703   // Check for a post-index addressing register operand. Specifically:
4704   // am3offset := '+' register
4705   //              | '-' register
4706   //              | register
4707   //              | # imm
4708   //              | # + imm
4709   //              | # - imm
4710 
4711   // This method must return MatchOperand_NoMatch without consuming any tokens
4712   // in the case where there is no match, as other alternatives take other
4713   // parse methods.
4714   MCAsmParser &Parser = getParser();
4715   AsmToken Tok = Parser.getTok();
4716   SMLoc S = Tok.getLoc();
4717 
4718   // Do immediates first, as we always parse those if we have a '#'.
4719   if (Parser.getTok().is(AsmToken::Hash) ||
4720       Parser.getTok().is(AsmToken::Dollar)) {
4721     Parser.Lex(); // Eat '#' or '$'.
4722     // Explicitly look for a '-', as we need to encode negative zero
4723     // differently.
4724     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4725     const MCExpr *Offset;
4726     SMLoc E;
4727     if (getParser().parseExpression(Offset, E))
4728       return MatchOperand_ParseFail;
4729     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4730     if (!CE) {
4731       Error(S, "constant expression expected");
4732       return MatchOperand_ParseFail;
4733     }
4734     // Negative zero is encoded as the flag value
4735     // std::numeric_limits<int32_t>::min().
4736     int32_t Val = CE->getValue();
4737     if (isNegative && Val == 0)
4738       Val = std::numeric_limits<int32_t>::min();
4739 
4740     Operands.push_back(
4741       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
4742 
4743     return MatchOperand_Success;
4744   }
4745 
4746   bool haveEaten = false;
4747   bool isAdd = true;
4748   if (Tok.is(AsmToken::Plus)) {
4749     Parser.Lex(); // Eat the '+' token.
4750     haveEaten = true;
4751   } else if (Tok.is(AsmToken::Minus)) {
4752     Parser.Lex(); // Eat the '-' token.
4753     isAdd = false;
4754     haveEaten = true;
4755   }
4756 
4757   Tok = Parser.getTok();
4758   int Reg = tryParseRegister();
4759   if (Reg == -1) {
4760     if (!haveEaten)
4761       return MatchOperand_NoMatch;
4762     Error(Tok.getLoc(), "register expected");
4763     return MatchOperand_ParseFail;
4764   }
4765 
4766   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4767                                                   0, S, Tok.getEndLoc()));
4768 
4769   return MatchOperand_Success;
4770 }
4771 
4772 /// Convert parsed operands to MCInst.  Needed here because this instruction
4773 /// only has two register operands, but multiplication is commutative so
4774 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4775 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4776                                     const OperandVector &Operands) {
4777   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4778   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4779   // If we have a three-operand form, make sure to set Rn to be the operand
4780   // that isn't the same as Rd.
4781   unsigned RegOp = 4;
4782   if (Operands.size() == 6 &&
4783       ((ARMOperand &)*Operands[4]).getReg() ==
4784           ((ARMOperand &)*Operands[3]).getReg())
4785     RegOp = 5;
4786   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
4787   Inst.addOperand(Inst.getOperand(0));
4788   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
4789 }
4790 
4791 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
4792                                     const OperandVector &Operands) {
4793   int CondOp = -1, ImmOp = -1;
4794   switch(Inst.getOpcode()) {
4795     case ARM::tB:
4796     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
4797 
4798     case ARM::t2B:
4799     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
4800 
4801     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
4802   }
4803   // first decide whether or not the branch should be conditional
4804   // by looking at it's location relative to an IT block
4805   if(inITBlock()) {
4806     // inside an IT block we cannot have any conditional branches. any
4807     // such instructions needs to be converted to unconditional form
4808     switch(Inst.getOpcode()) {
4809       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
4810       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
4811     }
4812   } else {
4813     // outside IT blocks we can only have unconditional branches with AL
4814     // condition code or conditional branches with non-AL condition code
4815     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
4816     switch(Inst.getOpcode()) {
4817       case ARM::tB:
4818       case ARM::tBcc:
4819         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
4820         break;
4821       case ARM::t2B:
4822       case ARM::t2Bcc:
4823         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
4824         break;
4825     }
4826   }
4827 
4828   // now decide on encoding size based on branch target range
4829   switch(Inst.getOpcode()) {
4830     // classify tB as either t2B or t1B based on range of immediate operand
4831     case ARM::tB: {
4832       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4833       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
4834         Inst.setOpcode(ARM::t2B);
4835       break;
4836     }
4837     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
4838     case ARM::tBcc: {
4839       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4840       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
4841         Inst.setOpcode(ARM::t2Bcc);
4842       break;
4843     }
4844   }
4845   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
4846   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
4847 }
4848 
4849 /// Parse an ARM memory expression, return false if successful else return true
4850 /// or an error.  The first token must be a '[' when called.
4851 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
4852   MCAsmParser &Parser = getParser();
4853   SMLoc S, E;
4854   if (Parser.getTok().isNot(AsmToken::LBrac))
4855     return TokError("Token is not a Left Bracket");
4856   S = Parser.getTok().getLoc();
4857   Parser.Lex(); // Eat left bracket token.
4858 
4859   const AsmToken &BaseRegTok = Parser.getTok();
4860   int BaseRegNum = tryParseRegister();
4861   if (BaseRegNum == -1)
4862     return Error(BaseRegTok.getLoc(), "register expected");
4863 
4864   // The next token must either be a comma, a colon or a closing bracket.
4865   const AsmToken &Tok = Parser.getTok();
4866   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
4867       !Tok.is(AsmToken::RBrac))
4868     return Error(Tok.getLoc(), "malformed memory operand");
4869 
4870   if (Tok.is(AsmToken::RBrac)) {
4871     E = Tok.getEndLoc();
4872     Parser.Lex(); // Eat right bracket token.
4873 
4874     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4875                                              ARM_AM::no_shift, 0, 0, false,
4876                                              S, E));
4877 
4878     // If there's a pre-indexing writeback marker, '!', just add it as a token
4879     // operand. It's rather odd, but syntactically valid.
4880     if (Parser.getTok().is(AsmToken::Exclaim)) {
4881       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4882       Parser.Lex(); // Eat the '!'.
4883     }
4884 
4885     return false;
4886   }
4887 
4888   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
4889          "Lost colon or comma in memory operand?!");
4890   if (Tok.is(AsmToken::Comma)) {
4891     Parser.Lex(); // Eat the comma.
4892   }
4893 
4894   // If we have a ':', it's an alignment specifier.
4895   if (Parser.getTok().is(AsmToken::Colon)) {
4896     Parser.Lex(); // Eat the ':'.
4897     E = Parser.getTok().getLoc();
4898     SMLoc AlignmentLoc = Tok.getLoc();
4899 
4900     const MCExpr *Expr;
4901     if (getParser().parseExpression(Expr))
4902      return true;
4903 
4904     // The expression has to be a constant. Memory references with relocations
4905     // don't come through here, as they use the <label> forms of the relevant
4906     // instructions.
4907     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4908     if (!CE)
4909       return Error (E, "constant expression expected");
4910 
4911     unsigned Align = 0;
4912     switch (CE->getValue()) {
4913     default:
4914       return Error(E,
4915                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
4916     case 16:  Align = 2; break;
4917     case 32:  Align = 4; break;
4918     case 64:  Align = 8; break;
4919     case 128: Align = 16; break;
4920     case 256: Align = 32; break;
4921     }
4922 
4923     // Now we should have the closing ']'
4924     if (Parser.getTok().isNot(AsmToken::RBrac))
4925       return Error(Parser.getTok().getLoc(), "']' expected");
4926     E = Parser.getTok().getEndLoc();
4927     Parser.Lex(); // Eat right bracket token.
4928 
4929     // Don't worry about range checking the value here. That's handled by
4930     // the is*() predicates.
4931     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4932                                              ARM_AM::no_shift, 0, Align,
4933                                              false, S, E, AlignmentLoc));
4934 
4935     // If there's a pre-indexing writeback marker, '!', just add it as a token
4936     // operand.
4937     if (Parser.getTok().is(AsmToken::Exclaim)) {
4938       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4939       Parser.Lex(); // Eat the '!'.
4940     }
4941 
4942     return false;
4943   }
4944 
4945   // If we have a '#', it's an immediate offset, else assume it's a register
4946   // offset. Be friendly and also accept a plain integer (without a leading
4947   // hash) for gas compatibility.
4948   if (Parser.getTok().is(AsmToken::Hash) ||
4949       Parser.getTok().is(AsmToken::Dollar) ||
4950       Parser.getTok().is(AsmToken::Integer)) {
4951     if (Parser.getTok().isNot(AsmToken::Integer))
4952       Parser.Lex(); // Eat '#' or '$'.
4953     E = Parser.getTok().getLoc();
4954 
4955     bool isNegative = getParser().getTok().is(AsmToken::Minus);
4956     const MCExpr *Offset;
4957     if (getParser().parseExpression(Offset))
4958      return true;
4959 
4960     // The expression has to be a constant. Memory references with relocations
4961     // don't come through here, as they use the <label> forms of the relevant
4962     // instructions.
4963     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4964     if (!CE)
4965       return Error (E, "constant expression expected");
4966 
4967     // If the constant was #-0, represent it as
4968     // std::numeric_limits<int32_t>::min().
4969     int32_t Val = CE->getValue();
4970     if (isNegative && Val == 0)
4971       CE = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
4972                                   getContext());
4973 
4974     // Now we should have the closing ']'
4975     if (Parser.getTok().isNot(AsmToken::RBrac))
4976       return Error(Parser.getTok().getLoc(), "']' expected");
4977     E = Parser.getTok().getEndLoc();
4978     Parser.Lex(); // Eat right bracket token.
4979 
4980     // Don't worry about range checking the value here. That's handled by
4981     // the is*() predicates.
4982     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
4983                                              ARM_AM::no_shift, 0, 0,
4984                                              false, S, E));
4985 
4986     // If there's a pre-indexing writeback marker, '!', just add it as a token
4987     // operand.
4988     if (Parser.getTok().is(AsmToken::Exclaim)) {
4989       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4990       Parser.Lex(); // Eat the '!'.
4991     }
4992 
4993     return false;
4994   }
4995 
4996   // The register offset is optionally preceded by a '+' or '-'
4997   bool isNegative = false;
4998   if (Parser.getTok().is(AsmToken::Minus)) {
4999     isNegative = true;
5000     Parser.Lex(); // Eat the '-'.
5001   } else if (Parser.getTok().is(AsmToken::Plus)) {
5002     // Nothing to do.
5003     Parser.Lex(); // Eat the '+'.
5004   }
5005 
5006   E = Parser.getTok().getLoc();
5007   int OffsetRegNum = tryParseRegister();
5008   if (OffsetRegNum == -1)
5009     return Error(E, "register expected");
5010 
5011   // If there's a shift operator, handle it.
5012   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5013   unsigned ShiftImm = 0;
5014   if (Parser.getTok().is(AsmToken::Comma)) {
5015     Parser.Lex(); // Eat the ','.
5016     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5017       return true;
5018   }
5019 
5020   // Now we should have the closing ']'
5021   if (Parser.getTok().isNot(AsmToken::RBrac))
5022     return Error(Parser.getTok().getLoc(), "']' expected");
5023   E = Parser.getTok().getEndLoc();
5024   Parser.Lex(); // Eat right bracket token.
5025 
5026   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
5027                                            ShiftType, ShiftImm, 0, isNegative,
5028                                            S, E));
5029 
5030   // If there's a pre-indexing writeback marker, '!', just add it as a token
5031   // operand.
5032   if (Parser.getTok().is(AsmToken::Exclaim)) {
5033     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5034     Parser.Lex(); // Eat the '!'.
5035   }
5036 
5037   return false;
5038 }
5039 
5040 /// parseMemRegOffsetShift - one of these two:
5041 ///   ( lsl | lsr | asr | ror ) , # shift_amount
5042 ///   rrx
5043 /// return true if it parses a shift otherwise it returns false.
5044 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
5045                                           unsigned &Amount) {
5046   MCAsmParser &Parser = getParser();
5047   SMLoc Loc = Parser.getTok().getLoc();
5048   const AsmToken &Tok = Parser.getTok();
5049   if (Tok.isNot(AsmToken::Identifier))
5050     return true;
5051   StringRef ShiftName = Tok.getString();
5052   if (ShiftName == "lsl" || ShiftName == "LSL" ||
5053       ShiftName == "asl" || ShiftName == "ASL")
5054     St = ARM_AM::lsl;
5055   else if (ShiftName == "lsr" || ShiftName == "LSR")
5056     St = ARM_AM::lsr;
5057   else if (ShiftName == "asr" || ShiftName == "ASR")
5058     St = ARM_AM::asr;
5059   else if (ShiftName == "ror" || ShiftName == "ROR")
5060     St = ARM_AM::ror;
5061   else if (ShiftName == "rrx" || ShiftName == "RRX")
5062     St = ARM_AM::rrx;
5063   else
5064     return Error(Loc, "illegal shift operator");
5065   Parser.Lex(); // Eat shift type token.
5066 
5067   // rrx stands alone.
5068   Amount = 0;
5069   if (St != ARM_AM::rrx) {
5070     Loc = Parser.getTok().getLoc();
5071     // A '#' and a shift amount.
5072     const AsmToken &HashTok = Parser.getTok();
5073     if (HashTok.isNot(AsmToken::Hash) &&
5074         HashTok.isNot(AsmToken::Dollar))
5075       return Error(HashTok.getLoc(), "'#' expected");
5076     Parser.Lex(); // Eat hash token.
5077 
5078     const MCExpr *Expr;
5079     if (getParser().parseExpression(Expr))
5080       return true;
5081     // Range check the immediate.
5082     // lsl, ror: 0 <= imm <= 31
5083     // lsr, asr: 0 <= imm <= 32
5084     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5085     if (!CE)
5086       return Error(Loc, "shift amount must be an immediate");
5087     int64_t Imm = CE->getValue();
5088     if (Imm < 0 ||
5089         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5090         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5091       return Error(Loc, "immediate shift value out of range");
5092     // If <ShiftTy> #0, turn it into a no_shift.
5093     if (Imm == 0)
5094       St = ARM_AM::lsl;
5095     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5096     if (Imm == 32)
5097       Imm = 0;
5098     Amount = Imm;
5099   }
5100 
5101   return false;
5102 }
5103 
5104 /// parseFPImm - A floating point immediate expression operand.
5105 OperandMatchResultTy
5106 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5107   MCAsmParser &Parser = getParser();
5108   // Anything that can accept a floating point constant as an operand
5109   // needs to go through here, as the regular parseExpression is
5110   // integer only.
5111   //
5112   // This routine still creates a generic Immediate operand, containing
5113   // a bitcast of the 64-bit floating point value. The various operands
5114   // that accept floats can check whether the value is valid for them
5115   // via the standard is*() predicates.
5116 
5117   SMLoc S = Parser.getTok().getLoc();
5118 
5119   if (Parser.getTok().isNot(AsmToken::Hash) &&
5120       Parser.getTok().isNot(AsmToken::Dollar))
5121     return MatchOperand_NoMatch;
5122 
5123   // Disambiguate the VMOV forms that can accept an FP immediate.
5124   // vmov.f32 <sreg>, #imm
5125   // vmov.f64 <dreg>, #imm
5126   // vmov.f32 <dreg>, #imm  @ vector f32x2
5127   // vmov.f32 <qreg>, #imm  @ vector f32x4
5128   //
5129   // There are also the NEON VMOV instructions which expect an
5130   // integer constant. Make sure we don't try to parse an FPImm
5131   // for these:
5132   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
5133   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
5134   bool isVmovf = TyOp.isToken() &&
5135                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
5136                   TyOp.getToken() == ".f16");
5137   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
5138   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
5139                                          Mnemonic.getToken() == "fconsts");
5140   if (!(isVmovf || isFconst))
5141     return MatchOperand_NoMatch;
5142 
5143   Parser.Lex(); // Eat '#' or '$'.
5144 
5145   // Handle negation, as that still comes through as a separate token.
5146   bool isNegative = false;
5147   if (Parser.getTok().is(AsmToken::Minus)) {
5148     isNegative = true;
5149     Parser.Lex();
5150   }
5151   const AsmToken &Tok = Parser.getTok();
5152   SMLoc Loc = Tok.getLoc();
5153   if (Tok.is(AsmToken::Real) && isVmovf) {
5154     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
5155     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
5156     // If we had a '-' in front, toggle the sign bit.
5157     IntVal ^= (uint64_t)isNegative << 31;
5158     Parser.Lex(); // Eat the token.
5159     Operands.push_back(ARMOperand::CreateImm(
5160           MCConstantExpr::create(IntVal, getContext()),
5161           S, Parser.getTok().getLoc()));
5162     return MatchOperand_Success;
5163   }
5164   // Also handle plain integers. Instructions which allow floating point
5165   // immediates also allow a raw encoded 8-bit value.
5166   if (Tok.is(AsmToken::Integer) && isFconst) {
5167     int64_t Val = Tok.getIntVal();
5168     Parser.Lex(); // Eat the token.
5169     if (Val > 255 || Val < 0) {
5170       Error(Loc, "encoded floating point value out of range");
5171       return MatchOperand_ParseFail;
5172     }
5173     float RealVal = ARM_AM::getFPImmFloat(Val);
5174     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5175 
5176     Operands.push_back(ARMOperand::CreateImm(
5177         MCConstantExpr::create(Val, getContext()), S,
5178         Parser.getTok().getLoc()));
5179     return MatchOperand_Success;
5180   }
5181 
5182   Error(Loc, "invalid floating point immediate");
5183   return MatchOperand_ParseFail;
5184 }
5185 
5186 /// Parse a arm instruction operand.  For now this parses the operand regardless
5187 /// of the mnemonic.
5188 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5189   MCAsmParser &Parser = getParser();
5190   SMLoc S, E;
5191 
5192   // Check if the current operand has a custom associated parser, if so, try to
5193   // custom parse the operand, or fallback to the general approach.
5194   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5195   if (ResTy == MatchOperand_Success)
5196     return false;
5197   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5198   // there was a match, but an error occurred, in which case, just return that
5199   // the operand parsing failed.
5200   if (ResTy == MatchOperand_ParseFail)
5201     return true;
5202 
5203   switch (getLexer().getKind()) {
5204   default:
5205     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5206     return true;
5207   case AsmToken::Identifier: {
5208     // If we've seen a branch mnemonic, the next operand must be a label.  This
5209     // is true even if the label is a register name.  So "br r1" means branch to
5210     // label "r1".
5211     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5212     if (!ExpectLabel) {
5213       if (!tryParseRegisterWithWriteBack(Operands))
5214         return false;
5215       int Res = tryParseShiftRegister(Operands);
5216       if (Res == 0) // success
5217         return false;
5218       else if (Res == -1) // irrecoverable error
5219         return true;
5220       // If this is VMRS, check for the apsr_nzcv operand.
5221       if (Mnemonic == "vmrs" &&
5222           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5223         S = Parser.getTok().getLoc();
5224         Parser.Lex();
5225         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5226         return false;
5227       }
5228     }
5229 
5230     // Fall though for the Identifier case that is not a register or a
5231     // special name.
5232     LLVM_FALLTHROUGH;
5233   }
5234   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5235   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5236   case AsmToken::String:  // quoted label names.
5237   case AsmToken::Dot: {   // . as a branch target
5238     // This was not a register so parse other operands that start with an
5239     // identifier (like labels) as expressions and create them as immediates.
5240     const MCExpr *IdVal;
5241     S = Parser.getTok().getLoc();
5242     if (getParser().parseExpression(IdVal))
5243       return true;
5244     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5245     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5246     return false;
5247   }
5248   case AsmToken::LBrac:
5249     return parseMemory(Operands);
5250   case AsmToken::LCurly:
5251     return parseRegisterList(Operands);
5252   case AsmToken::Dollar:
5253   case AsmToken::Hash:
5254     // #42 -> immediate.
5255     S = Parser.getTok().getLoc();
5256     Parser.Lex();
5257 
5258     if (Parser.getTok().isNot(AsmToken::Colon)) {
5259       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5260       const MCExpr *ImmVal;
5261       if (getParser().parseExpression(ImmVal))
5262         return true;
5263       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5264       if (CE) {
5265         int32_t Val = CE->getValue();
5266         if (isNegative && Val == 0)
5267           ImmVal = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5268                                           getContext());
5269       }
5270       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5271       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5272 
5273       // There can be a trailing '!' on operands that we want as a separate
5274       // '!' Token operand. Handle that here. For example, the compatibility
5275       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5276       if (Parser.getTok().is(AsmToken::Exclaim)) {
5277         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5278                                                    Parser.getTok().getLoc()));
5279         Parser.Lex(); // Eat exclaim token
5280       }
5281       return false;
5282     }
5283     // w/ a ':' after the '#', it's just like a plain ':'.
5284     LLVM_FALLTHROUGH;
5285 
5286   case AsmToken::Colon: {
5287     S = Parser.getTok().getLoc();
5288     // ":lower16:" and ":upper16:" expression prefixes
5289     // FIXME: Check it's an expression prefix,
5290     // e.g. (FOO - :lower16:BAR) isn't legal.
5291     ARMMCExpr::VariantKind RefKind;
5292     if (parsePrefix(RefKind))
5293       return true;
5294 
5295     const MCExpr *SubExprVal;
5296     if (getParser().parseExpression(SubExprVal))
5297       return true;
5298 
5299     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5300                                               getContext());
5301     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5302     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5303     return false;
5304   }
5305   case AsmToken::Equal: {
5306     S = Parser.getTok().getLoc();
5307     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5308       return Error(S, "unexpected token in operand");
5309     Parser.Lex(); // Eat '='
5310     const MCExpr *SubExprVal;
5311     if (getParser().parseExpression(SubExprVal))
5312       return true;
5313     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5314 
5315     // execute-only: we assume that assembly programmers know what they are
5316     // doing and allow literal pool creation here
5317     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
5318     return false;
5319   }
5320   }
5321 }
5322 
5323 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5324 //  :lower16: and :upper16:.
5325 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5326   MCAsmParser &Parser = getParser();
5327   RefKind = ARMMCExpr::VK_ARM_None;
5328 
5329   // consume an optional '#' (GNU compatibility)
5330   if (getLexer().is(AsmToken::Hash))
5331     Parser.Lex();
5332 
5333   // :lower16: and :upper16: modifiers
5334   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5335   Parser.Lex(); // Eat ':'
5336 
5337   if (getLexer().isNot(AsmToken::Identifier)) {
5338     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5339     return true;
5340   }
5341 
5342   enum {
5343     COFF = (1 << MCObjectFileInfo::IsCOFF),
5344     ELF = (1 << MCObjectFileInfo::IsELF),
5345     MACHO = (1 << MCObjectFileInfo::IsMachO),
5346     WASM = (1 << MCObjectFileInfo::IsWasm),
5347   };
5348   static const struct PrefixEntry {
5349     const char *Spelling;
5350     ARMMCExpr::VariantKind VariantKind;
5351     uint8_t SupportedFormats;
5352   } PrefixEntries[] = {
5353     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
5354     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
5355   };
5356 
5357   StringRef IDVal = Parser.getTok().getIdentifier();
5358 
5359   const auto &Prefix =
5360       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5361                    [&IDVal](const PrefixEntry &PE) {
5362                       return PE.Spelling == IDVal;
5363                    });
5364   if (Prefix == std::end(PrefixEntries)) {
5365     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5366     return true;
5367   }
5368 
5369   uint8_t CurrentFormat;
5370   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
5371   case MCObjectFileInfo::IsMachO:
5372     CurrentFormat = MACHO;
5373     break;
5374   case MCObjectFileInfo::IsELF:
5375     CurrentFormat = ELF;
5376     break;
5377   case MCObjectFileInfo::IsCOFF:
5378     CurrentFormat = COFF;
5379     break;
5380   case MCObjectFileInfo::IsWasm:
5381     CurrentFormat = WASM;
5382     break;
5383   }
5384 
5385   if (~Prefix->SupportedFormats & CurrentFormat) {
5386     Error(Parser.getTok().getLoc(),
5387           "cannot represent relocation in the current file format");
5388     return true;
5389   }
5390 
5391   RefKind = Prefix->VariantKind;
5392   Parser.Lex();
5393 
5394   if (getLexer().isNot(AsmToken::Colon)) {
5395     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5396     return true;
5397   }
5398   Parser.Lex(); // Eat the last ':'
5399 
5400   return false;
5401 }
5402 
5403 /// \brief Given a mnemonic, split out possible predication code and carry
5404 /// setting letters to form a canonical mnemonic and flags.
5405 //
5406 // FIXME: Would be nice to autogen this.
5407 // FIXME: This is a bit of a maze of special cases.
5408 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5409                                       unsigned &PredicationCode,
5410                                       bool &CarrySetting,
5411                                       unsigned &ProcessorIMod,
5412                                       StringRef &ITMask) {
5413   PredicationCode = ARMCC::AL;
5414   CarrySetting = false;
5415   ProcessorIMod = 0;
5416 
5417   // Ignore some mnemonics we know aren't predicated forms.
5418   //
5419   // FIXME: Would be nice to autogen this.
5420   if ((Mnemonic == "movs" && isThumb()) ||
5421       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5422       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5423       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5424       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5425       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5426       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5427       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5428       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5429       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5430       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5431       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5432       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5433       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
5434       Mnemonic == "bxns"  || Mnemonic == "blxns" ||
5435       Mnemonic == "vudot" || Mnemonic == "vsdot")
5436     return Mnemonic;
5437 
5438   // First, split out any predication code. Ignore mnemonics we know aren't
5439   // predicated but do have a carry-set and so weren't caught above.
5440   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5441       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5442       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5443       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5444     unsigned CC = ARMCondCodeFromString(Mnemonic.substr(Mnemonic.size()-2));
5445     if (CC != ~0U) {
5446       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5447       PredicationCode = CC;
5448     }
5449   }
5450 
5451   // Next, determine if we have a carry setting bit. We explicitly ignore all
5452   // the instructions we know end in 's'.
5453   if (Mnemonic.endswith("s") &&
5454       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5455         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5456         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5457         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5458         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5459         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5460         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5461         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5462         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5463         Mnemonic == "bxns" || Mnemonic == "blxns" ||
5464         (Mnemonic == "movs" && isThumb()))) {
5465     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5466     CarrySetting = true;
5467   }
5468 
5469   // The "cps" instruction can have a interrupt mode operand which is glued into
5470   // the mnemonic. Check if this is the case, split it and parse the imod op
5471   if (Mnemonic.startswith("cps")) {
5472     // Split out any imod code.
5473     unsigned IMod =
5474       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5475       .Case("ie", ARM_PROC::IE)
5476       .Case("id", ARM_PROC::ID)
5477       .Default(~0U);
5478     if (IMod != ~0U) {
5479       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5480       ProcessorIMod = IMod;
5481     }
5482   }
5483 
5484   // The "it" instruction has the condition mask on the end of the mnemonic.
5485   if (Mnemonic.startswith("it")) {
5486     ITMask = Mnemonic.slice(2, Mnemonic.size());
5487     Mnemonic = Mnemonic.slice(0, 2);
5488   }
5489 
5490   return Mnemonic;
5491 }
5492 
5493 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
5494 /// inclusion of carry set or predication code operands.
5495 //
5496 // FIXME: It would be nice to autogen this.
5497 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5498                                          bool &CanAcceptCarrySet,
5499                                          bool &CanAcceptPredicationCode) {
5500   CanAcceptCarrySet =
5501       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5502       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5503       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
5504       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
5505       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
5506       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
5507       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5508       (!isThumb() &&
5509        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
5510         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
5511 
5512   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5513       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
5514       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5515       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5516       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
5517       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
5518       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
5519       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
5520       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
5521       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5522       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
5523       Mnemonic == "vmovx" || Mnemonic == "vins" ||
5524       Mnemonic == "vudot" || Mnemonic == "vsdot") {
5525     // These mnemonics are never predicable
5526     CanAcceptPredicationCode = false;
5527   } else if (!isThumb()) {
5528     // Some instructions are only predicable in Thumb mode
5529     CanAcceptPredicationCode =
5530         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5531         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5532         Mnemonic != "dmb" && Mnemonic != "dsb" && Mnemonic != "isb" &&
5533         Mnemonic != "pld" && Mnemonic != "pli" && Mnemonic != "pldw" &&
5534         Mnemonic != "ldc2" && Mnemonic != "ldc2l" && Mnemonic != "stc2" &&
5535         Mnemonic != "stc2l" && !Mnemonic.startswith("rfe") &&
5536         !Mnemonic.startswith("srs");
5537   } else if (isThumbOne()) {
5538     if (hasV6MOps())
5539       CanAcceptPredicationCode = Mnemonic != "movs";
5540     else
5541       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5542   } else
5543     CanAcceptPredicationCode = true;
5544 }
5545 
5546 // \brief Some Thumb instructions have two operand forms that are not
5547 // available as three operand, convert to two operand form if possible.
5548 //
5549 // FIXME: We would really like to be able to tablegen'erate this.
5550 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
5551                                                  bool CarrySetting,
5552                                                  OperandVector &Operands) {
5553   if (Operands.size() != 6)
5554     return;
5555 
5556   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5557         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5558   if (!Op3.isReg() || !Op4.isReg())
5559     return;
5560 
5561   auto Op3Reg = Op3.getReg();
5562   auto Op4Reg = Op4.getReg();
5563 
5564   // For most Thumb2 cases we just generate the 3 operand form and reduce
5565   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
5566   // won't accept SP or PC so we do the transformation here taking care
5567   // with immediate range in the 'add sp, sp #imm' case.
5568   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5569   if (isThumbTwo()) {
5570     if (Mnemonic != "add")
5571       return;
5572     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
5573                         (Op5.isReg() && Op5.getReg() == ARM::PC);
5574     if (!TryTransform) {
5575       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
5576                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
5577                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
5578                        Op5.isImm() && !Op5.isImm0_508s4());
5579     }
5580     if (!TryTransform)
5581       return;
5582   } else if (!isThumbOne())
5583     return;
5584 
5585   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5586         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5587         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5588         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
5589     return;
5590 
5591   // If first 2 operands of a 3 operand instruction are the same
5592   // then transform to 2 operand version of the same instruction
5593   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5594   bool Transform = Op3Reg == Op4Reg;
5595 
5596   // For communtative operations, we might be able to transform if we swap
5597   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
5598   // as tADDrsp.
5599   const ARMOperand *LastOp = &Op5;
5600   bool Swap = false;
5601   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
5602       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
5603        Mnemonic == "and" || Mnemonic == "eor" ||
5604        Mnemonic == "adc" || Mnemonic == "orr")) {
5605     Swap = true;
5606     LastOp = &Op4;
5607     Transform = true;
5608   }
5609 
5610   // If both registers are the same then remove one of them from
5611   // the operand list, with certain exceptions.
5612   if (Transform) {
5613     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
5614     // 2 operand forms don't exist.
5615     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
5616         LastOp->isReg())
5617       Transform = false;
5618 
5619     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
5620     // 3-bits because the ARMARM says not to.
5621     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
5622       Transform = false;
5623   }
5624 
5625   if (Transform) {
5626     if (Swap)
5627       std::swap(Op4, Op5);
5628     Operands.erase(Operands.begin() + 3);
5629   }
5630 }
5631 
5632 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5633                                           OperandVector &Operands) {
5634   // FIXME: This is all horribly hacky. We really need a better way to deal
5635   // with optional operands like this in the matcher table.
5636 
5637   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5638   // another does not. Specifically, the MOVW instruction does not. So we
5639   // special case it here and remove the defaulted (non-setting) cc_out
5640   // operand if that's the instruction we're trying to match.
5641   //
5642   // We do this as post-processing of the explicit operands rather than just
5643   // conditionally adding the cc_out in the first place because we need
5644   // to check the type of the parsed immediate operand.
5645   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5646       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
5647       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5648       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5649     return true;
5650 
5651   // Register-register 'add' for thumb does not have a cc_out operand
5652   // when there are only two register operands.
5653   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5654       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5655       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5656       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5657     return true;
5658   // Register-register 'add' for thumb does not have a cc_out operand
5659   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5660   // have to check the immediate range here since Thumb2 has a variant
5661   // that can handle a different range and has a cc_out operand.
5662   if (((isThumb() && Mnemonic == "add") ||
5663        (isThumbTwo() && Mnemonic == "sub")) &&
5664       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5665       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5666       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5667       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5668       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5669        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5670     return true;
5671   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5672   // imm0_4095 variant. That's the least-preferred variant when
5673   // selecting via the generic "add" mnemonic, so to know that we
5674   // should remove the cc_out operand, we have to explicitly check that
5675   // it's not one of the other variants. Ugh.
5676   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5677       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5678       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5679       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5680     // Nest conditions rather than one big 'if' statement for readability.
5681     //
5682     // If both registers are low, we're in an IT block, and the immediate is
5683     // in range, we should use encoding T1 instead, which has a cc_out.
5684     if (inITBlock() &&
5685         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5686         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5687         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5688       return false;
5689     // Check against T3. If the second register is the PC, this is an
5690     // alternate form of ADR, which uses encoding T4, so check for that too.
5691     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5692         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5693       return false;
5694 
5695     // Otherwise, we use encoding T4, which does not have a cc_out
5696     // operand.
5697     return true;
5698   }
5699 
5700   // The thumb2 multiply instruction doesn't have a CCOut register, so
5701   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5702   // use the 16-bit encoding or not.
5703   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5704       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5705       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5706       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5707       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5708       // If the registers aren't low regs, the destination reg isn't the
5709       // same as one of the source regs, or the cc_out operand is zero
5710       // outside of an IT block, we have to use the 32-bit encoding, so
5711       // remove the cc_out operand.
5712       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5713        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5714        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5715        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5716                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5717                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5718                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5719     return true;
5720 
5721   // Also check the 'mul' syntax variant that doesn't specify an explicit
5722   // destination register.
5723   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5724       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5725       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5726       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5727       // If the registers aren't low regs  or the cc_out operand is zero
5728       // outside of an IT block, we have to use the 32-bit encoding, so
5729       // remove the cc_out operand.
5730       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5731        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5732        !inITBlock()))
5733     return true;
5734 
5735   // Register-register 'add/sub' for thumb does not have a cc_out operand
5736   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5737   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5738   // right, this will result in better diagnostics (which operand is off)
5739   // anyway.
5740   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5741       (Operands.size() == 5 || Operands.size() == 6) &&
5742       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5743       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5744       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5745       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5746        (Operands.size() == 6 &&
5747         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5748     return true;
5749 
5750   return false;
5751 }
5752 
5753 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5754                                               OperandVector &Operands) {
5755   // VRINT{Z, R, X} have a predicate operand in VFP, but not in NEON
5756   unsigned RegIdx = 3;
5757   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx" || Mnemonic == "vrintr") &&
5758       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
5759        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
5760     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5761         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
5762          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
5763       RegIdx = 4;
5764 
5765     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5766         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5767              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5768          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5769              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5770       return true;
5771   }
5772   return false;
5773 }
5774 
5775 static bool isDataTypeToken(StringRef Tok) {
5776   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5777     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
5778     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
5779     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
5780     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
5781     Tok == ".f" || Tok == ".d";
5782 }
5783 
5784 // FIXME: This bit should probably be handled via an explicit match class
5785 // in the .td files that matches the suffix instead of having it be
5786 // a literal string token the way it is now.
5787 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
5788   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
5789 }
5790 
5791 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
5792                                  unsigned VariantID);
5793 
5794 static bool RequiresVFPRegListValidation(StringRef Inst,
5795                                          bool &AcceptSinglePrecisionOnly,
5796                                          bool &AcceptDoublePrecisionOnly) {
5797   if (Inst.size() < 7)
5798     return false;
5799 
5800   if (Inst.startswith("fldm") || Inst.startswith("fstm")) {
5801     StringRef AddressingMode = Inst.substr(4, 2);
5802     if (AddressingMode == "ia" || AddressingMode == "db" ||
5803         AddressingMode == "ea" || AddressingMode == "fd") {
5804       AcceptSinglePrecisionOnly = Inst[6] == 's';
5805       AcceptDoublePrecisionOnly = Inst[6] == 'd' || Inst[6] == 'x';
5806       return true;
5807     }
5808   }
5809 
5810   return false;
5811 }
5812 
5813 /// Parse an arm instruction mnemonic followed by its operands.
5814 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
5815                                     SMLoc NameLoc, OperandVector &Operands) {
5816   MCAsmParser &Parser = getParser();
5817   // FIXME: Can this be done via tablegen in some fashion?
5818   bool RequireVFPRegisterListCheck;
5819   bool AcceptSinglePrecisionOnly;
5820   bool AcceptDoublePrecisionOnly;
5821   RequireVFPRegisterListCheck =
5822     RequiresVFPRegListValidation(Name, AcceptSinglePrecisionOnly,
5823                                  AcceptDoublePrecisionOnly);
5824 
5825   // Apply mnemonic aliases before doing anything else, as the destination
5826   // mnemonic may include suffices and we want to handle them normally.
5827   // The generic tblgen'erated code does this later, at the start of
5828   // MatchInstructionImpl(), but that's too late for aliases that include
5829   // any sort of suffix.
5830   uint64_t AvailableFeatures = getAvailableFeatures();
5831   unsigned AssemblerDialect = getParser().getAssemblerDialect();
5832   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
5833 
5834   // First check for the ARM-specific .req directive.
5835   if (Parser.getTok().is(AsmToken::Identifier) &&
5836       Parser.getTok().getIdentifier() == ".req") {
5837     parseDirectiveReq(Name, NameLoc);
5838     // We always return 'error' for this, as we're done with this
5839     // statement and don't need to match the 'instruction."
5840     return true;
5841   }
5842 
5843   // Create the leading tokens for the mnemonic, split by '.' characters.
5844   size_t Start = 0, Next = Name.find('.');
5845   StringRef Mnemonic = Name.slice(Start, Next);
5846 
5847   // Split out the predication code and carry setting flag from the mnemonic.
5848   unsigned PredicationCode;
5849   unsigned ProcessorIMod;
5850   bool CarrySetting;
5851   StringRef ITMask;
5852   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
5853                            ProcessorIMod, ITMask);
5854 
5855   // In Thumb1, only the branch (B) instruction can be predicated.
5856   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
5857     return Error(NameLoc, "conditional execution not supported in Thumb1");
5858   }
5859 
5860   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
5861 
5862   // Handle the IT instruction ITMask. Convert it to a bitmask. This
5863   // is the mask as it will be for the IT encoding if the conditional
5864   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
5865   // where the conditional bit0 is zero, the instruction post-processing
5866   // will adjust the mask accordingly.
5867   if (Mnemonic == "it") {
5868     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
5869     if (ITMask.size() > 3) {
5870       return Error(Loc, "too many conditions on IT instruction");
5871     }
5872     unsigned Mask = 8;
5873     for (unsigned i = ITMask.size(); i != 0; --i) {
5874       char pos = ITMask[i - 1];
5875       if (pos != 't' && pos != 'e') {
5876         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
5877       }
5878       Mask >>= 1;
5879       if (ITMask[i - 1] == 't')
5880         Mask |= 8;
5881     }
5882     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
5883   }
5884 
5885   // FIXME: This is all a pretty gross hack. We should automatically handle
5886   // optional operands like this via tblgen.
5887 
5888   // Next, add the CCOut and ConditionCode operands, if needed.
5889   //
5890   // For mnemonics which can ever incorporate a carry setting bit or predication
5891   // code, our matching model involves us always generating CCOut and
5892   // ConditionCode operands to match the mnemonic "as written" and then we let
5893   // the matcher deal with finding the right instruction or generating an
5894   // appropriate error.
5895   bool CanAcceptCarrySet, CanAcceptPredicationCode;
5896   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
5897 
5898   // If we had a carry-set on an instruction that can't do that, issue an
5899   // error.
5900   if (!CanAcceptCarrySet && CarrySetting) {
5901     return Error(NameLoc, "instruction '" + Mnemonic +
5902                  "' can not set flags, but 's' suffix specified");
5903   }
5904   // If we had a predication code on an instruction that can't do that, issue an
5905   // error.
5906   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
5907     return Error(NameLoc, "instruction '" + Mnemonic +
5908                  "' is not predicable, but condition code specified");
5909   }
5910 
5911   // Add the carry setting operand, if necessary.
5912   if (CanAcceptCarrySet) {
5913     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
5914     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
5915                                                Loc));
5916   }
5917 
5918   // Add the predication code operand, if necessary.
5919   if (CanAcceptPredicationCode) {
5920     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
5921                                       CarrySetting);
5922     Operands.push_back(ARMOperand::CreateCondCode(
5923                          ARMCC::CondCodes(PredicationCode), Loc));
5924   }
5925 
5926   // Add the processor imod operand, if necessary.
5927   if (ProcessorIMod) {
5928     Operands.push_back(ARMOperand::CreateImm(
5929           MCConstantExpr::create(ProcessorIMod, getContext()),
5930                                  NameLoc, NameLoc));
5931   } else if (Mnemonic == "cps" && isMClass()) {
5932     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
5933   }
5934 
5935   // Add the remaining tokens in the mnemonic.
5936   while (Next != StringRef::npos) {
5937     Start = Next;
5938     Next = Name.find('.', Start + 1);
5939     StringRef ExtraToken = Name.slice(Start, Next);
5940 
5941     // Some NEON instructions have an optional datatype suffix that is
5942     // completely ignored. Check for that.
5943     if (isDataTypeToken(ExtraToken) &&
5944         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
5945       continue;
5946 
5947     // For for ARM mode generate an error if the .n qualifier is used.
5948     if (ExtraToken == ".n" && !isThumb()) {
5949       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5950       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
5951                    "arm mode");
5952     }
5953 
5954     // The .n qualifier is always discarded as that is what the tables
5955     // and matcher expect.  In ARM mode the .w qualifier has no effect,
5956     // so discard it to avoid errors that can be caused by the matcher.
5957     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
5958       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5959       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
5960     }
5961   }
5962 
5963   // Read the remaining operands.
5964   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5965     // Read the first operand.
5966     if (parseOperand(Operands, Mnemonic)) {
5967       return true;
5968     }
5969 
5970     while (parseOptionalToken(AsmToken::Comma)) {
5971       // Parse and remember the operand.
5972       if (parseOperand(Operands, Mnemonic)) {
5973         return true;
5974       }
5975     }
5976   }
5977 
5978   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
5979     return true;
5980 
5981   if (RequireVFPRegisterListCheck) {
5982     ARMOperand &Op = static_cast<ARMOperand &>(*Operands.back());
5983     if (AcceptSinglePrecisionOnly && !Op.isSPRRegList())
5984       return Error(Op.getStartLoc(),
5985                    "VFP/Neon single precision register expected");
5986     if (AcceptDoublePrecisionOnly && !Op.isDPRRegList())
5987       return Error(Op.getStartLoc(),
5988                    "VFP/Neon double precision register expected");
5989   }
5990 
5991   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
5992 
5993   // Some instructions, mostly Thumb, have forms for the same mnemonic that
5994   // do and don't have a cc_out optional-def operand. With some spot-checks
5995   // of the operand list, we can figure out which variant we're trying to
5996   // parse and adjust accordingly before actually matching. We shouldn't ever
5997   // try to remove a cc_out operand that was explicitly set on the
5998   // mnemonic, of course (CarrySetting == true). Reason number #317 the
5999   // table driven matcher doesn't fit well with the ARM instruction set.
6000   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
6001     Operands.erase(Operands.begin() + 1);
6002 
6003   // Some instructions have the same mnemonic, but don't always
6004   // have a predicate. Distinguish them here and delete the
6005   // predicate if needed.
6006   if (shouldOmitPredicateOperand(Mnemonic, Operands))
6007     Operands.erase(Operands.begin() + 1);
6008 
6009   // ARM mode 'blx' need special handling, as the register operand version
6010   // is predicable, but the label operand version is not. So, we can't rely
6011   // on the Mnemonic based checking to correctly figure out when to put
6012   // a k_CondCode operand in the list. If we're trying to match the label
6013   // version, remove the k_CondCode operand here.
6014   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
6015       static_cast<ARMOperand &>(*Operands[2]).isImm())
6016     Operands.erase(Operands.begin() + 1);
6017 
6018   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
6019   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
6020   // a single GPRPair reg operand is used in the .td file to replace the two
6021   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
6022   // expressed as a GPRPair, so we have to manually merge them.
6023   // FIXME: We would really like to be able to tablegen'erate this.
6024   if (!isThumb() && Operands.size() > 4 &&
6025       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
6026        Mnemonic == "stlexd")) {
6027     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
6028     unsigned Idx = isLoad ? 2 : 3;
6029     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
6030     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
6031 
6032     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
6033     // Adjust only if Op1 and Op2 are GPRs.
6034     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
6035         MRC.contains(Op2.getReg())) {
6036       unsigned Reg1 = Op1.getReg();
6037       unsigned Reg2 = Op2.getReg();
6038       unsigned Rt = MRI->getEncodingValue(Reg1);
6039       unsigned Rt2 = MRI->getEncodingValue(Reg2);
6040 
6041       // Rt2 must be Rt + 1 and Rt must be even.
6042       if (Rt + 1 != Rt2 || (Rt & 1)) {
6043         return Error(Op2.getStartLoc(),
6044                      isLoad ? "destination operands must be sequential"
6045                             : "source operands must be sequential");
6046       }
6047       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
6048           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
6049       Operands[Idx] =
6050           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
6051       Operands.erase(Operands.begin() + Idx + 1);
6052     }
6053   }
6054 
6055   // GNU Assembler extension (compatibility)
6056   if ((Mnemonic == "ldrd" || Mnemonic == "strd")) {
6057     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
6058     ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6059     if (Op3.isMem()) {
6060       assert(Op2.isReg() && "expected register argument");
6061 
6062       unsigned SuperReg = MRI->getMatchingSuperReg(
6063           Op2.getReg(), ARM::gsub_0, &MRI->getRegClass(ARM::GPRPairRegClassID));
6064 
6065       assert(SuperReg && "expected register pair");
6066 
6067       unsigned PairedReg = MRI->getSubReg(SuperReg, ARM::gsub_1);
6068 
6069       Operands.insert(
6070           Operands.begin() + 3,
6071           ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6072     }
6073   }
6074 
6075   // FIXME: As said above, this is all a pretty gross hack.  This instruction
6076   // does not fit with other "subs" and tblgen.
6077   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
6078   // so the Mnemonic is the original name "subs" and delete the predicate
6079   // operand so it will match the table entry.
6080   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
6081       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6082       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
6083       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6084       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
6085       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6086     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
6087     Operands.erase(Operands.begin() + 1);
6088   }
6089   return false;
6090 }
6091 
6092 // Validate context-sensitive operand constraints.
6093 
6094 // return 'true' if register list contains non-low GPR registers,
6095 // 'false' otherwise. If Reg is in the register list or is HiReg, set
6096 // 'containsReg' to true.
6097 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
6098                                  unsigned Reg, unsigned HiReg,
6099                                  bool &containsReg) {
6100   containsReg = false;
6101   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
6102     unsigned OpReg = Inst.getOperand(i).getReg();
6103     if (OpReg == Reg)
6104       containsReg = true;
6105     // Anything other than a low register isn't legal here.
6106     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
6107       return true;
6108   }
6109   return false;
6110 }
6111 
6112 // Check if the specified regisgter is in the register list of the inst,
6113 // starting at the indicated operand number.
6114 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
6115   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
6116     unsigned OpReg = Inst.getOperand(i).getReg();
6117     if (OpReg == Reg)
6118       return true;
6119   }
6120   return false;
6121 }
6122 
6123 // Return true if instruction has the interesting property of being
6124 // allowed in IT blocks, but not being predicable.
6125 static bool instIsBreakpoint(const MCInst &Inst) {
6126     return Inst.getOpcode() == ARM::tBKPT ||
6127            Inst.getOpcode() == ARM::BKPT ||
6128            Inst.getOpcode() == ARM::tHLT ||
6129            Inst.getOpcode() == ARM::HLT;
6130 }
6131 
6132 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
6133                                        const OperandVector &Operands,
6134                                        unsigned ListNo, bool IsARPop) {
6135   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6136   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6137 
6138   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6139   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
6140   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6141 
6142   if (!IsARPop && ListContainsSP)
6143     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6144                  "SP may not be in the register list");
6145   else if (ListContainsPC && ListContainsLR)
6146     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6147                  "PC and LR may not be in the register list simultaneously");
6148   return false;
6149 }
6150 
6151 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
6152                                        const OperandVector &Operands,
6153                                        unsigned ListNo) {
6154   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6155   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6156 
6157   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6158   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6159 
6160   if (ListContainsSP && ListContainsPC)
6161     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6162                  "SP and PC may not be in the register list");
6163   else if (ListContainsSP)
6164     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6165                  "SP may not be in the register list");
6166   else if (ListContainsPC)
6167     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6168                  "PC may not be in the register list");
6169   return false;
6170 }
6171 
6172 // FIXME: We would really like to be able to tablegen'erate this.
6173 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6174                                        const OperandVector &Operands) {
6175   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6176   SMLoc Loc = Operands[0]->getStartLoc();
6177 
6178   // Check the IT block state first.
6179   // NOTE: BKPT and HLT instructions have the interesting property of being
6180   // allowed in IT blocks, but not being predicable. They just always execute.
6181   if (inITBlock() && !instIsBreakpoint(Inst)) {
6182     // The instruction must be predicable.
6183     if (!MCID.isPredicable())
6184       return Error(Loc, "instructions in IT block must be predicable");
6185     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
6186     if (Cond != currentITCond()) {
6187       // Find the condition code Operand to get its SMLoc information.
6188       SMLoc CondLoc;
6189       for (unsigned I = 1; I < Operands.size(); ++I)
6190         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
6191           CondLoc = Operands[I]->getStartLoc();
6192       return Error(CondLoc, "incorrect condition in IT block; got '" +
6193                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
6194                    "', but expected '" +
6195                    ARMCondCodeToString(ARMCC::CondCodes(currentITCond())) + "'");
6196     }
6197   // Check for non-'al' condition codes outside of the IT block.
6198   } else if (isThumbTwo() && MCID.isPredicable() &&
6199              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6200              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
6201              Inst.getOpcode() != ARM::t2Bcc) {
6202     return Error(Loc, "predicated instructions must be in IT block");
6203   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
6204              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6205                  ARMCC::AL) {
6206     return Warning(Loc, "predicated instructions should be in IT block");
6207   }
6208 
6209   // PC-setting instructions in an IT block, but not the last instruction of
6210   // the block, are UNPREDICTABLE.
6211   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
6212     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
6213   }
6214 
6215   const unsigned Opcode = Inst.getOpcode();
6216   switch (Opcode) {
6217   case ARM::LDRD:
6218   case ARM::LDRD_PRE:
6219   case ARM::LDRD_POST: {
6220     const unsigned RtReg = Inst.getOperand(0).getReg();
6221 
6222     // Rt can't be R14.
6223     if (RtReg == ARM::LR)
6224       return Error(Operands[3]->getStartLoc(),
6225                    "Rt can't be R14");
6226 
6227     const unsigned Rt = MRI->getEncodingValue(RtReg);
6228     // Rt must be even-numbered.
6229     if ((Rt & 1) == 1)
6230       return Error(Operands[3]->getStartLoc(),
6231                    "Rt must be even-numbered");
6232 
6233     // Rt2 must be Rt + 1.
6234     const unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6235     if (Rt2 != Rt + 1)
6236       return Error(Operands[3]->getStartLoc(),
6237                    "destination operands must be sequential");
6238 
6239     if (Opcode == ARM::LDRD_PRE || Opcode == ARM::LDRD_POST) {
6240       const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6241       // For addressing modes with writeback, the base register needs to be
6242       // different from the destination registers.
6243       if (Rn == Rt || Rn == Rt2)
6244         return Error(Operands[3]->getStartLoc(),
6245                      "base register needs to be different from destination "
6246                      "registers");
6247     }
6248 
6249     return false;
6250   }
6251   case ARM::t2LDRDi8:
6252   case ARM::t2LDRD_PRE:
6253   case ARM::t2LDRD_POST: {
6254     // Rt2 must be different from Rt.
6255     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6256     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6257     if (Rt2 == Rt)
6258       return Error(Operands[3]->getStartLoc(),
6259                    "destination operands can't be identical");
6260     return false;
6261   }
6262   case ARM::t2BXJ: {
6263     const unsigned RmReg = Inst.getOperand(0).getReg();
6264     // Rm = SP is no longer unpredictable in v8-A
6265     if (RmReg == ARM::SP && !hasV8Ops())
6266       return Error(Operands[2]->getStartLoc(),
6267                    "r13 (SP) is an unpredictable operand to BXJ");
6268     return false;
6269   }
6270   case ARM::STRD: {
6271     // Rt2 must be Rt + 1.
6272     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6273     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6274     if (Rt2 != Rt + 1)
6275       return Error(Operands[3]->getStartLoc(),
6276                    "source operands must be sequential");
6277     return false;
6278   }
6279   case ARM::STRD_PRE:
6280   case ARM::STRD_POST: {
6281     // Rt2 must be Rt + 1.
6282     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6283     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6284     if (Rt2 != Rt + 1)
6285       return Error(Operands[3]->getStartLoc(),
6286                    "source operands must be sequential");
6287     return false;
6288   }
6289   case ARM::STR_PRE_IMM:
6290   case ARM::STR_PRE_REG:
6291   case ARM::STR_POST_IMM:
6292   case ARM::STR_POST_REG:
6293   case ARM::STRH_PRE:
6294   case ARM::STRH_POST:
6295   case ARM::STRB_PRE_IMM:
6296   case ARM::STRB_PRE_REG:
6297   case ARM::STRB_POST_IMM:
6298   case ARM::STRB_POST_REG: {
6299     // Rt must be different from Rn.
6300     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6301     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6302 
6303     if (Rt == Rn)
6304       return Error(Operands[3]->getStartLoc(),
6305                    "source register and base register can't be identical");
6306     return false;
6307   }
6308   case ARM::LDR_PRE_IMM:
6309   case ARM::LDR_PRE_REG:
6310   case ARM::LDR_POST_IMM:
6311   case ARM::LDR_POST_REG:
6312   case ARM::LDRH_PRE:
6313   case ARM::LDRH_POST:
6314   case ARM::LDRSH_PRE:
6315   case ARM::LDRSH_POST:
6316   case ARM::LDRB_PRE_IMM:
6317   case ARM::LDRB_PRE_REG:
6318   case ARM::LDRB_POST_IMM:
6319   case ARM::LDRB_POST_REG:
6320   case ARM::LDRSB_PRE:
6321   case ARM::LDRSB_POST: {
6322     // Rt must be different from Rn.
6323     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6324     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6325 
6326     if (Rt == Rn)
6327       return Error(Operands[3]->getStartLoc(),
6328                    "destination register and base register can't be identical");
6329     return false;
6330   }
6331   case ARM::SBFX:
6332   case ARM::UBFX: {
6333     // Width must be in range [1, 32-lsb].
6334     unsigned LSB = Inst.getOperand(2).getImm();
6335     unsigned Widthm1 = Inst.getOperand(3).getImm();
6336     if (Widthm1 >= 32 - LSB)
6337       return Error(Operands[5]->getStartLoc(),
6338                    "bitfield width must be in range [1,32-lsb]");
6339     return false;
6340   }
6341   // Notionally handles ARM::tLDMIA_UPD too.
6342   case ARM::tLDMIA: {
6343     // If we're parsing Thumb2, the .w variant is available and handles
6344     // most cases that are normally illegal for a Thumb1 LDM instruction.
6345     // We'll make the transformation in processInstruction() if necessary.
6346     //
6347     // Thumb LDM instructions are writeback iff the base register is not
6348     // in the register list.
6349     unsigned Rn = Inst.getOperand(0).getReg();
6350     bool HasWritebackToken =
6351         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6352          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
6353     bool ListContainsBase;
6354     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
6355       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6356                    "registers must be in range r0-r7");
6357     // If we should have writeback, then there should be a '!' token.
6358     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6359       return Error(Operands[2]->getStartLoc(),
6360                    "writeback operator '!' expected");
6361     // If we should not have writeback, there must not be a '!'. This is
6362     // true even for the 32-bit wide encodings.
6363     if (ListContainsBase && HasWritebackToken)
6364       return Error(Operands[3]->getStartLoc(),
6365                    "writeback operator '!' not allowed when base register "
6366                    "in register list");
6367 
6368     if (validatetLDMRegList(Inst, Operands, 3))
6369       return true;
6370     break;
6371   }
6372   case ARM::LDMIA_UPD:
6373   case ARM::LDMDB_UPD:
6374   case ARM::LDMIB_UPD:
6375   case ARM::LDMDA_UPD:
6376     // ARM variants loading and updating the same register are only officially
6377     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6378     if (!hasV7Ops())
6379       break;
6380     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6381       return Error(Operands.back()->getStartLoc(),
6382                    "writeback register not allowed in register list");
6383     break;
6384   case ARM::t2LDMIA:
6385   case ARM::t2LDMDB:
6386     if (validatetLDMRegList(Inst, Operands, 3))
6387       return true;
6388     break;
6389   case ARM::t2STMIA:
6390   case ARM::t2STMDB:
6391     if (validatetSTMRegList(Inst, Operands, 3))
6392       return true;
6393     break;
6394   case ARM::t2LDMIA_UPD:
6395   case ARM::t2LDMDB_UPD:
6396   case ARM::t2STMIA_UPD:
6397   case ARM::t2STMDB_UPD:
6398     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6399       return Error(Operands.back()->getStartLoc(),
6400                    "writeback register not allowed in register list");
6401 
6402     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
6403       if (validatetLDMRegList(Inst, Operands, 3))
6404         return true;
6405     } else {
6406       if (validatetSTMRegList(Inst, Operands, 3))
6407         return true;
6408     }
6409     break;
6410 
6411   case ARM::sysLDMIA_UPD:
6412   case ARM::sysLDMDA_UPD:
6413   case ARM::sysLDMDB_UPD:
6414   case ARM::sysLDMIB_UPD:
6415     if (!listContainsReg(Inst, 3, ARM::PC))
6416       return Error(Operands[4]->getStartLoc(),
6417                    "writeback register only allowed on system LDM "
6418                    "if PC in register-list");
6419     break;
6420   case ARM::sysSTMIA_UPD:
6421   case ARM::sysSTMDA_UPD:
6422   case ARM::sysSTMDB_UPD:
6423   case ARM::sysSTMIB_UPD:
6424     return Error(Operands[2]->getStartLoc(),
6425                  "system STM cannot have writeback register");
6426   case ARM::tMUL:
6427     // The second source operand must be the same register as the destination
6428     // operand.
6429     //
6430     // In this case, we must directly check the parsed operands because the
6431     // cvtThumbMultiply() function is written in such a way that it guarantees
6432     // this first statement is always true for the new Inst.  Essentially, the
6433     // destination is unconditionally copied into the second source operand
6434     // without checking to see if it matches what we actually parsed.
6435     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6436                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6437         (((ARMOperand &)*Operands[3]).getReg() !=
6438          ((ARMOperand &)*Operands[4]).getReg())) {
6439       return Error(Operands[3]->getStartLoc(),
6440                    "destination register must match source register");
6441     }
6442     break;
6443 
6444   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6445   // so only issue a diagnostic for thumb1. The instructions will be
6446   // switched to the t2 encodings in processInstruction() if necessary.
6447   case ARM::tPOP: {
6448     bool ListContainsBase;
6449     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6450         !isThumbTwo())
6451       return Error(Operands[2]->getStartLoc(),
6452                    "registers must be in range r0-r7 or pc");
6453     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
6454       return true;
6455     break;
6456   }
6457   case ARM::tPUSH: {
6458     bool ListContainsBase;
6459     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6460         !isThumbTwo())
6461       return Error(Operands[2]->getStartLoc(),
6462                    "registers must be in range r0-r7 or lr");
6463     if (validatetSTMRegList(Inst, Operands, 2))
6464       return true;
6465     break;
6466   }
6467   case ARM::tSTMIA_UPD: {
6468     bool ListContainsBase, InvalidLowList;
6469     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6470                                           0, ListContainsBase);
6471     if (InvalidLowList && !isThumbTwo())
6472       return Error(Operands[4]->getStartLoc(),
6473                    "registers must be in range r0-r7");
6474 
6475     // This would be converted to a 32-bit stm, but that's not valid if the
6476     // writeback register is in the list.
6477     if (InvalidLowList && ListContainsBase)
6478       return Error(Operands[4]->getStartLoc(),
6479                    "writeback operator '!' not allowed when base register "
6480                    "in register list");
6481 
6482     if (validatetSTMRegList(Inst, Operands, 4))
6483       return true;
6484     break;
6485   }
6486   case ARM::tADDrSP:
6487     // If the non-SP source operand and the destination operand are not the
6488     // same, we need thumb2 (for the wide encoding), or we have an error.
6489     if (!isThumbTwo() &&
6490         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6491       return Error(Operands[4]->getStartLoc(),
6492                    "source register must be the same as destination");
6493     }
6494     break;
6495 
6496   // Final range checking for Thumb unconditional branch instructions.
6497   case ARM::tB:
6498     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6499       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6500     break;
6501   case ARM::t2B: {
6502     int op = (Operands[2]->isImm()) ? 2 : 3;
6503     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6504       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6505     break;
6506   }
6507   // Final range checking for Thumb conditional branch instructions.
6508   case ARM::tBcc:
6509     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6510       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6511     break;
6512   case ARM::t2Bcc: {
6513     int Op = (Operands[2]->isImm()) ? 2 : 3;
6514     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6515       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6516     break;
6517   }
6518   case ARM::tCBZ:
6519   case ARM::tCBNZ: {
6520     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
6521       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6522     break;
6523   }
6524   case ARM::MOVi16:
6525   case ARM::MOVTi16:
6526   case ARM::t2MOVi16:
6527   case ARM::t2MOVTi16:
6528     {
6529     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6530     // especially when we turn it into a movw and the expression <symbol> does
6531     // not have a :lower16: or :upper16 as part of the expression.  We don't
6532     // want the behavior of silently truncating, which can be unexpected and
6533     // lead to bugs that are difficult to find since this is an easy mistake
6534     // to make.
6535     int i = (Operands[3]->isImm()) ? 3 : 4;
6536     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6537     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6538     if (CE) break;
6539     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6540     if (!E) break;
6541     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6542     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6543                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6544       return Error(
6545           Op.getStartLoc(),
6546           "immediate expression for mov requires :lower16: or :upper16");
6547     break;
6548   }
6549   case ARM::HINT:
6550   case ARM::t2HINT:
6551     if (hasRAS()) {
6552       // ESB is not predicable (pred must be AL)
6553       unsigned Imm8 = Inst.getOperand(0).getImm();
6554       unsigned Pred = Inst.getOperand(1).getImm();
6555       if (Imm8 == 0x10 && Pred != ARMCC::AL)
6556         return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
6557                                                  "predicable, but condition "
6558                                                  "code specified");
6559     }
6560     // Without the RAS extension, this behaves as any other unallocated hint.
6561     break;
6562   }
6563 
6564   return false;
6565 }
6566 
6567 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6568   switch(Opc) {
6569   default: llvm_unreachable("unexpected opcode!");
6570   // VST1LN
6571   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6572   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6573   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6574   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6575   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6576   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6577   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6578   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6579   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6580 
6581   // VST2LN
6582   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6583   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6584   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6585   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6586   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6587 
6588   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6589   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6590   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6591   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6592   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6593 
6594   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6595   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6596   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6597   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6598   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6599 
6600   // VST3LN
6601   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6602   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6603   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6604   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6605   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6606   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6607   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6608   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6609   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6610   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6611   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6612   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6613   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6614   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6615   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6616 
6617   // VST3
6618   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6619   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6620   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6621   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6622   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6623   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6624   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6625   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6626   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6627   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6628   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6629   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6630   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6631   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6632   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6633   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6634   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6635   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6636 
6637   // VST4LN
6638   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6639   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6640   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6641   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6642   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6643   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6644   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6645   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6646   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6647   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6648   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6649   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6650   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6651   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6652   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6653 
6654   // VST4
6655   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6656   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6657   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6658   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6659   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6660   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6661   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6662   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6663   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6664   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6665   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6666   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6667   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
6668   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
6669   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
6670   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
6671   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
6672   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
6673   }
6674 }
6675 
6676 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
6677   switch(Opc) {
6678   default: llvm_unreachable("unexpected opcode!");
6679   // VLD1LN
6680   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6681   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6682   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6683   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6684   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6685   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6686   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
6687   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
6688   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
6689 
6690   // VLD2LN
6691   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6692   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6693   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6694   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
6695   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6696   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6697   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6698   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6699   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
6700   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6701   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
6702   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
6703   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
6704   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
6705   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
6706 
6707   // VLD3DUP
6708   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6709   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6710   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6711   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
6712   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6713   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6714   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6715   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6716   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6717   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
6718   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6719   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6720   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
6721   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
6722   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
6723   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
6724   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
6725   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
6726 
6727   // VLD3LN
6728   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6729   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6730   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6731   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
6732   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6733   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6734   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6735   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6736   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
6737   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6738   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
6739   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
6740   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
6741   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
6742   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
6743 
6744   // VLD3
6745   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6746   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6747   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6748   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6749   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6750   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6751   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6752   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6753   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6754   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6755   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6756   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6757   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
6758   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
6759   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
6760   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
6761   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
6762   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
6763 
6764   // VLD4LN
6765   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6766   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6767   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6768   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6769   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6770   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6771   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6772   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6773   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6774   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6775   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
6776   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
6777   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
6778   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
6779   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
6780 
6781   // VLD4DUP
6782   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6783   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6784   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6785   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
6786   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
6787   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6788   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6789   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6790   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6791   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
6792   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
6793   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6794   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
6795   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
6796   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
6797   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
6798   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
6799   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
6800 
6801   // VLD4
6802   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6803   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6804   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6805   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6806   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6807   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6808   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6809   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6810   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6811   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6812   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6813   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6814   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
6815   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
6816   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
6817   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
6818   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
6819   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
6820   }
6821 }
6822 
6823 bool ARMAsmParser::processInstruction(MCInst &Inst,
6824                                       const OperandVector &Operands,
6825                                       MCStreamer &Out) {
6826   // Check if we have the wide qualifier, because if it's present we
6827   // must avoid selecting a 16-bit thumb instruction.
6828   bool HasWideQualifier = false;
6829   for (auto &Op : Operands) {
6830     ARMOperand &ARMOp = static_cast<ARMOperand&>(*Op);
6831     if (ARMOp.isToken() && ARMOp.getToken() == ".w") {
6832       HasWideQualifier = true;
6833       break;
6834     }
6835   }
6836 
6837   switch (Inst.getOpcode()) {
6838   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
6839   case ARM::LDRT_POST:
6840   case ARM::LDRBT_POST: {
6841     const unsigned Opcode =
6842       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
6843                                            : ARM::LDRBT_POST_IMM;
6844     MCInst TmpInst;
6845     TmpInst.setOpcode(Opcode);
6846     TmpInst.addOperand(Inst.getOperand(0));
6847     TmpInst.addOperand(Inst.getOperand(1));
6848     TmpInst.addOperand(Inst.getOperand(1));
6849     TmpInst.addOperand(MCOperand::createReg(0));
6850     TmpInst.addOperand(MCOperand::createImm(0));
6851     TmpInst.addOperand(Inst.getOperand(2));
6852     TmpInst.addOperand(Inst.getOperand(3));
6853     Inst = TmpInst;
6854     return true;
6855   }
6856   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
6857   case ARM::STRT_POST:
6858   case ARM::STRBT_POST: {
6859     const unsigned Opcode =
6860       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
6861                                            : ARM::STRBT_POST_IMM;
6862     MCInst TmpInst;
6863     TmpInst.setOpcode(Opcode);
6864     TmpInst.addOperand(Inst.getOperand(1));
6865     TmpInst.addOperand(Inst.getOperand(0));
6866     TmpInst.addOperand(Inst.getOperand(1));
6867     TmpInst.addOperand(MCOperand::createReg(0));
6868     TmpInst.addOperand(MCOperand::createImm(0));
6869     TmpInst.addOperand(Inst.getOperand(2));
6870     TmpInst.addOperand(Inst.getOperand(3));
6871     Inst = TmpInst;
6872     return true;
6873   }
6874   // Alias for alternate form of 'ADR Rd, #imm' instruction.
6875   case ARM::ADDri: {
6876     if (Inst.getOperand(1).getReg() != ARM::PC ||
6877         Inst.getOperand(5).getReg() != 0 ||
6878         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
6879       return false;
6880     MCInst TmpInst;
6881     TmpInst.setOpcode(ARM::ADR);
6882     TmpInst.addOperand(Inst.getOperand(0));
6883     if (Inst.getOperand(2).isImm()) {
6884       // Immediate (mod_imm) will be in its encoded form, we must unencode it
6885       // before passing it to the ADR instruction.
6886       unsigned Enc = Inst.getOperand(2).getImm();
6887       TmpInst.addOperand(MCOperand::createImm(
6888         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
6889     } else {
6890       // Turn PC-relative expression into absolute expression.
6891       // Reading PC provides the start of the current instruction + 8 and
6892       // the transform to adr is biased by that.
6893       MCSymbol *Dot = getContext().createTempSymbol();
6894       Out.EmitLabel(Dot);
6895       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
6896       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
6897                                                      MCSymbolRefExpr::VK_None,
6898                                                      getContext());
6899       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
6900       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
6901                                                      getContext());
6902       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
6903                                                         getContext());
6904       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
6905     }
6906     TmpInst.addOperand(Inst.getOperand(3));
6907     TmpInst.addOperand(Inst.getOperand(4));
6908     Inst = TmpInst;
6909     return true;
6910   }
6911   // Aliases for alternate PC+imm syntax of LDR instructions.
6912   case ARM::t2LDRpcrel:
6913     // Select the narrow version if the immediate will fit.
6914     if (Inst.getOperand(1).getImm() > 0 &&
6915         Inst.getOperand(1).getImm() <= 0xff &&
6916         !HasWideQualifier)
6917       Inst.setOpcode(ARM::tLDRpci);
6918     else
6919       Inst.setOpcode(ARM::t2LDRpci);
6920     return true;
6921   case ARM::t2LDRBpcrel:
6922     Inst.setOpcode(ARM::t2LDRBpci);
6923     return true;
6924   case ARM::t2LDRHpcrel:
6925     Inst.setOpcode(ARM::t2LDRHpci);
6926     return true;
6927   case ARM::t2LDRSBpcrel:
6928     Inst.setOpcode(ARM::t2LDRSBpci);
6929     return true;
6930   case ARM::t2LDRSHpcrel:
6931     Inst.setOpcode(ARM::t2LDRSHpci);
6932     return true;
6933   case ARM::LDRConstPool:
6934   case ARM::tLDRConstPool:
6935   case ARM::t2LDRConstPool: {
6936     // Pseudo instruction ldr rt, =immediate is converted to a
6937     // MOV rt, immediate if immediate is known and representable
6938     // otherwise we create a constant pool entry that we load from.
6939     MCInst TmpInst;
6940     if (Inst.getOpcode() == ARM::LDRConstPool)
6941       TmpInst.setOpcode(ARM::LDRi12);
6942     else if (Inst.getOpcode() == ARM::tLDRConstPool)
6943       TmpInst.setOpcode(ARM::tLDRpci);
6944     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
6945       TmpInst.setOpcode(ARM::t2LDRpci);
6946     const ARMOperand &PoolOperand =
6947       (HasWideQualifier ?
6948        static_cast<ARMOperand &>(*Operands[4]) :
6949        static_cast<ARMOperand &>(*Operands[3]));
6950     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
6951     // If SubExprVal is a constant we may be able to use a MOV
6952     if (isa<MCConstantExpr>(SubExprVal) &&
6953         Inst.getOperand(0).getReg() != ARM::PC &&
6954         Inst.getOperand(0).getReg() != ARM::SP) {
6955       int64_t Value =
6956         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
6957       bool UseMov  = true;
6958       bool MovHasS = true;
6959       if (Inst.getOpcode() == ARM::LDRConstPool) {
6960         // ARM Constant
6961         if (ARM_AM::getSOImmVal(Value) != -1) {
6962           Value = ARM_AM::getSOImmVal(Value);
6963           TmpInst.setOpcode(ARM::MOVi);
6964         }
6965         else if (ARM_AM::getSOImmVal(~Value) != -1) {
6966           Value = ARM_AM::getSOImmVal(~Value);
6967           TmpInst.setOpcode(ARM::MVNi);
6968         }
6969         else if (hasV6T2Ops() &&
6970                  Value >=0 && Value < 65536) {
6971           TmpInst.setOpcode(ARM::MOVi16);
6972           MovHasS = false;
6973         }
6974         else
6975           UseMov = false;
6976       }
6977       else {
6978         // Thumb/Thumb2 Constant
6979         if (hasThumb2() &&
6980             ARM_AM::getT2SOImmVal(Value) != -1)
6981           TmpInst.setOpcode(ARM::t2MOVi);
6982         else if (hasThumb2() &&
6983                  ARM_AM::getT2SOImmVal(~Value) != -1) {
6984           TmpInst.setOpcode(ARM::t2MVNi);
6985           Value = ~Value;
6986         }
6987         else if (hasV8MBaseline() &&
6988                  Value >=0 && Value < 65536) {
6989           TmpInst.setOpcode(ARM::t2MOVi16);
6990           MovHasS = false;
6991         }
6992         else
6993           UseMov = false;
6994       }
6995       if (UseMov) {
6996         TmpInst.addOperand(Inst.getOperand(0));           // Rt
6997         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
6998         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
6999         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7000         if (MovHasS)
7001           TmpInst.addOperand(MCOperand::createReg(0));    // S
7002         Inst = TmpInst;
7003         return true;
7004       }
7005     }
7006     // No opportunity to use MOV/MVN create constant pool
7007     const MCExpr *CPLoc =
7008       getTargetStreamer().addConstantPoolEntry(SubExprVal,
7009                                                PoolOperand.getStartLoc());
7010     TmpInst.addOperand(Inst.getOperand(0));           // Rt
7011     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
7012     if (TmpInst.getOpcode() == ARM::LDRi12)
7013       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
7014     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7015     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7016     Inst = TmpInst;
7017     return true;
7018   }
7019   // Handle NEON VST complex aliases.
7020   case ARM::VST1LNdWB_register_Asm_8:
7021   case ARM::VST1LNdWB_register_Asm_16:
7022   case ARM::VST1LNdWB_register_Asm_32: {
7023     MCInst TmpInst;
7024     // Shuffle the operands around so the lane index operand is in the
7025     // right place.
7026     unsigned Spacing;
7027     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7028     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7029     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7030     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7031     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7032     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7033     TmpInst.addOperand(Inst.getOperand(1)); // lane
7034     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7035     TmpInst.addOperand(Inst.getOperand(6));
7036     Inst = TmpInst;
7037     return true;
7038   }
7039 
7040   case ARM::VST2LNdWB_register_Asm_8:
7041   case ARM::VST2LNdWB_register_Asm_16:
7042   case ARM::VST2LNdWB_register_Asm_32:
7043   case ARM::VST2LNqWB_register_Asm_16:
7044   case ARM::VST2LNqWB_register_Asm_32: {
7045     MCInst TmpInst;
7046     // Shuffle the operands around so the lane index operand is in the
7047     // right place.
7048     unsigned Spacing;
7049     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7050     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7051     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7052     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7053     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7054     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7055     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7056                                             Spacing));
7057     TmpInst.addOperand(Inst.getOperand(1)); // lane
7058     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7059     TmpInst.addOperand(Inst.getOperand(6));
7060     Inst = TmpInst;
7061     return true;
7062   }
7063 
7064   case ARM::VST3LNdWB_register_Asm_8:
7065   case ARM::VST3LNdWB_register_Asm_16:
7066   case ARM::VST3LNdWB_register_Asm_32:
7067   case ARM::VST3LNqWB_register_Asm_16:
7068   case ARM::VST3LNqWB_register_Asm_32: {
7069     MCInst TmpInst;
7070     // Shuffle the operands around so the lane index operand is in the
7071     // right place.
7072     unsigned Spacing;
7073     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7074     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7075     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7076     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7077     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7078     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7079     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7080                                             Spacing));
7081     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7082                                             Spacing * 2));
7083     TmpInst.addOperand(Inst.getOperand(1)); // lane
7084     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7085     TmpInst.addOperand(Inst.getOperand(6));
7086     Inst = TmpInst;
7087     return true;
7088   }
7089 
7090   case ARM::VST4LNdWB_register_Asm_8:
7091   case ARM::VST4LNdWB_register_Asm_16:
7092   case ARM::VST4LNdWB_register_Asm_32:
7093   case ARM::VST4LNqWB_register_Asm_16:
7094   case ARM::VST4LNqWB_register_Asm_32: {
7095     MCInst TmpInst;
7096     // Shuffle the operands around so the lane index operand is in the
7097     // right place.
7098     unsigned Spacing;
7099     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7100     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7101     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7102     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7103     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7104     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7105     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7106                                             Spacing));
7107     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7108                                             Spacing * 2));
7109     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7110                                             Spacing * 3));
7111     TmpInst.addOperand(Inst.getOperand(1)); // lane
7112     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7113     TmpInst.addOperand(Inst.getOperand(6));
7114     Inst = TmpInst;
7115     return true;
7116   }
7117 
7118   case ARM::VST1LNdWB_fixed_Asm_8:
7119   case ARM::VST1LNdWB_fixed_Asm_16:
7120   case ARM::VST1LNdWB_fixed_Asm_32: {
7121     MCInst TmpInst;
7122     // Shuffle the operands around so the lane index operand is in the
7123     // right place.
7124     unsigned Spacing;
7125     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7126     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7127     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7128     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7129     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7130     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7131     TmpInst.addOperand(Inst.getOperand(1)); // lane
7132     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7133     TmpInst.addOperand(Inst.getOperand(5));
7134     Inst = TmpInst;
7135     return true;
7136   }
7137 
7138   case ARM::VST2LNdWB_fixed_Asm_8:
7139   case ARM::VST2LNdWB_fixed_Asm_16:
7140   case ARM::VST2LNdWB_fixed_Asm_32:
7141   case ARM::VST2LNqWB_fixed_Asm_16:
7142   case ARM::VST2LNqWB_fixed_Asm_32: {
7143     MCInst TmpInst;
7144     // Shuffle the operands around so the lane index operand is in the
7145     // right place.
7146     unsigned Spacing;
7147     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7148     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7149     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7150     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7151     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7152     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7153     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7154                                             Spacing));
7155     TmpInst.addOperand(Inst.getOperand(1)); // lane
7156     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7157     TmpInst.addOperand(Inst.getOperand(5));
7158     Inst = TmpInst;
7159     return true;
7160   }
7161 
7162   case ARM::VST3LNdWB_fixed_Asm_8:
7163   case ARM::VST3LNdWB_fixed_Asm_16:
7164   case ARM::VST3LNdWB_fixed_Asm_32:
7165   case ARM::VST3LNqWB_fixed_Asm_16:
7166   case ARM::VST3LNqWB_fixed_Asm_32: {
7167     MCInst TmpInst;
7168     // Shuffle the operands around so the lane index operand is in the
7169     // right place.
7170     unsigned Spacing;
7171     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7172     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7173     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7174     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7175     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7176     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7177     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7178                                             Spacing));
7179     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7180                                             Spacing * 2));
7181     TmpInst.addOperand(Inst.getOperand(1)); // lane
7182     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7183     TmpInst.addOperand(Inst.getOperand(5));
7184     Inst = TmpInst;
7185     return true;
7186   }
7187 
7188   case ARM::VST4LNdWB_fixed_Asm_8:
7189   case ARM::VST4LNdWB_fixed_Asm_16:
7190   case ARM::VST4LNdWB_fixed_Asm_32:
7191   case ARM::VST4LNqWB_fixed_Asm_16:
7192   case ARM::VST4LNqWB_fixed_Asm_32: {
7193     MCInst TmpInst;
7194     // Shuffle the operands around so the lane index operand is in the
7195     // right place.
7196     unsigned Spacing;
7197     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7198     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7199     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7200     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7201     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7202     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7203     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7204                                             Spacing));
7205     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7206                                             Spacing * 2));
7207     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7208                                             Spacing * 3));
7209     TmpInst.addOperand(Inst.getOperand(1)); // lane
7210     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7211     TmpInst.addOperand(Inst.getOperand(5));
7212     Inst = TmpInst;
7213     return true;
7214   }
7215 
7216   case ARM::VST1LNdAsm_8:
7217   case ARM::VST1LNdAsm_16:
7218   case ARM::VST1LNdAsm_32: {
7219     MCInst TmpInst;
7220     // Shuffle the operands around so the lane index operand is in the
7221     // right place.
7222     unsigned Spacing;
7223     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7224     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7225     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7226     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7227     TmpInst.addOperand(Inst.getOperand(1)); // lane
7228     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7229     TmpInst.addOperand(Inst.getOperand(5));
7230     Inst = TmpInst;
7231     return true;
7232   }
7233 
7234   case ARM::VST2LNdAsm_8:
7235   case ARM::VST2LNdAsm_16:
7236   case ARM::VST2LNdAsm_32:
7237   case ARM::VST2LNqAsm_16:
7238   case ARM::VST2LNqAsm_32: {
7239     MCInst TmpInst;
7240     // Shuffle the operands around so the lane index operand is in the
7241     // right place.
7242     unsigned Spacing;
7243     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7244     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7245     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7246     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7247     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7248                                             Spacing));
7249     TmpInst.addOperand(Inst.getOperand(1)); // lane
7250     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7251     TmpInst.addOperand(Inst.getOperand(5));
7252     Inst = TmpInst;
7253     return true;
7254   }
7255 
7256   case ARM::VST3LNdAsm_8:
7257   case ARM::VST3LNdAsm_16:
7258   case ARM::VST3LNdAsm_32:
7259   case ARM::VST3LNqAsm_16:
7260   case ARM::VST3LNqAsm_32: {
7261     MCInst TmpInst;
7262     // Shuffle the operands around so the lane index operand is in the
7263     // right place.
7264     unsigned Spacing;
7265     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7266     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7267     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7268     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7269     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7270                                             Spacing));
7271     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7272                                             Spacing * 2));
7273     TmpInst.addOperand(Inst.getOperand(1)); // lane
7274     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7275     TmpInst.addOperand(Inst.getOperand(5));
7276     Inst = TmpInst;
7277     return true;
7278   }
7279 
7280   case ARM::VST4LNdAsm_8:
7281   case ARM::VST4LNdAsm_16:
7282   case ARM::VST4LNdAsm_32:
7283   case ARM::VST4LNqAsm_16:
7284   case ARM::VST4LNqAsm_32: {
7285     MCInst TmpInst;
7286     // Shuffle the operands around so the lane index operand is in the
7287     // right place.
7288     unsigned Spacing;
7289     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7290     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7291     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7292     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7293     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7294                                             Spacing));
7295     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7296                                             Spacing * 2));
7297     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7298                                             Spacing * 3));
7299     TmpInst.addOperand(Inst.getOperand(1)); // lane
7300     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7301     TmpInst.addOperand(Inst.getOperand(5));
7302     Inst = TmpInst;
7303     return true;
7304   }
7305 
7306   // Handle NEON VLD complex aliases.
7307   case ARM::VLD1LNdWB_register_Asm_8:
7308   case ARM::VLD1LNdWB_register_Asm_16:
7309   case ARM::VLD1LNdWB_register_Asm_32: {
7310     MCInst TmpInst;
7311     // Shuffle the operands around so the lane index operand is in the
7312     // right place.
7313     unsigned Spacing;
7314     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7315     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7316     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7317     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7318     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7319     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7320     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7321     TmpInst.addOperand(Inst.getOperand(1)); // lane
7322     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7323     TmpInst.addOperand(Inst.getOperand(6));
7324     Inst = TmpInst;
7325     return true;
7326   }
7327 
7328   case ARM::VLD2LNdWB_register_Asm_8:
7329   case ARM::VLD2LNdWB_register_Asm_16:
7330   case ARM::VLD2LNdWB_register_Asm_32:
7331   case ARM::VLD2LNqWB_register_Asm_16:
7332   case ARM::VLD2LNqWB_register_Asm_32: {
7333     MCInst TmpInst;
7334     // Shuffle the operands around so the lane index operand is in the
7335     // right place.
7336     unsigned Spacing;
7337     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7338     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7339     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7340                                             Spacing));
7341     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7342     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7343     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7344     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7345     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7346     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7347                                             Spacing));
7348     TmpInst.addOperand(Inst.getOperand(1)); // lane
7349     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7350     TmpInst.addOperand(Inst.getOperand(6));
7351     Inst = TmpInst;
7352     return true;
7353   }
7354 
7355   case ARM::VLD3LNdWB_register_Asm_8:
7356   case ARM::VLD3LNdWB_register_Asm_16:
7357   case ARM::VLD3LNdWB_register_Asm_32:
7358   case ARM::VLD3LNqWB_register_Asm_16:
7359   case ARM::VLD3LNqWB_register_Asm_32: {
7360     MCInst TmpInst;
7361     // Shuffle the operands around so the lane index operand is in the
7362     // right place.
7363     unsigned Spacing;
7364     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7365     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7366     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7367                                             Spacing));
7368     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7369                                             Spacing * 2));
7370     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7371     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7372     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7373     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7374     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7375     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7376                                             Spacing));
7377     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7378                                             Spacing * 2));
7379     TmpInst.addOperand(Inst.getOperand(1)); // lane
7380     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7381     TmpInst.addOperand(Inst.getOperand(6));
7382     Inst = TmpInst;
7383     return true;
7384   }
7385 
7386   case ARM::VLD4LNdWB_register_Asm_8:
7387   case ARM::VLD4LNdWB_register_Asm_16:
7388   case ARM::VLD4LNdWB_register_Asm_32:
7389   case ARM::VLD4LNqWB_register_Asm_16:
7390   case ARM::VLD4LNqWB_register_Asm_32: {
7391     MCInst TmpInst;
7392     // Shuffle the operands around so the lane index operand is in the
7393     // right place.
7394     unsigned Spacing;
7395     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7396     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7397     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7398                                             Spacing));
7399     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7400                                             Spacing * 2));
7401     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7402                                             Spacing * 3));
7403     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7404     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7405     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7406     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7407     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7408     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7409                                             Spacing));
7410     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7411                                             Spacing * 2));
7412     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7413                                             Spacing * 3));
7414     TmpInst.addOperand(Inst.getOperand(1)); // lane
7415     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7416     TmpInst.addOperand(Inst.getOperand(6));
7417     Inst = TmpInst;
7418     return true;
7419   }
7420 
7421   case ARM::VLD1LNdWB_fixed_Asm_8:
7422   case ARM::VLD1LNdWB_fixed_Asm_16:
7423   case ARM::VLD1LNdWB_fixed_Asm_32: {
7424     MCInst TmpInst;
7425     // Shuffle the operands around so the lane index operand is in the
7426     // right place.
7427     unsigned Spacing;
7428     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7429     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7430     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7431     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7432     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7433     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7434     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7435     TmpInst.addOperand(Inst.getOperand(1)); // lane
7436     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7437     TmpInst.addOperand(Inst.getOperand(5));
7438     Inst = TmpInst;
7439     return true;
7440   }
7441 
7442   case ARM::VLD2LNdWB_fixed_Asm_8:
7443   case ARM::VLD2LNdWB_fixed_Asm_16:
7444   case ARM::VLD2LNdWB_fixed_Asm_32:
7445   case ARM::VLD2LNqWB_fixed_Asm_16:
7446   case ARM::VLD2LNqWB_fixed_Asm_32: {
7447     MCInst TmpInst;
7448     // Shuffle the operands around so the lane index operand is in the
7449     // right place.
7450     unsigned Spacing;
7451     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7452     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7453     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7454                                             Spacing));
7455     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7456     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7457     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7458     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7459     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7460     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7461                                             Spacing));
7462     TmpInst.addOperand(Inst.getOperand(1)); // lane
7463     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7464     TmpInst.addOperand(Inst.getOperand(5));
7465     Inst = TmpInst;
7466     return true;
7467   }
7468 
7469   case ARM::VLD3LNdWB_fixed_Asm_8:
7470   case ARM::VLD3LNdWB_fixed_Asm_16:
7471   case ARM::VLD3LNdWB_fixed_Asm_32:
7472   case ARM::VLD3LNqWB_fixed_Asm_16:
7473   case ARM::VLD3LNqWB_fixed_Asm_32: {
7474     MCInst TmpInst;
7475     // Shuffle the operands around so the lane index operand is in the
7476     // right place.
7477     unsigned Spacing;
7478     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7479     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7480     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7481                                             Spacing));
7482     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7483                                             Spacing * 2));
7484     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7485     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7486     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7487     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7488     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7489     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7490                                             Spacing));
7491     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7492                                             Spacing * 2));
7493     TmpInst.addOperand(Inst.getOperand(1)); // lane
7494     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7495     TmpInst.addOperand(Inst.getOperand(5));
7496     Inst = TmpInst;
7497     return true;
7498   }
7499 
7500   case ARM::VLD4LNdWB_fixed_Asm_8:
7501   case ARM::VLD4LNdWB_fixed_Asm_16:
7502   case ARM::VLD4LNdWB_fixed_Asm_32:
7503   case ARM::VLD4LNqWB_fixed_Asm_16:
7504   case ARM::VLD4LNqWB_fixed_Asm_32: {
7505     MCInst TmpInst;
7506     // Shuffle the operands around so the lane index operand is in the
7507     // right place.
7508     unsigned Spacing;
7509     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7510     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7511     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7512                                             Spacing));
7513     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7514                                             Spacing * 2));
7515     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7516                                             Spacing * 3));
7517     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7518     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7519     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7520     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7521     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7522     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7523                                             Spacing));
7524     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7525                                             Spacing * 2));
7526     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7527                                             Spacing * 3));
7528     TmpInst.addOperand(Inst.getOperand(1)); // lane
7529     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7530     TmpInst.addOperand(Inst.getOperand(5));
7531     Inst = TmpInst;
7532     return true;
7533   }
7534 
7535   case ARM::VLD1LNdAsm_8:
7536   case ARM::VLD1LNdAsm_16:
7537   case ARM::VLD1LNdAsm_32: {
7538     MCInst TmpInst;
7539     // Shuffle the operands around so the lane index operand is in the
7540     // right place.
7541     unsigned Spacing;
7542     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7543     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7544     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7545     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7546     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7547     TmpInst.addOperand(Inst.getOperand(1)); // lane
7548     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7549     TmpInst.addOperand(Inst.getOperand(5));
7550     Inst = TmpInst;
7551     return true;
7552   }
7553 
7554   case ARM::VLD2LNdAsm_8:
7555   case ARM::VLD2LNdAsm_16:
7556   case ARM::VLD2LNdAsm_32:
7557   case ARM::VLD2LNqAsm_16:
7558   case ARM::VLD2LNqAsm_32: {
7559     MCInst TmpInst;
7560     // Shuffle the operands around so the lane index operand is in the
7561     // right place.
7562     unsigned Spacing;
7563     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7564     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7565     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7566                                             Spacing));
7567     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7568     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7569     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7570     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7571                                             Spacing));
7572     TmpInst.addOperand(Inst.getOperand(1)); // lane
7573     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7574     TmpInst.addOperand(Inst.getOperand(5));
7575     Inst = TmpInst;
7576     return true;
7577   }
7578 
7579   case ARM::VLD3LNdAsm_8:
7580   case ARM::VLD3LNdAsm_16:
7581   case ARM::VLD3LNdAsm_32:
7582   case ARM::VLD3LNqAsm_16:
7583   case ARM::VLD3LNqAsm_32: {
7584     MCInst TmpInst;
7585     // Shuffle the operands around so the lane index operand is in the
7586     // right place.
7587     unsigned Spacing;
7588     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7589     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7590     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7591                                             Spacing));
7592     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7593                                             Spacing * 2));
7594     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7595     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7596     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7597     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7598                                             Spacing));
7599     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7600                                             Spacing * 2));
7601     TmpInst.addOperand(Inst.getOperand(1)); // lane
7602     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7603     TmpInst.addOperand(Inst.getOperand(5));
7604     Inst = TmpInst;
7605     return true;
7606   }
7607 
7608   case ARM::VLD4LNdAsm_8:
7609   case ARM::VLD4LNdAsm_16:
7610   case ARM::VLD4LNdAsm_32:
7611   case ARM::VLD4LNqAsm_16:
7612   case ARM::VLD4LNqAsm_32: {
7613     MCInst TmpInst;
7614     // Shuffle the operands around so the lane index operand is in the
7615     // right place.
7616     unsigned Spacing;
7617     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7618     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7619     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7620                                             Spacing));
7621     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7622                                             Spacing * 2));
7623     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7624                                             Spacing * 3));
7625     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7626     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7627     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7628     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7629                                             Spacing));
7630     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7631                                             Spacing * 2));
7632     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7633                                             Spacing * 3));
7634     TmpInst.addOperand(Inst.getOperand(1)); // lane
7635     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7636     TmpInst.addOperand(Inst.getOperand(5));
7637     Inst = TmpInst;
7638     return true;
7639   }
7640 
7641   // VLD3DUP single 3-element structure to all lanes instructions.
7642   case ARM::VLD3DUPdAsm_8:
7643   case ARM::VLD3DUPdAsm_16:
7644   case ARM::VLD3DUPdAsm_32:
7645   case ARM::VLD3DUPqAsm_8:
7646   case ARM::VLD3DUPqAsm_16:
7647   case ARM::VLD3DUPqAsm_32: {
7648     MCInst TmpInst;
7649     unsigned Spacing;
7650     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7651     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7652     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7653                                             Spacing));
7654     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7655                                             Spacing * 2));
7656     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7657     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7658     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7659     TmpInst.addOperand(Inst.getOperand(4));
7660     Inst = TmpInst;
7661     return true;
7662   }
7663 
7664   case ARM::VLD3DUPdWB_fixed_Asm_8:
7665   case ARM::VLD3DUPdWB_fixed_Asm_16:
7666   case ARM::VLD3DUPdWB_fixed_Asm_32:
7667   case ARM::VLD3DUPqWB_fixed_Asm_8:
7668   case ARM::VLD3DUPqWB_fixed_Asm_16:
7669   case ARM::VLD3DUPqWB_fixed_Asm_32: {
7670     MCInst TmpInst;
7671     unsigned Spacing;
7672     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7673     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7674     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7675                                             Spacing));
7676     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7677                                             Spacing * 2));
7678     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7679     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7680     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7681     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7682     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7683     TmpInst.addOperand(Inst.getOperand(4));
7684     Inst = TmpInst;
7685     return true;
7686   }
7687 
7688   case ARM::VLD3DUPdWB_register_Asm_8:
7689   case ARM::VLD3DUPdWB_register_Asm_16:
7690   case ARM::VLD3DUPdWB_register_Asm_32:
7691   case ARM::VLD3DUPqWB_register_Asm_8:
7692   case ARM::VLD3DUPqWB_register_Asm_16:
7693   case ARM::VLD3DUPqWB_register_Asm_32: {
7694     MCInst TmpInst;
7695     unsigned Spacing;
7696     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7697     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7698     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7699                                             Spacing));
7700     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7701                                             Spacing * 2));
7702     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7703     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7704     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7705     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7706     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7707     TmpInst.addOperand(Inst.getOperand(5));
7708     Inst = TmpInst;
7709     return true;
7710   }
7711 
7712   // VLD3 multiple 3-element structure instructions.
7713   case ARM::VLD3dAsm_8:
7714   case ARM::VLD3dAsm_16:
7715   case ARM::VLD3dAsm_32:
7716   case ARM::VLD3qAsm_8:
7717   case ARM::VLD3qAsm_16:
7718   case ARM::VLD3qAsm_32: {
7719     MCInst TmpInst;
7720     unsigned Spacing;
7721     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7722     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7723     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7724                                             Spacing));
7725     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7726                                             Spacing * 2));
7727     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7728     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7729     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7730     TmpInst.addOperand(Inst.getOperand(4));
7731     Inst = TmpInst;
7732     return true;
7733   }
7734 
7735   case ARM::VLD3dWB_fixed_Asm_8:
7736   case ARM::VLD3dWB_fixed_Asm_16:
7737   case ARM::VLD3dWB_fixed_Asm_32:
7738   case ARM::VLD3qWB_fixed_Asm_8:
7739   case ARM::VLD3qWB_fixed_Asm_16:
7740   case ARM::VLD3qWB_fixed_Asm_32: {
7741     MCInst TmpInst;
7742     unsigned Spacing;
7743     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7744     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7745     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7746                                             Spacing));
7747     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7748                                             Spacing * 2));
7749     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7750     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7751     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7752     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7753     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7754     TmpInst.addOperand(Inst.getOperand(4));
7755     Inst = TmpInst;
7756     return true;
7757   }
7758 
7759   case ARM::VLD3dWB_register_Asm_8:
7760   case ARM::VLD3dWB_register_Asm_16:
7761   case ARM::VLD3dWB_register_Asm_32:
7762   case ARM::VLD3qWB_register_Asm_8:
7763   case ARM::VLD3qWB_register_Asm_16:
7764   case ARM::VLD3qWB_register_Asm_32: {
7765     MCInst TmpInst;
7766     unsigned Spacing;
7767     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7768     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7769     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7770                                             Spacing));
7771     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7772                                             Spacing * 2));
7773     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7774     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7775     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7776     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7777     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7778     TmpInst.addOperand(Inst.getOperand(5));
7779     Inst = TmpInst;
7780     return true;
7781   }
7782 
7783   // VLD4DUP single 3-element structure to all lanes instructions.
7784   case ARM::VLD4DUPdAsm_8:
7785   case ARM::VLD4DUPdAsm_16:
7786   case ARM::VLD4DUPdAsm_32:
7787   case ARM::VLD4DUPqAsm_8:
7788   case ARM::VLD4DUPqAsm_16:
7789   case ARM::VLD4DUPqAsm_32: {
7790     MCInst TmpInst;
7791     unsigned Spacing;
7792     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7793     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7794     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7795                                             Spacing));
7796     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7797                                             Spacing * 2));
7798     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7799                                             Spacing * 3));
7800     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7801     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7802     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7803     TmpInst.addOperand(Inst.getOperand(4));
7804     Inst = TmpInst;
7805     return true;
7806   }
7807 
7808   case ARM::VLD4DUPdWB_fixed_Asm_8:
7809   case ARM::VLD4DUPdWB_fixed_Asm_16:
7810   case ARM::VLD4DUPdWB_fixed_Asm_32:
7811   case ARM::VLD4DUPqWB_fixed_Asm_8:
7812   case ARM::VLD4DUPqWB_fixed_Asm_16:
7813   case ARM::VLD4DUPqWB_fixed_Asm_32: {
7814     MCInst TmpInst;
7815     unsigned Spacing;
7816     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7817     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7818     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7819                                             Spacing));
7820     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7821                                             Spacing * 2));
7822     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7823                                             Spacing * 3));
7824     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7825     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7826     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7827     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7828     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7829     TmpInst.addOperand(Inst.getOperand(4));
7830     Inst = TmpInst;
7831     return true;
7832   }
7833 
7834   case ARM::VLD4DUPdWB_register_Asm_8:
7835   case ARM::VLD4DUPdWB_register_Asm_16:
7836   case ARM::VLD4DUPdWB_register_Asm_32:
7837   case ARM::VLD4DUPqWB_register_Asm_8:
7838   case ARM::VLD4DUPqWB_register_Asm_16:
7839   case ARM::VLD4DUPqWB_register_Asm_32: {
7840     MCInst TmpInst;
7841     unsigned Spacing;
7842     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7843     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7844     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7845                                             Spacing));
7846     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7847                                             Spacing * 2));
7848     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7849                                             Spacing * 3));
7850     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7851     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7852     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7853     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7854     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7855     TmpInst.addOperand(Inst.getOperand(5));
7856     Inst = TmpInst;
7857     return true;
7858   }
7859 
7860   // VLD4 multiple 4-element structure instructions.
7861   case ARM::VLD4dAsm_8:
7862   case ARM::VLD4dAsm_16:
7863   case ARM::VLD4dAsm_32:
7864   case ARM::VLD4qAsm_8:
7865   case ARM::VLD4qAsm_16:
7866   case ARM::VLD4qAsm_32: {
7867     MCInst TmpInst;
7868     unsigned Spacing;
7869     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7870     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7871     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7872                                             Spacing));
7873     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7874                                             Spacing * 2));
7875     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7876                                             Spacing * 3));
7877     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7878     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7879     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7880     TmpInst.addOperand(Inst.getOperand(4));
7881     Inst = TmpInst;
7882     return true;
7883   }
7884 
7885   case ARM::VLD4dWB_fixed_Asm_8:
7886   case ARM::VLD4dWB_fixed_Asm_16:
7887   case ARM::VLD4dWB_fixed_Asm_32:
7888   case ARM::VLD4qWB_fixed_Asm_8:
7889   case ARM::VLD4qWB_fixed_Asm_16:
7890   case ARM::VLD4qWB_fixed_Asm_32: {
7891     MCInst TmpInst;
7892     unsigned Spacing;
7893     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7894     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7895     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7896                                             Spacing));
7897     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7898                                             Spacing * 2));
7899     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7900                                             Spacing * 3));
7901     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7902     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7903     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7904     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7905     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7906     TmpInst.addOperand(Inst.getOperand(4));
7907     Inst = TmpInst;
7908     return true;
7909   }
7910 
7911   case ARM::VLD4dWB_register_Asm_8:
7912   case ARM::VLD4dWB_register_Asm_16:
7913   case ARM::VLD4dWB_register_Asm_32:
7914   case ARM::VLD4qWB_register_Asm_8:
7915   case ARM::VLD4qWB_register_Asm_16:
7916   case ARM::VLD4qWB_register_Asm_32: {
7917     MCInst TmpInst;
7918     unsigned Spacing;
7919     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7920     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7921     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7922                                             Spacing));
7923     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7924                                             Spacing * 2));
7925     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7926                                             Spacing * 3));
7927     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7928     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7929     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7930     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7931     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7932     TmpInst.addOperand(Inst.getOperand(5));
7933     Inst = TmpInst;
7934     return true;
7935   }
7936 
7937   // VST3 multiple 3-element structure instructions.
7938   case ARM::VST3dAsm_8:
7939   case ARM::VST3dAsm_16:
7940   case ARM::VST3dAsm_32:
7941   case ARM::VST3qAsm_8:
7942   case ARM::VST3qAsm_16:
7943   case ARM::VST3qAsm_32: {
7944     MCInst TmpInst;
7945     unsigned Spacing;
7946     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7947     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7948     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7949     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7950     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7951                                             Spacing));
7952     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7953                                             Spacing * 2));
7954     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7955     TmpInst.addOperand(Inst.getOperand(4));
7956     Inst = TmpInst;
7957     return true;
7958   }
7959 
7960   case ARM::VST3dWB_fixed_Asm_8:
7961   case ARM::VST3dWB_fixed_Asm_16:
7962   case ARM::VST3dWB_fixed_Asm_32:
7963   case ARM::VST3qWB_fixed_Asm_8:
7964   case ARM::VST3qWB_fixed_Asm_16:
7965   case ARM::VST3qWB_fixed_Asm_32: {
7966     MCInst TmpInst;
7967     unsigned Spacing;
7968     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7969     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7970     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7971     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7972     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7973     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7974     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7975                                             Spacing));
7976     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7977                                             Spacing * 2));
7978     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7979     TmpInst.addOperand(Inst.getOperand(4));
7980     Inst = TmpInst;
7981     return true;
7982   }
7983 
7984   case ARM::VST3dWB_register_Asm_8:
7985   case ARM::VST3dWB_register_Asm_16:
7986   case ARM::VST3dWB_register_Asm_32:
7987   case ARM::VST3qWB_register_Asm_8:
7988   case ARM::VST3qWB_register_Asm_16:
7989   case ARM::VST3qWB_register_Asm_32: {
7990     MCInst TmpInst;
7991     unsigned Spacing;
7992     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7993     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7994     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7995     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7996     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7997     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7998     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7999                                             Spacing));
8000     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8001                                             Spacing * 2));
8002     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8003     TmpInst.addOperand(Inst.getOperand(5));
8004     Inst = TmpInst;
8005     return true;
8006   }
8007 
8008   // VST4 multiple 3-element structure instructions.
8009   case ARM::VST4dAsm_8:
8010   case ARM::VST4dAsm_16:
8011   case ARM::VST4dAsm_32:
8012   case ARM::VST4qAsm_8:
8013   case ARM::VST4qAsm_16:
8014   case ARM::VST4qAsm_32: {
8015     MCInst TmpInst;
8016     unsigned Spacing;
8017     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8018     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8019     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8020     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8021     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8022                                             Spacing));
8023     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8024                                             Spacing * 2));
8025     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8026                                             Spacing * 3));
8027     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8028     TmpInst.addOperand(Inst.getOperand(4));
8029     Inst = TmpInst;
8030     return true;
8031   }
8032 
8033   case ARM::VST4dWB_fixed_Asm_8:
8034   case ARM::VST4dWB_fixed_Asm_16:
8035   case ARM::VST4dWB_fixed_Asm_32:
8036   case ARM::VST4qWB_fixed_Asm_8:
8037   case ARM::VST4qWB_fixed_Asm_16:
8038   case ARM::VST4qWB_fixed_Asm_32: {
8039     MCInst TmpInst;
8040     unsigned Spacing;
8041     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8042     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8043     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8044     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8045     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8046     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8047     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8048                                             Spacing));
8049     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8050                                             Spacing * 2));
8051     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8052                                             Spacing * 3));
8053     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8054     TmpInst.addOperand(Inst.getOperand(4));
8055     Inst = TmpInst;
8056     return true;
8057   }
8058 
8059   case ARM::VST4dWB_register_Asm_8:
8060   case ARM::VST4dWB_register_Asm_16:
8061   case ARM::VST4dWB_register_Asm_32:
8062   case ARM::VST4qWB_register_Asm_8:
8063   case ARM::VST4qWB_register_Asm_16:
8064   case ARM::VST4qWB_register_Asm_32: {
8065     MCInst TmpInst;
8066     unsigned Spacing;
8067     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8068     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8069     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8070     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8071     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8072     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8073     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8074                                             Spacing));
8075     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8076                                             Spacing * 2));
8077     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8078                                             Spacing * 3));
8079     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8080     TmpInst.addOperand(Inst.getOperand(5));
8081     Inst = TmpInst;
8082     return true;
8083   }
8084 
8085   // Handle encoding choice for the shift-immediate instructions.
8086   case ARM::t2LSLri:
8087   case ARM::t2LSRri:
8088   case ARM::t2ASRri:
8089     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8090         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8091         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8092         !HasWideQualifier) {
8093       unsigned NewOpc;
8094       switch (Inst.getOpcode()) {
8095       default: llvm_unreachable("unexpected opcode");
8096       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
8097       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
8098       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
8099       }
8100       // The Thumb1 operands aren't in the same order. Awesome, eh?
8101       MCInst TmpInst;
8102       TmpInst.setOpcode(NewOpc);
8103       TmpInst.addOperand(Inst.getOperand(0));
8104       TmpInst.addOperand(Inst.getOperand(5));
8105       TmpInst.addOperand(Inst.getOperand(1));
8106       TmpInst.addOperand(Inst.getOperand(2));
8107       TmpInst.addOperand(Inst.getOperand(3));
8108       TmpInst.addOperand(Inst.getOperand(4));
8109       Inst = TmpInst;
8110       return true;
8111     }
8112     return false;
8113 
8114   // Handle the Thumb2 mode MOV complex aliases.
8115   case ARM::t2MOVsr:
8116   case ARM::t2MOVSsr: {
8117     // Which instruction to expand to depends on the CCOut operand and
8118     // whether we're in an IT block if the register operands are low
8119     // registers.
8120     bool isNarrow = false;
8121     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8122         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8123         isARMLowRegister(Inst.getOperand(2).getReg()) &&
8124         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8125         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr) &&
8126         !HasWideQualifier)
8127       isNarrow = true;
8128     MCInst TmpInst;
8129     unsigned newOpc;
8130     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
8131     default: llvm_unreachable("unexpected opcode!");
8132     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
8133     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
8134     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
8135     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
8136     }
8137     TmpInst.setOpcode(newOpc);
8138     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8139     if (isNarrow)
8140       TmpInst.addOperand(MCOperand::createReg(
8141           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8142     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8143     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8144     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8145     TmpInst.addOperand(Inst.getOperand(5));
8146     if (!isNarrow)
8147       TmpInst.addOperand(MCOperand::createReg(
8148           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8149     Inst = TmpInst;
8150     return true;
8151   }
8152   case ARM::t2MOVsi:
8153   case ARM::t2MOVSsi: {
8154     // Which instruction to expand to depends on the CCOut operand and
8155     // whether we're in an IT block if the register operands are low
8156     // registers.
8157     bool isNarrow = false;
8158     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8159         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8160         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi) &&
8161         !HasWideQualifier)
8162       isNarrow = true;
8163     MCInst TmpInst;
8164     unsigned newOpc;
8165     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8166     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
8167     bool isMov = false;
8168     // MOV rd, rm, LSL #0 is actually a MOV instruction
8169     if (Shift == ARM_AM::lsl && Amount == 0) {
8170       isMov = true;
8171       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
8172       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
8173       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
8174       // instead.
8175       if (inITBlock()) {
8176         isNarrow = false;
8177       }
8178       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
8179     } else {
8180       switch(Shift) {
8181       default: llvm_unreachable("unexpected opcode!");
8182       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
8183       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
8184       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
8185       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
8186       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
8187       }
8188     }
8189     if (Amount == 32) Amount = 0;
8190     TmpInst.setOpcode(newOpc);
8191     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8192     if (isNarrow && !isMov)
8193       TmpInst.addOperand(MCOperand::createReg(
8194           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8195     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8196     if (newOpc != ARM::t2RRX && !isMov)
8197       TmpInst.addOperand(MCOperand::createImm(Amount));
8198     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8199     TmpInst.addOperand(Inst.getOperand(4));
8200     if (!isNarrow)
8201       TmpInst.addOperand(MCOperand::createReg(
8202           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8203     Inst = TmpInst;
8204     return true;
8205   }
8206   // Handle the ARM mode MOV complex aliases.
8207   case ARM::ASRr:
8208   case ARM::LSRr:
8209   case ARM::LSLr:
8210   case ARM::RORr: {
8211     ARM_AM::ShiftOpc ShiftTy;
8212     switch(Inst.getOpcode()) {
8213     default: llvm_unreachable("unexpected opcode!");
8214     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
8215     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
8216     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
8217     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
8218     }
8219     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
8220     MCInst TmpInst;
8221     TmpInst.setOpcode(ARM::MOVsr);
8222     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8223     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8224     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8225     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8226     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8227     TmpInst.addOperand(Inst.getOperand(4));
8228     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8229     Inst = TmpInst;
8230     return true;
8231   }
8232   case ARM::ASRi:
8233   case ARM::LSRi:
8234   case ARM::LSLi:
8235   case ARM::RORi: {
8236     ARM_AM::ShiftOpc ShiftTy;
8237     switch(Inst.getOpcode()) {
8238     default: llvm_unreachable("unexpected opcode!");
8239     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
8240     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
8241     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
8242     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
8243     }
8244     // A shift by zero is a plain MOVr, not a MOVsi.
8245     unsigned Amt = Inst.getOperand(2).getImm();
8246     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
8247     // A shift by 32 should be encoded as 0 when permitted
8248     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
8249       Amt = 0;
8250     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
8251     MCInst TmpInst;
8252     TmpInst.setOpcode(Opc);
8253     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8254     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8255     if (Opc == ARM::MOVsi)
8256       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8257     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8258     TmpInst.addOperand(Inst.getOperand(4));
8259     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8260     Inst = TmpInst;
8261     return true;
8262   }
8263   case ARM::RRXi: {
8264     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
8265     MCInst TmpInst;
8266     TmpInst.setOpcode(ARM::MOVsi);
8267     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8268     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8269     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8270     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8271     TmpInst.addOperand(Inst.getOperand(3));
8272     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
8273     Inst = TmpInst;
8274     return true;
8275   }
8276   case ARM::t2LDMIA_UPD: {
8277     // If this is a load of a single register, then we should use
8278     // a post-indexed LDR instruction instead, per the ARM ARM.
8279     if (Inst.getNumOperands() != 5)
8280       return false;
8281     MCInst TmpInst;
8282     TmpInst.setOpcode(ARM::t2LDR_POST);
8283     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8284     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8285     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8286     TmpInst.addOperand(MCOperand::createImm(4));
8287     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8288     TmpInst.addOperand(Inst.getOperand(3));
8289     Inst = TmpInst;
8290     return true;
8291   }
8292   case ARM::t2STMDB_UPD: {
8293     // If this is a store of a single register, then we should use
8294     // a pre-indexed STR instruction instead, per the ARM ARM.
8295     if (Inst.getNumOperands() != 5)
8296       return false;
8297     MCInst TmpInst;
8298     TmpInst.setOpcode(ARM::t2STR_PRE);
8299     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8300     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8301     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8302     TmpInst.addOperand(MCOperand::createImm(-4));
8303     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8304     TmpInst.addOperand(Inst.getOperand(3));
8305     Inst = TmpInst;
8306     return true;
8307   }
8308   case ARM::LDMIA_UPD:
8309     // If this is a load of a single register via a 'pop', then we should use
8310     // a post-indexed LDR instruction instead, per the ARM ARM.
8311     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
8312         Inst.getNumOperands() == 5) {
8313       MCInst TmpInst;
8314       TmpInst.setOpcode(ARM::LDR_POST_IMM);
8315       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8316       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8317       TmpInst.addOperand(Inst.getOperand(1)); // Rn
8318       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
8319       TmpInst.addOperand(MCOperand::createImm(4));
8320       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8321       TmpInst.addOperand(Inst.getOperand(3));
8322       Inst = TmpInst;
8323       return true;
8324     }
8325     break;
8326   case ARM::STMDB_UPD:
8327     // If this is a store of a single register via a 'push', then we should use
8328     // a pre-indexed STR instruction instead, per the ARM ARM.
8329     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8330         Inst.getNumOperands() == 5) {
8331       MCInst TmpInst;
8332       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8333       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8334       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8335       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8336       TmpInst.addOperand(MCOperand::createImm(-4));
8337       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8338       TmpInst.addOperand(Inst.getOperand(3));
8339       Inst = TmpInst;
8340     }
8341     break;
8342   case ARM::t2ADDri12:
8343     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8344     // mnemonic was used (not "addw"), encoding T3 is preferred.
8345     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8346         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8347       break;
8348     Inst.setOpcode(ARM::t2ADDri);
8349     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8350     break;
8351   case ARM::t2SUBri12:
8352     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8353     // mnemonic was used (not "subw"), encoding T3 is preferred.
8354     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8355         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8356       break;
8357     Inst.setOpcode(ARM::t2SUBri);
8358     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8359     break;
8360   case ARM::tADDi8:
8361     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8362     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8363     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8364     // to encoding T1 if <Rd> is omitted."
8365     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8366       Inst.setOpcode(ARM::tADDi3);
8367       return true;
8368     }
8369     break;
8370   case ARM::tSUBi8:
8371     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8372     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8373     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8374     // to encoding T1 if <Rd> is omitted."
8375     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8376       Inst.setOpcode(ARM::tSUBi3);
8377       return true;
8378     }
8379     break;
8380   case ARM::t2ADDri:
8381   case ARM::t2SUBri: {
8382     // If the destination and first source operand are the same, and
8383     // the flags are compatible with the current IT status, use encoding T2
8384     // instead of T3. For compatibility with the system 'as'. Make sure the
8385     // wide encoding wasn't explicit.
8386     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8387         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8388         (Inst.getOperand(2).isImm() &&
8389          (unsigned)Inst.getOperand(2).getImm() > 255) ||
8390         Inst.getOperand(5).getReg() != (inITBlock() ? 0 : ARM::CPSR) ||
8391         HasWideQualifier)
8392       break;
8393     MCInst TmpInst;
8394     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8395                       ARM::tADDi8 : ARM::tSUBi8);
8396     TmpInst.addOperand(Inst.getOperand(0));
8397     TmpInst.addOperand(Inst.getOperand(5));
8398     TmpInst.addOperand(Inst.getOperand(0));
8399     TmpInst.addOperand(Inst.getOperand(2));
8400     TmpInst.addOperand(Inst.getOperand(3));
8401     TmpInst.addOperand(Inst.getOperand(4));
8402     Inst = TmpInst;
8403     return true;
8404   }
8405   case ARM::t2ADDrr: {
8406     // If the destination and first source operand are the same, and
8407     // there's no setting of the flags, use encoding T2 instead of T3.
8408     // Note that this is only for ADD, not SUB. This mirrors the system
8409     // 'as' behaviour.  Also take advantage of ADD being commutative.
8410     // Make sure the wide encoding wasn't explicit.
8411     bool Swap = false;
8412     auto DestReg = Inst.getOperand(0).getReg();
8413     bool Transform = DestReg == Inst.getOperand(1).getReg();
8414     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
8415       Transform = true;
8416       Swap = true;
8417     }
8418     if (!Transform ||
8419         Inst.getOperand(5).getReg() != 0 ||
8420         HasWideQualifier)
8421       break;
8422     MCInst TmpInst;
8423     TmpInst.setOpcode(ARM::tADDhirr);
8424     TmpInst.addOperand(Inst.getOperand(0));
8425     TmpInst.addOperand(Inst.getOperand(0));
8426     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
8427     TmpInst.addOperand(Inst.getOperand(3));
8428     TmpInst.addOperand(Inst.getOperand(4));
8429     Inst = TmpInst;
8430     return true;
8431   }
8432   case ARM::tADDrSP:
8433     // If the non-SP source operand and the destination operand are not the
8434     // same, we need to use the 32-bit encoding if it's available.
8435     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8436       Inst.setOpcode(ARM::t2ADDrr);
8437       Inst.addOperand(MCOperand::createReg(0)); // cc_out
8438       return true;
8439     }
8440     break;
8441   case ARM::tB:
8442     // A Thumb conditional branch outside of an IT block is a tBcc.
8443     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8444       Inst.setOpcode(ARM::tBcc);
8445       return true;
8446     }
8447     break;
8448   case ARM::t2B:
8449     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8450     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8451       Inst.setOpcode(ARM::t2Bcc);
8452       return true;
8453     }
8454     break;
8455   case ARM::t2Bcc:
8456     // If the conditional is AL or we're in an IT block, we really want t2B.
8457     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8458       Inst.setOpcode(ARM::t2B);
8459       return true;
8460     }
8461     break;
8462   case ARM::tBcc:
8463     // If the conditional is AL, we really want tB.
8464     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8465       Inst.setOpcode(ARM::tB);
8466       return true;
8467     }
8468     break;
8469   case ARM::tLDMIA: {
8470     // If the register list contains any high registers, or if the writeback
8471     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8472     // instead if we're in Thumb2. Otherwise, this should have generated
8473     // an error in validateInstruction().
8474     unsigned Rn = Inst.getOperand(0).getReg();
8475     bool hasWritebackToken =
8476         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8477          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8478     bool listContainsBase;
8479     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8480         (!listContainsBase && !hasWritebackToken) ||
8481         (listContainsBase && hasWritebackToken)) {
8482       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8483       assert(isThumbTwo());
8484       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8485       // If we're switching to the updating version, we need to insert
8486       // the writeback tied operand.
8487       if (hasWritebackToken)
8488         Inst.insert(Inst.begin(),
8489                     MCOperand::createReg(Inst.getOperand(0).getReg()));
8490       return true;
8491     }
8492     break;
8493   }
8494   case ARM::tSTMIA_UPD: {
8495     // If the register list contains any high registers, we need to use
8496     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8497     // should have generated an error in validateInstruction().
8498     unsigned Rn = Inst.getOperand(0).getReg();
8499     bool listContainsBase;
8500     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8501       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8502       assert(isThumbTwo());
8503       Inst.setOpcode(ARM::t2STMIA_UPD);
8504       return true;
8505     }
8506     break;
8507   }
8508   case ARM::tPOP: {
8509     bool listContainsBase;
8510     // If the register list contains any high registers, we need to use
8511     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8512     // should have generated an error in validateInstruction().
8513     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8514       return false;
8515     assert(isThumbTwo());
8516     Inst.setOpcode(ARM::t2LDMIA_UPD);
8517     // Add the base register and writeback operands.
8518     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8519     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8520     return true;
8521   }
8522   case ARM::tPUSH: {
8523     bool listContainsBase;
8524     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8525       return false;
8526     assert(isThumbTwo());
8527     Inst.setOpcode(ARM::t2STMDB_UPD);
8528     // Add the base register and writeback operands.
8529     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8530     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8531     return true;
8532   }
8533   case ARM::t2MOVi:
8534     // If we can use the 16-bit encoding and the user didn't explicitly
8535     // request the 32-bit variant, transform it here.
8536     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8537         (Inst.getOperand(1).isImm() &&
8538          (unsigned)Inst.getOperand(1).getImm() <= 255) &&
8539         Inst.getOperand(4).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8540         !HasWideQualifier) {
8541       // The operands aren't in the same order for tMOVi8...
8542       MCInst TmpInst;
8543       TmpInst.setOpcode(ARM::tMOVi8);
8544       TmpInst.addOperand(Inst.getOperand(0));
8545       TmpInst.addOperand(Inst.getOperand(4));
8546       TmpInst.addOperand(Inst.getOperand(1));
8547       TmpInst.addOperand(Inst.getOperand(2));
8548       TmpInst.addOperand(Inst.getOperand(3));
8549       Inst = TmpInst;
8550       return true;
8551     }
8552     break;
8553 
8554   case ARM::t2MOVr:
8555     // If we can use the 16-bit encoding and the user didn't explicitly
8556     // request the 32-bit variant, transform it here.
8557     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8558         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8559         Inst.getOperand(2).getImm() == ARMCC::AL &&
8560         Inst.getOperand(4).getReg() == ARM::CPSR &&
8561         !HasWideQualifier) {
8562       // The operands aren't the same for tMOV[S]r... (no cc_out)
8563       MCInst TmpInst;
8564       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8565       TmpInst.addOperand(Inst.getOperand(0));
8566       TmpInst.addOperand(Inst.getOperand(1));
8567       TmpInst.addOperand(Inst.getOperand(2));
8568       TmpInst.addOperand(Inst.getOperand(3));
8569       Inst = TmpInst;
8570       return true;
8571     }
8572     break;
8573 
8574   case ARM::t2SXTH:
8575   case ARM::t2SXTB:
8576   case ARM::t2UXTH:
8577   case ARM::t2UXTB:
8578     // If we can use the 16-bit encoding and the user didn't explicitly
8579     // request the 32-bit variant, transform it here.
8580     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8581         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8582         Inst.getOperand(2).getImm() == 0 &&
8583         !HasWideQualifier) {
8584       unsigned NewOpc;
8585       switch (Inst.getOpcode()) {
8586       default: llvm_unreachable("Illegal opcode!");
8587       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8588       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8589       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8590       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8591       }
8592       // The operands aren't the same for thumb1 (no rotate operand).
8593       MCInst TmpInst;
8594       TmpInst.setOpcode(NewOpc);
8595       TmpInst.addOperand(Inst.getOperand(0));
8596       TmpInst.addOperand(Inst.getOperand(1));
8597       TmpInst.addOperand(Inst.getOperand(3));
8598       TmpInst.addOperand(Inst.getOperand(4));
8599       Inst = TmpInst;
8600       return true;
8601     }
8602     break;
8603 
8604   case ARM::MOVsi: {
8605     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8606     // rrx shifts and asr/lsr of #32 is encoded as 0
8607     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
8608       return false;
8609     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8610       // Shifting by zero is accepted as a vanilla 'MOVr'
8611       MCInst TmpInst;
8612       TmpInst.setOpcode(ARM::MOVr);
8613       TmpInst.addOperand(Inst.getOperand(0));
8614       TmpInst.addOperand(Inst.getOperand(1));
8615       TmpInst.addOperand(Inst.getOperand(3));
8616       TmpInst.addOperand(Inst.getOperand(4));
8617       TmpInst.addOperand(Inst.getOperand(5));
8618       Inst = TmpInst;
8619       return true;
8620     }
8621     return false;
8622   }
8623   case ARM::ANDrsi:
8624   case ARM::ORRrsi:
8625   case ARM::EORrsi:
8626   case ARM::BICrsi:
8627   case ARM::SUBrsi:
8628   case ARM::ADDrsi: {
8629     unsigned newOpc;
8630     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8631     if (SOpc == ARM_AM::rrx) return false;
8632     switch (Inst.getOpcode()) {
8633     default: llvm_unreachable("unexpected opcode!");
8634     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8635     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8636     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8637     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8638     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8639     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8640     }
8641     // If the shift is by zero, use the non-shifted instruction definition.
8642     // The exception is for right shifts, where 0 == 32
8643     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8644         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8645       MCInst TmpInst;
8646       TmpInst.setOpcode(newOpc);
8647       TmpInst.addOperand(Inst.getOperand(0));
8648       TmpInst.addOperand(Inst.getOperand(1));
8649       TmpInst.addOperand(Inst.getOperand(2));
8650       TmpInst.addOperand(Inst.getOperand(4));
8651       TmpInst.addOperand(Inst.getOperand(5));
8652       TmpInst.addOperand(Inst.getOperand(6));
8653       Inst = TmpInst;
8654       return true;
8655     }
8656     return false;
8657   }
8658   case ARM::ITasm:
8659   case ARM::t2IT: {
8660     MCOperand &MO = Inst.getOperand(1);
8661     unsigned Mask = MO.getImm();
8662     ARMCC::CondCodes Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8663 
8664     // Set up the IT block state according to the IT instruction we just
8665     // matched.
8666     assert(!inITBlock() && "nested IT blocks?!");
8667     startExplicitITBlock(Cond, Mask);
8668     MO.setImm(getITMaskEncoding());
8669     break;
8670   }
8671   case ARM::t2LSLrr:
8672   case ARM::t2LSRrr:
8673   case ARM::t2ASRrr:
8674   case ARM::t2SBCrr:
8675   case ARM::t2RORrr:
8676   case ARM::t2BICrr:
8677     // Assemblers should use the narrow encodings of these instructions when permissible.
8678     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8679          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8680         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8681         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8682         !HasWideQualifier) {
8683       unsigned NewOpc;
8684       switch (Inst.getOpcode()) {
8685         default: llvm_unreachable("unexpected opcode");
8686         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
8687         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
8688         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
8689         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
8690         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
8691         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
8692       }
8693       MCInst TmpInst;
8694       TmpInst.setOpcode(NewOpc);
8695       TmpInst.addOperand(Inst.getOperand(0));
8696       TmpInst.addOperand(Inst.getOperand(5));
8697       TmpInst.addOperand(Inst.getOperand(1));
8698       TmpInst.addOperand(Inst.getOperand(2));
8699       TmpInst.addOperand(Inst.getOperand(3));
8700       TmpInst.addOperand(Inst.getOperand(4));
8701       Inst = TmpInst;
8702       return true;
8703     }
8704     return false;
8705 
8706   case ARM::t2ANDrr:
8707   case ARM::t2EORrr:
8708   case ARM::t2ADCrr:
8709   case ARM::t2ORRrr:
8710     // Assemblers should use the narrow encodings of these instructions when permissible.
8711     // These instructions are special in that they are commutable, so shorter encodings
8712     // are available more often.
8713     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8714          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8715         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
8716          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
8717         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8718         !HasWideQualifier) {
8719       unsigned NewOpc;
8720       switch (Inst.getOpcode()) {
8721         default: llvm_unreachable("unexpected opcode");
8722         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
8723         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
8724         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
8725         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
8726       }
8727       MCInst TmpInst;
8728       TmpInst.setOpcode(NewOpc);
8729       TmpInst.addOperand(Inst.getOperand(0));
8730       TmpInst.addOperand(Inst.getOperand(5));
8731       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
8732         TmpInst.addOperand(Inst.getOperand(1));
8733         TmpInst.addOperand(Inst.getOperand(2));
8734       } else {
8735         TmpInst.addOperand(Inst.getOperand(2));
8736         TmpInst.addOperand(Inst.getOperand(1));
8737       }
8738       TmpInst.addOperand(Inst.getOperand(3));
8739       TmpInst.addOperand(Inst.getOperand(4));
8740       Inst = TmpInst;
8741       return true;
8742     }
8743     return false;
8744   }
8745   return false;
8746 }
8747 
8748 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
8749   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
8750   // suffix depending on whether they're in an IT block or not.
8751   unsigned Opc = Inst.getOpcode();
8752   const MCInstrDesc &MCID = MII.get(Opc);
8753   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
8754     assert(MCID.hasOptionalDef() &&
8755            "optionally flag setting instruction missing optional def operand");
8756     assert(MCID.NumOperands == Inst.getNumOperands() &&
8757            "operand count mismatch!");
8758     // Find the optional-def operand (cc_out).
8759     unsigned OpNo;
8760     for (OpNo = 0;
8761          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
8762          ++OpNo)
8763       ;
8764     // If we're parsing Thumb1, reject it completely.
8765     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
8766       return Match_RequiresFlagSetting;
8767     // If we're parsing Thumb2, which form is legal depends on whether we're
8768     // in an IT block.
8769     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
8770         !inITBlock())
8771       return Match_RequiresITBlock;
8772     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
8773         inITBlock())
8774       return Match_RequiresNotITBlock;
8775     // LSL with zero immediate is not allowed in an IT block
8776     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
8777       return Match_RequiresNotITBlock;
8778   } else if (isThumbOne()) {
8779     // Some high-register supporting Thumb1 encodings only allow both registers
8780     // to be from r0-r7 when in Thumb2.
8781     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
8782         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8783         isARMLowRegister(Inst.getOperand(2).getReg()))
8784       return Match_RequiresThumb2;
8785     // Others only require ARMv6 or later.
8786     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
8787              isARMLowRegister(Inst.getOperand(0).getReg()) &&
8788              isARMLowRegister(Inst.getOperand(1).getReg()))
8789       return Match_RequiresV6;
8790   }
8791 
8792   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
8793   // than the loop below can handle, so it uses the GPRnopc register class and
8794   // we do SP handling here.
8795   if (Opc == ARM::t2MOVr && !hasV8Ops())
8796   {
8797     // SP as both source and destination is not allowed
8798     if (Inst.getOperand(0).getReg() == ARM::SP &&
8799         Inst.getOperand(1).getReg() == ARM::SP)
8800       return Match_RequiresV8;
8801     // When flags-setting SP as either source or destination is not allowed
8802     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
8803         (Inst.getOperand(0).getReg() == ARM::SP ||
8804          Inst.getOperand(1).getReg() == ARM::SP))
8805       return Match_RequiresV8;
8806   }
8807 
8808   // Use of SP for VMRS/VMSR is only allowed in ARM mode with the exception of
8809   // ARMv8-A.
8810   if ((Inst.getOpcode() == ARM::VMRS || Inst.getOpcode() == ARM::VMSR) &&
8811       Inst.getOperand(0).getReg() == ARM::SP && (isThumb() && !hasV8Ops()))
8812     return Match_InvalidOperand;
8813 
8814   for (unsigned I = 0; I < MCID.NumOperands; ++I)
8815     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
8816       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
8817       if ((Inst.getOperand(I).getReg() == ARM::SP) && !hasV8Ops())
8818         return Match_RequiresV8;
8819       else if (Inst.getOperand(I).getReg() == ARM::PC)
8820         return Match_InvalidOperand;
8821     }
8822 
8823   return Match_Success;
8824 }
8825 
8826 namespace llvm {
8827 
8828 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
8829   return true; // In an assembly source, no need to second-guess
8830 }
8831 
8832 } // end namespace llvm
8833 
8834 // Returns true if Inst is unpredictable if it is in and IT block, but is not
8835 // the last instruction in the block.
8836 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
8837   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8838 
8839   // All branch & call instructions terminate IT blocks with the exception of
8840   // SVC.
8841   if (MCID.isTerminator() || (MCID.isCall() && Inst.getOpcode() != ARM::tSVC) ||
8842       MCID.isReturn() || MCID.isBranch() || MCID.isIndirectBranch())
8843     return true;
8844 
8845   // Any arithmetic instruction which writes to the PC also terminates the IT
8846   // block.
8847   for (unsigned OpIdx = 0; OpIdx < MCID.getNumDefs(); ++OpIdx) {
8848     MCOperand &Op = Inst.getOperand(OpIdx);
8849     if (Op.isReg() && Op.getReg() == ARM::PC)
8850       return true;
8851   }
8852 
8853   if (MCID.hasImplicitDefOfPhysReg(ARM::PC, MRI))
8854     return true;
8855 
8856   // Instructions with variable operand lists, which write to the variable
8857   // operands. We only care about Thumb instructions here, as ARM instructions
8858   // obviously can't be in an IT block.
8859   switch (Inst.getOpcode()) {
8860   case ARM::tLDMIA:
8861   case ARM::t2LDMIA:
8862   case ARM::t2LDMIA_UPD:
8863   case ARM::t2LDMDB:
8864   case ARM::t2LDMDB_UPD:
8865     if (listContainsReg(Inst, 3, ARM::PC))
8866       return true;
8867     break;
8868   case ARM::tPOP:
8869     if (listContainsReg(Inst, 2, ARM::PC))
8870       return true;
8871     break;
8872   }
8873 
8874   return false;
8875 }
8876 
8877 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
8878                                           uint64_t &ErrorInfo,
8879                                           bool MatchingInlineAsm,
8880                                           bool &EmitInITBlock,
8881                                           MCStreamer &Out) {
8882   // If we can't use an implicit IT block here, just match as normal.
8883   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
8884     return MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
8885 
8886   // Try to match the instruction in an extension of the current IT block (if
8887   // there is one).
8888   if (inImplicitITBlock()) {
8889     extendImplicitITBlock(ITState.Cond);
8890     if (MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm) ==
8891             Match_Success) {
8892       // The match succeded, but we still have to check that the instruction is
8893       // valid in this implicit IT block.
8894       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8895       if (MCID.isPredicable()) {
8896         ARMCC::CondCodes InstCond =
8897             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8898                 .getImm();
8899         ARMCC::CondCodes ITCond = currentITCond();
8900         if (InstCond == ITCond) {
8901           EmitInITBlock = true;
8902           return Match_Success;
8903         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
8904           invertCurrentITCondition();
8905           EmitInITBlock = true;
8906           return Match_Success;
8907         }
8908       }
8909     }
8910     rewindImplicitITPosition();
8911   }
8912 
8913   // Finish the current IT block, and try to match outside any IT block.
8914   flushPendingInstructions(Out);
8915   unsigned PlainMatchResult =
8916       MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm);
8917   if (PlainMatchResult == Match_Success) {
8918     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8919     if (MCID.isPredicable()) {
8920       ARMCC::CondCodes InstCond =
8921           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8922               .getImm();
8923       // Some forms of the branch instruction have their own condition code
8924       // fields, so can be conditionally executed without an IT block.
8925       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
8926         EmitInITBlock = false;
8927         return Match_Success;
8928       }
8929       if (InstCond == ARMCC::AL) {
8930         EmitInITBlock = false;
8931         return Match_Success;
8932       }
8933     } else {
8934       EmitInITBlock = false;
8935       return Match_Success;
8936     }
8937   }
8938 
8939   // Try to match in a new IT block. The matcher doesn't check the actual
8940   // condition, so we create an IT block with a dummy condition, and fix it up
8941   // once we know the actual condition.
8942   startImplicitITBlock();
8943   if (MatchInstructionImpl(Operands, Inst, ErrorInfo, MatchingInlineAsm) ==
8944       Match_Success) {
8945     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8946     if (MCID.isPredicable()) {
8947       ITState.Cond =
8948           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8949               .getImm();
8950       EmitInITBlock = true;
8951       return Match_Success;
8952     }
8953   }
8954   discardImplicitITBlock();
8955 
8956   // If none of these succeed, return the error we got when trying to match
8957   // outside any IT blocks.
8958   EmitInITBlock = false;
8959   return PlainMatchResult;
8960 }
8961 
8962 std::string ARMMnemonicSpellCheck(StringRef S, uint64_t FBS);
8963 
8964 static const char *getSubtargetFeatureName(uint64_t Val);
8965 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
8966                                            OperandVector &Operands,
8967                                            MCStreamer &Out, uint64_t &ErrorInfo,
8968                                            bool MatchingInlineAsm) {
8969   MCInst Inst;
8970   unsigned MatchResult;
8971   bool PendConditionalInstruction = false;
8972 
8973   MatchResult = MatchInstruction(Operands, Inst, ErrorInfo, MatchingInlineAsm,
8974                                  PendConditionalInstruction, Out);
8975 
8976   SMLoc ErrorLoc;
8977   if (ErrorInfo < Operands.size()) {
8978     ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8979     if (ErrorLoc == SMLoc())
8980       ErrorLoc = IDLoc;
8981   }
8982 
8983   switch (MatchResult) {
8984   case Match_Success:
8985     // Context sensitive operand constraints aren't handled by the matcher,
8986     // so check them here.
8987     if (validateInstruction(Inst, Operands)) {
8988       // Still progress the IT block, otherwise one wrong condition causes
8989       // nasty cascading errors.
8990       forwardITPosition();
8991       return true;
8992     }
8993 
8994     { // processInstruction() updates inITBlock state, we need to save it away
8995       bool wasInITBlock = inITBlock();
8996 
8997       // Some instructions need post-processing to, for example, tweak which
8998       // encoding is selected. Loop on it while changes happen so the
8999       // individual transformations can chain off each other. E.g.,
9000       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
9001       while (processInstruction(Inst, Operands, Out))
9002         ;
9003 
9004       // Only after the instruction is fully processed, we can validate it
9005       if (wasInITBlock && hasV8Ops() && isThumb() &&
9006           !isV8EligibleForIT(&Inst)) {
9007         Warning(IDLoc, "deprecated instruction in IT block");
9008       }
9009     }
9010 
9011     // Only move forward at the very end so that everything in validate
9012     // and process gets a consistent answer about whether we're in an IT
9013     // block.
9014     forwardITPosition();
9015 
9016     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
9017     // doesn't actually encode.
9018     if (Inst.getOpcode() == ARM::ITasm)
9019       return false;
9020 
9021     Inst.setLoc(IDLoc);
9022     if (PendConditionalInstruction) {
9023       PendingConditionalInsts.push_back(Inst);
9024       if (isITBlockFull() || isITBlockTerminator(Inst))
9025         flushPendingInstructions(Out);
9026     } else {
9027       Out.EmitInstruction(Inst, getSTI());
9028     }
9029     return false;
9030   case Match_MissingFeature: {
9031     assert(ErrorInfo && "Unknown missing feature!");
9032     // Special case the error message for the very common case where only
9033     // a single subtarget feature is missing (Thumb vs. ARM, e.g.).
9034     std::string Msg = "instruction requires:";
9035     uint64_t Mask = 1;
9036     for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
9037       if (ErrorInfo & Mask) {
9038         Msg += " ";
9039         Msg += getSubtargetFeatureName(ErrorInfo & Mask);
9040       }
9041       Mask <<= 1;
9042     }
9043     return Error(IDLoc, Msg);
9044   }
9045   case Match_InvalidOperand: {
9046     SMLoc ErrorLoc = IDLoc;
9047     if (ErrorInfo != ~0ULL) {
9048       if (ErrorInfo >= Operands.size())
9049         return Error(IDLoc, "too few operands for instruction");
9050 
9051       ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
9052       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
9053     }
9054 
9055     return Error(ErrorLoc, "invalid operand for instruction");
9056   }
9057   case Match_MnemonicFail: {
9058     uint64_t FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
9059     std::string Suggestion = ARMMnemonicSpellCheck(
9060       ((ARMOperand &)*Operands[0]).getToken(), FBS);
9061     return Error(IDLoc, "invalid instruction" + Suggestion,
9062                  ((ARMOperand &)*Operands[0]).getLocRange());
9063   }
9064   case Match_RequiresNotITBlock:
9065     return Error(IDLoc, "flag setting instruction only valid outside IT block");
9066   case Match_RequiresITBlock:
9067     return Error(IDLoc, "instruction only valid inside IT block");
9068   case Match_RequiresV6:
9069     return Error(IDLoc, "instruction variant requires ARMv6 or later");
9070   case Match_RequiresThumb2:
9071     return Error(IDLoc, "instruction variant requires Thumb2");
9072   case Match_RequiresV8:
9073     return Error(IDLoc, "instruction variant requires ARMv8 or later");
9074   case Match_RequiresFlagSetting:
9075     return Error(IDLoc, "no flag-preserving variant of this instruction available");
9076   case Match_ImmRange0_1:
9077     return Error(ErrorLoc, "immediate operand must be in the range [0,1]");
9078   case Match_ImmRange0_3:
9079     return Error(ErrorLoc, "immediate operand must be in the range [0,3]");
9080   case Match_ImmRange0_7:
9081     return Error(ErrorLoc, "immediate operand must be in the range [0,7]");
9082   case Match_ImmRange0_15:
9083     return Error(ErrorLoc, "immediate operand must be in the range [0,15]");
9084   case Match_ImmRange0_31:
9085     return Error(ErrorLoc, "immediate operand must be in the range [0,31]");
9086   case Match_ImmRange0_32:
9087     return Error(ErrorLoc, "immediate operand must be in the range [0,32]");
9088   case Match_ImmRange0_63:
9089     return Error(ErrorLoc, "immediate operand must be in the range [0,63]");
9090   case Match_ImmRange0_239:
9091     return Error(ErrorLoc, "immediate operand must be in the range [0,239]");
9092   case Match_ImmRange0_255:
9093     return Error(ErrorLoc, "immediate operand must be in the range [0,255]");
9094   case Match_ImmRange0_4095:
9095     return Error(ErrorLoc, "immediate operand must be in the range [0,4095]");
9096   case Match_ImmRange0_65535:
9097     return Error(ErrorLoc, "immediate operand must be in the range [0,65535]");
9098   case Match_ImmRange1_7:
9099     return Error(ErrorLoc, "immediate operand must be in the range [1,7]");
9100   case Match_ImmRange1_8:
9101     return Error(ErrorLoc, "immediate operand must be in the range [1,8]");
9102   case Match_ImmRange1_15:
9103     return Error(ErrorLoc, "immediate operand must be in the range [1,15]");
9104   case Match_ImmRange1_16:
9105     return Error(ErrorLoc, "immediate operand must be in the range [1,16]");
9106   case Match_ImmRange1_31:
9107     return Error(ErrorLoc, "immediate operand must be in the range [1,31]");
9108   case Match_ImmRange1_32:
9109     return Error(ErrorLoc, "immediate operand must be in the range [1,32]");
9110   case Match_ImmRange1_64:
9111     return Error(ErrorLoc, "immediate operand must be in the range [1,64]");
9112   case Match_ImmRange8_8:
9113     return Error(ErrorLoc, "immediate operand must be 8.");
9114   case Match_ImmRange16_16:
9115     return Error(ErrorLoc, "immediate operand must be 16.");
9116   case Match_ImmRange32_32:
9117     return Error(ErrorLoc, "immediate operand must be 32.");
9118   case Match_ImmRange256_65535:
9119     return Error(ErrorLoc, "immediate operand must be in the range [255,65535]");
9120   case Match_ImmRange0_16777215:
9121     return Error(ErrorLoc, "immediate operand must be in the range [0,0xffffff]");
9122   case Match_AlignedMemoryRequiresNone:
9123   case Match_DupAlignedMemoryRequiresNone:
9124   case Match_AlignedMemoryRequires16:
9125   case Match_DupAlignedMemoryRequires16:
9126   case Match_AlignedMemoryRequires32:
9127   case Match_DupAlignedMemoryRequires32:
9128   case Match_AlignedMemoryRequires64:
9129   case Match_DupAlignedMemoryRequires64:
9130   case Match_AlignedMemoryRequires64or128:
9131   case Match_DupAlignedMemoryRequires64or128:
9132   case Match_AlignedMemoryRequires64or128or256:
9133   {
9134     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getAlignmentLoc();
9135     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
9136     switch (MatchResult) {
9137       default:
9138         llvm_unreachable("Missing Match_Aligned type");
9139       case Match_AlignedMemoryRequiresNone:
9140       case Match_DupAlignedMemoryRequiresNone:
9141         return Error(ErrorLoc, "alignment must be omitted");
9142       case Match_AlignedMemoryRequires16:
9143       case Match_DupAlignedMemoryRequires16:
9144         return Error(ErrorLoc, "alignment must be 16 or omitted");
9145       case Match_AlignedMemoryRequires32:
9146       case Match_DupAlignedMemoryRequires32:
9147         return Error(ErrorLoc, "alignment must be 32 or omitted");
9148       case Match_AlignedMemoryRequires64:
9149       case Match_DupAlignedMemoryRequires64:
9150         return Error(ErrorLoc, "alignment must be 64 or omitted");
9151       case Match_AlignedMemoryRequires64or128:
9152       case Match_DupAlignedMemoryRequires64or128:
9153         return Error(ErrorLoc, "alignment must be 64, 128 or omitted");
9154       case Match_AlignedMemoryRequires64or128or256:
9155         return Error(ErrorLoc, "alignment must be 64, 128, 256 or omitted");
9156     }
9157   }
9158   }
9159 
9160   llvm_unreachable("Implement any new match types added!");
9161 }
9162 
9163 /// parseDirective parses the arm specific directives
9164 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
9165   const MCObjectFileInfo::Environment Format =
9166     getContext().getObjectFileInfo()->getObjectFileType();
9167   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9168   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
9169 
9170   StringRef IDVal = DirectiveID.getIdentifier();
9171   if (IDVal == ".word")
9172     parseLiteralValues(4, DirectiveID.getLoc());
9173   else if (IDVal == ".short" || IDVal == ".hword")
9174     parseLiteralValues(2, DirectiveID.getLoc());
9175   else if (IDVal == ".thumb")
9176     parseDirectiveThumb(DirectiveID.getLoc());
9177   else if (IDVal == ".arm")
9178     parseDirectiveARM(DirectiveID.getLoc());
9179   else if (IDVal == ".thumb_func")
9180     parseDirectiveThumbFunc(DirectiveID.getLoc());
9181   else if (IDVal == ".code")
9182     parseDirectiveCode(DirectiveID.getLoc());
9183   else if (IDVal == ".syntax")
9184     parseDirectiveSyntax(DirectiveID.getLoc());
9185   else if (IDVal == ".unreq")
9186     parseDirectiveUnreq(DirectiveID.getLoc());
9187   else if (IDVal == ".fnend")
9188     parseDirectiveFnEnd(DirectiveID.getLoc());
9189   else if (IDVal == ".cantunwind")
9190     parseDirectiveCantUnwind(DirectiveID.getLoc());
9191   else if (IDVal == ".personality")
9192     parseDirectivePersonality(DirectiveID.getLoc());
9193   else if (IDVal == ".handlerdata")
9194     parseDirectiveHandlerData(DirectiveID.getLoc());
9195   else if (IDVal == ".setfp")
9196     parseDirectiveSetFP(DirectiveID.getLoc());
9197   else if (IDVal == ".pad")
9198     parseDirectivePad(DirectiveID.getLoc());
9199   else if (IDVal == ".save")
9200     parseDirectiveRegSave(DirectiveID.getLoc(), false);
9201   else if (IDVal == ".vsave")
9202     parseDirectiveRegSave(DirectiveID.getLoc(), true);
9203   else if (IDVal == ".ltorg" || IDVal == ".pool")
9204     parseDirectiveLtorg(DirectiveID.getLoc());
9205   else if (IDVal == ".even")
9206     parseDirectiveEven(DirectiveID.getLoc());
9207   else if (IDVal == ".personalityindex")
9208     parseDirectivePersonalityIndex(DirectiveID.getLoc());
9209   else if (IDVal == ".unwind_raw")
9210     parseDirectiveUnwindRaw(DirectiveID.getLoc());
9211   else if (IDVal == ".movsp")
9212     parseDirectiveMovSP(DirectiveID.getLoc());
9213   else if (IDVal == ".arch_extension")
9214     parseDirectiveArchExtension(DirectiveID.getLoc());
9215   else if (IDVal == ".align")
9216     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
9217   else if (IDVal == ".thumb_set")
9218     parseDirectiveThumbSet(DirectiveID.getLoc());
9219   else if (!IsMachO && !IsCOFF) {
9220     if (IDVal == ".arch")
9221       parseDirectiveArch(DirectiveID.getLoc());
9222     else if (IDVal == ".cpu")
9223       parseDirectiveCPU(DirectiveID.getLoc());
9224     else if (IDVal == ".eabi_attribute")
9225       parseDirectiveEabiAttr(DirectiveID.getLoc());
9226     else if (IDVal == ".fpu")
9227       parseDirectiveFPU(DirectiveID.getLoc());
9228     else if (IDVal == ".fnstart")
9229       parseDirectiveFnStart(DirectiveID.getLoc());
9230     else if (IDVal == ".inst")
9231       parseDirectiveInst(DirectiveID.getLoc());
9232     else if (IDVal == ".inst.n")
9233       parseDirectiveInst(DirectiveID.getLoc(), 'n');
9234     else if (IDVal == ".inst.w")
9235       parseDirectiveInst(DirectiveID.getLoc(), 'w');
9236     else if (IDVal == ".object_arch")
9237       parseDirectiveObjectArch(DirectiveID.getLoc());
9238     else if (IDVal == ".tlsdescseq")
9239       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
9240     else
9241       return true;
9242   } else
9243     return true;
9244   return false;
9245 }
9246 
9247 /// parseLiteralValues
9248 ///  ::= .hword expression [, expression]*
9249 ///  ::= .short expression [, expression]*
9250 ///  ::= .word expression [, expression]*
9251 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
9252   auto parseOne = [&]() -> bool {
9253     const MCExpr *Value;
9254     if (getParser().parseExpression(Value))
9255       return true;
9256     getParser().getStreamer().EmitValue(Value, Size, L);
9257     return false;
9258   };
9259   return (parseMany(parseOne));
9260 }
9261 
9262 /// parseDirectiveThumb
9263 ///  ::= .thumb
9264 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
9265   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9266       check(!hasThumb(), L, "target does not support Thumb mode"))
9267     return true;
9268 
9269   if (!isThumb())
9270     SwitchMode();
9271 
9272   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9273   return false;
9274 }
9275 
9276 /// parseDirectiveARM
9277 ///  ::= .arm
9278 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
9279   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9280       check(!hasARM(), L, "target does not support ARM mode"))
9281     return true;
9282 
9283   if (isThumb())
9284     SwitchMode();
9285   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9286   return false;
9287 }
9288 
9289 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
9290   // We need to flush the current implicit IT block on a label, because it is
9291   // not legal to branch into an IT block.
9292   flushPendingInstructions(getStreamer());
9293   if (NextSymbolIsThumb) {
9294     getParser().getStreamer().EmitThumbFunc(Symbol);
9295     NextSymbolIsThumb = false;
9296   }
9297 }
9298 
9299 /// parseDirectiveThumbFunc
9300 ///  ::= .thumbfunc symbol_name
9301 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
9302   MCAsmParser &Parser = getParser();
9303   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
9304   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9305 
9306   // Darwin asm has (optionally) function name after .thumb_func direction
9307   // ELF doesn't
9308 
9309   if (IsMachO) {
9310     if (Parser.getTok().is(AsmToken::Identifier) ||
9311         Parser.getTok().is(AsmToken::String)) {
9312       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
9313           Parser.getTok().getIdentifier());
9314       getParser().getStreamer().EmitThumbFunc(Func);
9315       Parser.Lex();
9316       if (parseToken(AsmToken::EndOfStatement,
9317                      "unexpected token in '.thumb_func' directive"))
9318         return true;
9319       return false;
9320     }
9321   }
9322 
9323   if (parseToken(AsmToken::EndOfStatement,
9324                  "unexpected token in '.thumb_func' directive"))
9325     return true;
9326 
9327   NextSymbolIsThumb = true;
9328   return false;
9329 }
9330 
9331 /// parseDirectiveSyntax
9332 ///  ::= .syntax unified | divided
9333 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
9334   MCAsmParser &Parser = getParser();
9335   const AsmToken &Tok = Parser.getTok();
9336   if (Tok.isNot(AsmToken::Identifier)) {
9337     Error(L, "unexpected token in .syntax directive");
9338     return false;
9339   }
9340 
9341   StringRef Mode = Tok.getString();
9342   Parser.Lex();
9343   if (check(Mode == "divided" || Mode == "DIVIDED", L,
9344             "'.syntax divided' arm assembly not supported") ||
9345       check(Mode != "unified" && Mode != "UNIFIED", L,
9346             "unrecognized syntax mode in .syntax directive") ||
9347       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9348     return true;
9349 
9350   // TODO tell the MC streamer the mode
9351   // getParser().getStreamer().Emit???();
9352   return false;
9353 }
9354 
9355 /// parseDirectiveCode
9356 ///  ::= .code 16 | 32
9357 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
9358   MCAsmParser &Parser = getParser();
9359   const AsmToken &Tok = Parser.getTok();
9360   if (Tok.isNot(AsmToken::Integer))
9361     return Error(L, "unexpected token in .code directive");
9362   int64_t Val = Parser.getTok().getIntVal();
9363   if (Val != 16 && Val != 32) {
9364     Error(L, "invalid operand to .code directive");
9365     return false;
9366   }
9367   Parser.Lex();
9368 
9369   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9370     return true;
9371 
9372   if (Val == 16) {
9373     if (!hasThumb())
9374       return Error(L, "target does not support Thumb mode");
9375 
9376     if (!isThumb())
9377       SwitchMode();
9378     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9379   } else {
9380     if (!hasARM())
9381       return Error(L, "target does not support ARM mode");
9382 
9383     if (isThumb())
9384       SwitchMode();
9385     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9386   }
9387 
9388   return false;
9389 }
9390 
9391 /// parseDirectiveReq
9392 ///  ::= name .req registername
9393 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
9394   MCAsmParser &Parser = getParser();
9395   Parser.Lex(); // Eat the '.req' token.
9396   unsigned Reg;
9397   SMLoc SRegLoc, ERegLoc;
9398   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
9399             "register name expected") ||
9400       parseToken(AsmToken::EndOfStatement,
9401                  "unexpected input in .req directive."))
9402     return true;
9403 
9404   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
9405     return Error(SRegLoc,
9406                  "redefinition of '" + Name + "' does not match original.");
9407 
9408   return false;
9409 }
9410 
9411 /// parseDirectiveUneq
9412 ///  ::= .unreq registername
9413 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
9414   MCAsmParser &Parser = getParser();
9415   if (Parser.getTok().isNot(AsmToken::Identifier))
9416     return Error(L, "unexpected input in .unreq directive.");
9417   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
9418   Parser.Lex(); // Eat the identifier.
9419   if (parseToken(AsmToken::EndOfStatement,
9420                  "unexpected input in '.unreq' directive"))
9421     return true;
9422   return false;
9423 }
9424 
9425 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
9426 // before, if supported by the new target, or emit mapping symbols for the mode
9427 // switch.
9428 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
9429   if (WasThumb != isThumb()) {
9430     if (WasThumb && hasThumb()) {
9431       // Stay in Thumb mode
9432       SwitchMode();
9433     } else if (!WasThumb && hasARM()) {
9434       // Stay in ARM mode
9435       SwitchMode();
9436     } else {
9437       // Mode switch forced, because the new arch doesn't support the old mode.
9438       getParser().getStreamer().EmitAssemblerFlag(isThumb() ? MCAF_Code16
9439                                                             : MCAF_Code32);
9440       // Warn about the implcit mode switch. GAS does not switch modes here,
9441       // but instead stays in the old mode, reporting an error on any following
9442       // instructions as the mode does not exist on the target.
9443       Warning(Loc, Twine("new target does not support ") +
9444                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
9445                        (!WasThumb ? "thumb" : "arm") + " mode");
9446     }
9447   }
9448 }
9449 
9450 /// parseDirectiveArch
9451 ///  ::= .arch token
9452 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
9453   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
9454   ARM::ArchKind ID = ARM::parseArch(Arch);
9455 
9456   if (ID == ARM::ArchKind::INVALID)
9457     return Error(L, "Unknown arch name");
9458 
9459   bool WasThumb = isThumb();
9460   Triple T;
9461   MCSubtargetInfo &STI = copySTI();
9462   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
9463   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9464   FixModeAfterArchChange(WasThumb, L);
9465 
9466   getTargetStreamer().emitArch(ID);
9467   return false;
9468 }
9469 
9470 /// parseDirectiveEabiAttr
9471 ///  ::= .eabi_attribute int, int [, "str"]
9472 ///  ::= .eabi_attribute Tag_name, int [, "str"]
9473 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
9474   MCAsmParser &Parser = getParser();
9475   int64_t Tag;
9476   SMLoc TagLoc;
9477   TagLoc = Parser.getTok().getLoc();
9478   if (Parser.getTok().is(AsmToken::Identifier)) {
9479     StringRef Name = Parser.getTok().getIdentifier();
9480     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
9481     if (Tag == -1) {
9482       Error(TagLoc, "attribute name not recognised: " + Name);
9483       return false;
9484     }
9485     Parser.Lex();
9486   } else {
9487     const MCExpr *AttrExpr;
9488 
9489     TagLoc = Parser.getTok().getLoc();
9490     if (Parser.parseExpression(AttrExpr))
9491       return true;
9492 
9493     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9494     if (check(!CE, TagLoc, "expected numeric constant"))
9495       return true;
9496 
9497     Tag = CE->getValue();
9498   }
9499 
9500   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9501     return true;
9502 
9503   StringRef StringValue = "";
9504   bool IsStringValue = false;
9505 
9506   int64_t IntegerValue = 0;
9507   bool IsIntegerValue = false;
9508 
9509   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9510     IsStringValue = true;
9511   else if (Tag == ARMBuildAttrs::compatibility) {
9512     IsStringValue = true;
9513     IsIntegerValue = true;
9514   } else if (Tag < 32 || Tag % 2 == 0)
9515     IsIntegerValue = true;
9516   else if (Tag % 2 == 1)
9517     IsStringValue = true;
9518   else
9519     llvm_unreachable("invalid tag type");
9520 
9521   if (IsIntegerValue) {
9522     const MCExpr *ValueExpr;
9523     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9524     if (Parser.parseExpression(ValueExpr))
9525       return true;
9526 
9527     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9528     if (!CE)
9529       return Error(ValueExprLoc, "expected numeric constant");
9530     IntegerValue = CE->getValue();
9531   }
9532 
9533   if (Tag == ARMBuildAttrs::compatibility) {
9534     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9535       return true;
9536   }
9537 
9538   if (IsStringValue) {
9539     if (Parser.getTok().isNot(AsmToken::String))
9540       return Error(Parser.getTok().getLoc(), "bad string constant");
9541 
9542     StringValue = Parser.getTok().getStringContents();
9543     Parser.Lex();
9544   }
9545 
9546   if (Parser.parseToken(AsmToken::EndOfStatement,
9547                         "unexpected token in '.eabi_attribute' directive"))
9548     return true;
9549 
9550   if (IsIntegerValue && IsStringValue) {
9551     assert(Tag == ARMBuildAttrs::compatibility);
9552     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9553   } else if (IsIntegerValue)
9554     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9555   else if (IsStringValue)
9556     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9557   return false;
9558 }
9559 
9560 /// parseDirectiveCPU
9561 ///  ::= .cpu str
9562 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9563   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9564   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9565 
9566   // FIXME: This is using table-gen data, but should be moved to
9567   // ARMTargetParser once that is table-gen'd.
9568   if (!getSTI().isCPUStringValid(CPU))
9569     return Error(L, "Unknown CPU name");
9570 
9571   bool WasThumb = isThumb();
9572   MCSubtargetInfo &STI = copySTI();
9573   STI.setDefaultFeatures(CPU, "");
9574   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9575   FixModeAfterArchChange(WasThumb, L);
9576 
9577   return false;
9578 }
9579 
9580 /// parseDirectiveFPU
9581 ///  ::= .fpu str
9582 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9583   SMLoc FPUNameLoc = getTok().getLoc();
9584   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9585 
9586   unsigned ID = ARM::parseFPU(FPU);
9587   std::vector<StringRef> Features;
9588   if (!ARM::getFPUFeatures(ID, Features))
9589     return Error(FPUNameLoc, "Unknown FPU name");
9590 
9591   MCSubtargetInfo &STI = copySTI();
9592   for (auto Feature : Features)
9593     STI.ApplyFeatureFlag(Feature);
9594   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9595 
9596   getTargetStreamer().emitFPU(ID);
9597   return false;
9598 }
9599 
9600 /// parseDirectiveFnStart
9601 ///  ::= .fnstart
9602 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9603   if (parseToken(AsmToken::EndOfStatement,
9604                  "unexpected token in '.fnstart' directive"))
9605     return true;
9606 
9607   if (UC.hasFnStart()) {
9608     Error(L, ".fnstart starts before the end of previous one");
9609     UC.emitFnStartLocNotes();
9610     return true;
9611   }
9612 
9613   // Reset the unwind directives parser state
9614   UC.reset();
9615 
9616   getTargetStreamer().emitFnStart();
9617 
9618   UC.recordFnStart(L);
9619   return false;
9620 }
9621 
9622 /// parseDirectiveFnEnd
9623 ///  ::= .fnend
9624 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9625   if (parseToken(AsmToken::EndOfStatement,
9626                  "unexpected token in '.fnend' directive"))
9627     return true;
9628   // Check the ordering of unwind directives
9629   if (!UC.hasFnStart())
9630     return Error(L, ".fnstart must precede .fnend directive");
9631 
9632   // Reset the unwind directives parser state
9633   getTargetStreamer().emitFnEnd();
9634 
9635   UC.reset();
9636   return false;
9637 }
9638 
9639 /// parseDirectiveCantUnwind
9640 ///  ::= .cantunwind
9641 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9642   if (parseToken(AsmToken::EndOfStatement,
9643                  "unexpected token in '.cantunwind' directive"))
9644     return true;
9645 
9646   UC.recordCantUnwind(L);
9647   // Check the ordering of unwind directives
9648   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
9649     return true;
9650 
9651   if (UC.hasHandlerData()) {
9652     Error(L, ".cantunwind can't be used with .handlerdata directive");
9653     UC.emitHandlerDataLocNotes();
9654     return true;
9655   }
9656   if (UC.hasPersonality()) {
9657     Error(L, ".cantunwind can't be used with .personality directive");
9658     UC.emitPersonalityLocNotes();
9659     return true;
9660   }
9661 
9662   getTargetStreamer().emitCantUnwind();
9663   return false;
9664 }
9665 
9666 /// parseDirectivePersonality
9667 ///  ::= .personality name
9668 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9669   MCAsmParser &Parser = getParser();
9670   bool HasExistingPersonality = UC.hasPersonality();
9671 
9672   // Parse the name of the personality routine
9673   if (Parser.getTok().isNot(AsmToken::Identifier))
9674     return Error(L, "unexpected input in .personality directive.");
9675   StringRef Name(Parser.getTok().getIdentifier());
9676   Parser.Lex();
9677 
9678   if (parseToken(AsmToken::EndOfStatement,
9679                  "unexpected token in '.personality' directive"))
9680     return true;
9681 
9682   UC.recordPersonality(L);
9683 
9684   // Check the ordering of unwind directives
9685   if (!UC.hasFnStart())
9686     return Error(L, ".fnstart must precede .personality directive");
9687   if (UC.cantUnwind()) {
9688     Error(L, ".personality can't be used with .cantunwind directive");
9689     UC.emitCantUnwindLocNotes();
9690     return true;
9691   }
9692   if (UC.hasHandlerData()) {
9693     Error(L, ".personality must precede .handlerdata directive");
9694     UC.emitHandlerDataLocNotes();
9695     return true;
9696   }
9697   if (HasExistingPersonality) {
9698     Error(L, "multiple personality directives");
9699     UC.emitPersonalityLocNotes();
9700     return true;
9701   }
9702 
9703   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
9704   getTargetStreamer().emitPersonality(PR);
9705   return false;
9706 }
9707 
9708 /// parseDirectiveHandlerData
9709 ///  ::= .handlerdata
9710 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9711   if (parseToken(AsmToken::EndOfStatement,
9712                  "unexpected token in '.handlerdata' directive"))
9713     return true;
9714 
9715   UC.recordHandlerData(L);
9716   // Check the ordering of unwind directives
9717   if (!UC.hasFnStart())
9718     return Error(L, ".fnstart must precede .personality directive");
9719   if (UC.cantUnwind()) {
9720     Error(L, ".handlerdata can't be used with .cantunwind directive");
9721     UC.emitCantUnwindLocNotes();
9722     return true;
9723   }
9724 
9725   getTargetStreamer().emitHandlerData();
9726   return false;
9727 }
9728 
9729 /// parseDirectiveSetFP
9730 ///  ::= .setfp fpreg, spreg [, offset]
9731 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9732   MCAsmParser &Parser = getParser();
9733   // Check the ordering of unwind directives
9734   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
9735       check(UC.hasHandlerData(), L,
9736             ".setfp must precede .handlerdata directive"))
9737     return true;
9738 
9739   // Parse fpreg
9740   SMLoc FPRegLoc = Parser.getTok().getLoc();
9741   int FPReg = tryParseRegister();
9742 
9743   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
9744       Parser.parseToken(AsmToken::Comma, "comma expected"))
9745     return true;
9746 
9747   // Parse spreg
9748   SMLoc SPRegLoc = Parser.getTok().getLoc();
9749   int SPReg = tryParseRegister();
9750   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
9751       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
9752             "register should be either $sp or the latest fp register"))
9753     return true;
9754 
9755   // Update the frame pointer register
9756   UC.saveFPReg(FPReg);
9757 
9758   // Parse offset
9759   int64_t Offset = 0;
9760   if (Parser.parseOptionalToken(AsmToken::Comma)) {
9761     if (Parser.getTok().isNot(AsmToken::Hash) &&
9762         Parser.getTok().isNot(AsmToken::Dollar))
9763       return Error(Parser.getTok().getLoc(), "'#' expected");
9764     Parser.Lex(); // skip hash token.
9765 
9766     const MCExpr *OffsetExpr;
9767     SMLoc ExLoc = Parser.getTok().getLoc();
9768     SMLoc EndLoc;
9769     if (getParser().parseExpression(OffsetExpr, EndLoc))
9770       return Error(ExLoc, "malformed setfp offset");
9771     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9772     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
9773       return true;
9774     Offset = CE->getValue();
9775   }
9776 
9777   if (Parser.parseToken(AsmToken::EndOfStatement))
9778     return true;
9779 
9780   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9781                                 static_cast<unsigned>(SPReg), Offset);
9782   return false;
9783 }
9784 
9785 /// parseDirective
9786 ///  ::= .pad offset
9787 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9788   MCAsmParser &Parser = getParser();
9789   // Check the ordering of unwind directives
9790   if (!UC.hasFnStart())
9791     return Error(L, ".fnstart must precede .pad directive");
9792   if (UC.hasHandlerData())
9793     return Error(L, ".pad must precede .handlerdata directive");
9794 
9795   // Parse the offset
9796   if (Parser.getTok().isNot(AsmToken::Hash) &&
9797       Parser.getTok().isNot(AsmToken::Dollar))
9798     return Error(Parser.getTok().getLoc(), "'#' expected");
9799   Parser.Lex(); // skip hash token.
9800 
9801   const MCExpr *OffsetExpr;
9802   SMLoc ExLoc = Parser.getTok().getLoc();
9803   SMLoc EndLoc;
9804   if (getParser().parseExpression(OffsetExpr, EndLoc))
9805     return Error(ExLoc, "malformed pad offset");
9806   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9807   if (!CE)
9808     return Error(ExLoc, "pad offset must be an immediate");
9809 
9810   if (parseToken(AsmToken::EndOfStatement,
9811                  "unexpected token in '.pad' directive"))
9812     return true;
9813 
9814   getTargetStreamer().emitPad(CE->getValue());
9815   return false;
9816 }
9817 
9818 /// parseDirectiveRegSave
9819 ///  ::= .save  { registers }
9820 ///  ::= .vsave { registers }
9821 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
9822   // Check the ordering of unwind directives
9823   if (!UC.hasFnStart())
9824     return Error(L, ".fnstart must precede .save or .vsave directives");
9825   if (UC.hasHandlerData())
9826     return Error(L, ".save or .vsave must precede .handlerdata directive");
9827 
9828   // RAII object to make sure parsed operands are deleted.
9829   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
9830 
9831   // Parse the register list
9832   if (parseRegisterList(Operands) ||
9833       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9834     return true;
9835   ARMOperand &Op = (ARMOperand &)*Operands[0];
9836   if (!IsVector && !Op.isRegList())
9837     return Error(L, ".save expects GPR registers");
9838   if (IsVector && !Op.isDPRRegList())
9839     return Error(L, ".vsave expects DPR registers");
9840 
9841   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
9842   return false;
9843 }
9844 
9845 /// parseDirectiveInst
9846 ///  ::= .inst opcode [, ...]
9847 ///  ::= .inst.n opcode [, ...]
9848 ///  ::= .inst.w opcode [, ...]
9849 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
9850   int Width = 4;
9851 
9852   if (isThumb()) {
9853     switch (Suffix) {
9854     case 'n':
9855       Width = 2;
9856       break;
9857     case 'w':
9858       break;
9859     default:
9860       return Error(Loc, "cannot determine Thumb instruction size, "
9861                         "use inst.n/inst.w instead");
9862     }
9863   } else {
9864     if (Suffix)
9865       return Error(Loc, "width suffixes are invalid in ARM mode");
9866   }
9867 
9868   auto parseOne = [&]() -> bool {
9869     const MCExpr *Expr;
9870     if (getParser().parseExpression(Expr))
9871       return true;
9872     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
9873     if (!Value) {
9874       return Error(Loc, "expected constant expression");
9875     }
9876 
9877     switch (Width) {
9878     case 2:
9879       if (Value->getValue() > 0xffff)
9880         return Error(Loc, "inst.n operand is too big, use inst.w instead");
9881       break;
9882     case 4:
9883       if (Value->getValue() > 0xffffffff)
9884         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
9885                               " operand is too big");
9886       break;
9887     default:
9888       llvm_unreachable("only supported widths are 2 and 4");
9889     }
9890 
9891     getTargetStreamer().emitInst(Value->getValue(), Suffix);
9892     return false;
9893   };
9894 
9895   if (parseOptionalToken(AsmToken::EndOfStatement))
9896     return Error(Loc, "expected expression following directive");
9897   if (parseMany(parseOne))
9898     return true;
9899   return false;
9900 }
9901 
9902 /// parseDirectiveLtorg
9903 ///  ::= .ltorg | .pool
9904 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
9905   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9906     return true;
9907   getTargetStreamer().emitCurrentConstantPool();
9908   return false;
9909 }
9910 
9911 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
9912   const MCSection *Section = getStreamer().getCurrentSectionOnly();
9913 
9914   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9915     return true;
9916 
9917   if (!Section) {
9918     getStreamer().InitSections(false);
9919     Section = getStreamer().getCurrentSectionOnly();
9920   }
9921 
9922   assert(Section && "must have section to emit alignment");
9923   if (Section->UseCodeAlign())
9924     getStreamer().EmitCodeAlignment(2);
9925   else
9926     getStreamer().EmitValueToAlignment(2);
9927 
9928   return false;
9929 }
9930 
9931 /// parseDirectivePersonalityIndex
9932 ///   ::= .personalityindex index
9933 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
9934   MCAsmParser &Parser = getParser();
9935   bool HasExistingPersonality = UC.hasPersonality();
9936 
9937   const MCExpr *IndexExpression;
9938   SMLoc IndexLoc = Parser.getTok().getLoc();
9939   if (Parser.parseExpression(IndexExpression) ||
9940       parseToken(AsmToken::EndOfStatement,
9941                  "unexpected token in '.personalityindex' directive")) {
9942     return true;
9943   }
9944 
9945   UC.recordPersonalityIndex(L);
9946 
9947   if (!UC.hasFnStart()) {
9948     return Error(L, ".fnstart must precede .personalityindex directive");
9949   }
9950   if (UC.cantUnwind()) {
9951     Error(L, ".personalityindex cannot be used with .cantunwind");
9952     UC.emitCantUnwindLocNotes();
9953     return true;
9954   }
9955   if (UC.hasHandlerData()) {
9956     Error(L, ".personalityindex must precede .handlerdata directive");
9957     UC.emitHandlerDataLocNotes();
9958     return true;
9959   }
9960   if (HasExistingPersonality) {
9961     Error(L, "multiple personality directives");
9962     UC.emitPersonalityLocNotes();
9963     return true;
9964   }
9965 
9966   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
9967   if (!CE)
9968     return Error(IndexLoc, "index must be a constant number");
9969   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
9970     return Error(IndexLoc,
9971                  "personality routine index should be in range [0-3]");
9972 
9973   getTargetStreamer().emitPersonalityIndex(CE->getValue());
9974   return false;
9975 }
9976 
9977 /// parseDirectiveUnwindRaw
9978 ///   ::= .unwind_raw offset, opcode [, opcode...]
9979 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
9980   MCAsmParser &Parser = getParser();
9981   int64_t StackOffset;
9982   const MCExpr *OffsetExpr;
9983   SMLoc OffsetLoc = getLexer().getLoc();
9984 
9985   if (!UC.hasFnStart())
9986     return Error(L, ".fnstart must precede .unwind_raw directives");
9987   if (getParser().parseExpression(OffsetExpr))
9988     return Error(OffsetLoc, "expected expression");
9989 
9990   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9991   if (!CE)
9992     return Error(OffsetLoc, "offset must be a constant");
9993 
9994   StackOffset = CE->getValue();
9995 
9996   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
9997     return true;
9998 
9999   SmallVector<uint8_t, 16> Opcodes;
10000 
10001   auto parseOne = [&]() -> bool {
10002     const MCExpr *OE;
10003     SMLoc OpcodeLoc = getLexer().getLoc();
10004     if (check(getLexer().is(AsmToken::EndOfStatement) ||
10005                   Parser.parseExpression(OE),
10006               OpcodeLoc, "expected opcode expression"))
10007       return true;
10008     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
10009     if (!OC)
10010       return Error(OpcodeLoc, "opcode value must be a constant");
10011     const int64_t Opcode = OC->getValue();
10012     if (Opcode & ~0xff)
10013       return Error(OpcodeLoc, "invalid opcode");
10014     Opcodes.push_back(uint8_t(Opcode));
10015     return false;
10016   };
10017 
10018   // Must have at least 1 element
10019   SMLoc OpcodeLoc = getLexer().getLoc();
10020   if (parseOptionalToken(AsmToken::EndOfStatement))
10021     return Error(OpcodeLoc, "expected opcode expression");
10022   if (parseMany(parseOne))
10023     return true;
10024 
10025   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
10026   return false;
10027 }
10028 
10029 /// parseDirectiveTLSDescSeq
10030 ///   ::= .tlsdescseq tls-variable
10031 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
10032   MCAsmParser &Parser = getParser();
10033 
10034   if (getLexer().isNot(AsmToken::Identifier))
10035     return TokError("expected variable after '.tlsdescseq' directive");
10036 
10037   const MCSymbolRefExpr *SRE =
10038     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
10039                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
10040   Lex();
10041 
10042   if (parseToken(AsmToken::EndOfStatement,
10043                  "unexpected token in '.tlsdescseq' directive"))
10044     return true;
10045 
10046   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
10047   return false;
10048 }
10049 
10050 /// parseDirectiveMovSP
10051 ///  ::= .movsp reg [, #offset]
10052 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
10053   MCAsmParser &Parser = getParser();
10054   if (!UC.hasFnStart())
10055     return Error(L, ".fnstart must precede .movsp directives");
10056   if (UC.getFPReg() != ARM::SP)
10057     return Error(L, "unexpected .movsp directive");
10058 
10059   SMLoc SPRegLoc = Parser.getTok().getLoc();
10060   int SPReg = tryParseRegister();
10061   if (SPReg == -1)
10062     return Error(SPRegLoc, "register expected");
10063   if (SPReg == ARM::SP || SPReg == ARM::PC)
10064     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
10065 
10066   int64_t Offset = 0;
10067   if (Parser.parseOptionalToken(AsmToken::Comma)) {
10068     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
10069       return true;
10070 
10071     const MCExpr *OffsetExpr;
10072     SMLoc OffsetLoc = Parser.getTok().getLoc();
10073 
10074     if (Parser.parseExpression(OffsetExpr))
10075       return Error(OffsetLoc, "malformed offset expression");
10076 
10077     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10078     if (!CE)
10079       return Error(OffsetLoc, "offset must be an immediate constant");
10080 
10081     Offset = CE->getValue();
10082   }
10083 
10084   if (parseToken(AsmToken::EndOfStatement,
10085                  "unexpected token in '.movsp' directive"))
10086     return true;
10087 
10088   getTargetStreamer().emitMovSP(SPReg, Offset);
10089   UC.saveFPReg(SPReg);
10090 
10091   return false;
10092 }
10093 
10094 /// parseDirectiveObjectArch
10095 ///   ::= .object_arch name
10096 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
10097   MCAsmParser &Parser = getParser();
10098   if (getLexer().isNot(AsmToken::Identifier))
10099     return Error(getLexer().getLoc(), "unexpected token");
10100 
10101   StringRef Arch = Parser.getTok().getString();
10102   SMLoc ArchLoc = Parser.getTok().getLoc();
10103   Lex();
10104 
10105   ARM::ArchKind ID = ARM::parseArch(Arch);
10106 
10107   if (ID == ARM::ArchKind::INVALID)
10108     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
10109   if (parseToken(AsmToken::EndOfStatement))
10110     return true;
10111 
10112   getTargetStreamer().emitObjectArch(ID);
10113   return false;
10114 }
10115 
10116 /// parseDirectiveAlign
10117 ///   ::= .align
10118 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
10119   // NOTE: if this is not the end of the statement, fall back to the target
10120   // agnostic handling for this directive which will correctly handle this.
10121   if (parseOptionalToken(AsmToken::EndOfStatement)) {
10122     // '.align' is target specifically handled to mean 2**2 byte alignment.
10123     const MCSection *Section = getStreamer().getCurrentSectionOnly();
10124     assert(Section && "must have section to emit alignment");
10125     if (Section->UseCodeAlign())
10126       getStreamer().EmitCodeAlignment(4, 0);
10127     else
10128       getStreamer().EmitValueToAlignment(4, 0, 1, 0);
10129     return false;
10130   }
10131   return true;
10132 }
10133 
10134 /// parseDirectiveThumbSet
10135 ///  ::= .thumb_set name, value
10136 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
10137   MCAsmParser &Parser = getParser();
10138 
10139   StringRef Name;
10140   if (check(Parser.parseIdentifier(Name),
10141             "expected identifier after '.thumb_set'") ||
10142       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
10143     return true;
10144 
10145   MCSymbol *Sym;
10146   const MCExpr *Value;
10147   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
10148                                                Parser, Sym, Value))
10149     return true;
10150 
10151   getTargetStreamer().emitThumbSet(Sym, Value);
10152   return false;
10153 }
10154 
10155 /// Force static initialization.
10156 extern "C" void LLVMInitializeARMAsmParser() {
10157   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
10158   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
10159   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
10160   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
10161 }
10162 
10163 #define GET_REGISTER_MATCHER
10164 #define GET_SUBTARGET_FEATURE_NAME
10165 #define GET_MATCHER_IMPLEMENTATION
10166 #include "ARMGenAsmMatcher.inc"
10167 
10168 // FIXME: This structure should be moved inside ARMTargetParser
10169 // when we start to table-generate them, and we can use the ARM
10170 // flags below, that were generated by table-gen.
10171 static const struct {
10172   const unsigned Kind;
10173   const uint64_t ArchCheck;
10174   const FeatureBitset Features;
10175 } Extensions[] = {
10176   { ARM::AEK_CRC, Feature_HasV8, {ARM::FeatureCRC} },
10177   { ARM::AEK_CRYPTO,  Feature_HasV8,
10178     {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10179   { ARM::AEK_FP, Feature_HasV8, {ARM::FeatureFPARMv8} },
10180   { (ARM::AEK_HWDIVTHUMB | ARM::AEK_HWDIVARM), Feature_HasV7 | Feature_IsNotMClass,
10181     {ARM::FeatureHWDivThumb, ARM::FeatureHWDivARM} },
10182   { ARM::AEK_MP, Feature_HasV7 | Feature_IsNotMClass, {ARM::FeatureMP} },
10183   { ARM::AEK_SIMD, Feature_HasV8, {ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10184   { ARM::AEK_SEC, Feature_HasV6K, {ARM::FeatureTrustZone} },
10185   // FIXME: Only available in A-class, isel not predicated
10186   { ARM::AEK_VIRT, Feature_HasV7, {ARM::FeatureVirtualization} },
10187   { ARM::AEK_FP16, Feature_HasV8_2a, {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
10188   { ARM::AEK_RAS, Feature_HasV8, {ARM::FeatureRAS} },
10189   // FIXME: Unsupported extensions.
10190   { ARM::AEK_OS, Feature_None, {} },
10191   { ARM::AEK_IWMMXT, Feature_None, {} },
10192   { ARM::AEK_IWMMXT2, Feature_None, {} },
10193   { ARM::AEK_MAVERICK, Feature_None, {} },
10194   { ARM::AEK_XSCALE, Feature_None, {} },
10195 };
10196 
10197 /// parseDirectiveArchExtension
10198 ///   ::= .arch_extension [no]feature
10199 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
10200   MCAsmParser &Parser = getParser();
10201 
10202   if (getLexer().isNot(AsmToken::Identifier))
10203     return Error(getLexer().getLoc(), "expected architecture extension name");
10204 
10205   StringRef Name = Parser.getTok().getString();
10206   SMLoc ExtLoc = Parser.getTok().getLoc();
10207   Lex();
10208 
10209   if (parseToken(AsmToken::EndOfStatement,
10210                  "unexpected token in '.arch_extension' directive"))
10211     return true;
10212 
10213   bool EnableFeature = true;
10214   if (Name.startswith_lower("no")) {
10215     EnableFeature = false;
10216     Name = Name.substr(2);
10217   }
10218   unsigned FeatureKind = ARM::parseArchExt(Name);
10219   if (FeatureKind == ARM::AEK_INVALID)
10220     return Error(ExtLoc, "unknown architectural extension: " + Name);
10221 
10222   for (const auto &Extension : Extensions) {
10223     if (Extension.Kind != FeatureKind)
10224       continue;
10225 
10226     if (Extension.Features.none())
10227       return Error(ExtLoc, "unsupported architectural extension: " + Name);
10228 
10229     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
10230       return Error(ExtLoc, "architectural extension '" + Name +
10231                                "' is not "
10232                                "allowed for the current base architecture");
10233 
10234     MCSubtargetInfo &STI = copySTI();
10235     FeatureBitset ToggleFeatures = EnableFeature
10236       ? (~STI.getFeatureBits() & Extension.Features)
10237       : ( STI.getFeatureBits() & Extension.Features);
10238 
10239     uint64_t Features =
10240         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
10241     setAvailableFeatures(Features);
10242     return false;
10243   }
10244 
10245   return Error(ExtLoc, "unknown architectural extension: " + Name);
10246 }
10247 
10248 // Define this matcher function after the auto-generated include so we
10249 // have the match class enum definitions.
10250 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
10251                                                   unsigned Kind) {
10252   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
10253   // If the kind is a token for a literal immediate, check if our asm
10254   // operand matches. This is for InstAliases which have a fixed-value
10255   // immediate in the syntax.
10256   switch (Kind) {
10257   default: break;
10258   case MCK__35_0:
10259     if (Op.isImm())
10260       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
10261         if (CE->getValue() == 0)
10262           return Match_Success;
10263     break;
10264   case MCK_ModImm:
10265     if (Op.isImm()) {
10266       const MCExpr *SOExpr = Op.getImm();
10267       int64_t Value;
10268       if (!SOExpr->evaluateAsAbsolute(Value))
10269         return Match_Success;
10270       assert((Value >= std::numeric_limits<int32_t>::min() &&
10271               Value <= std::numeric_limits<uint32_t>::max()) &&
10272              "expression value must be representable in 32 bits");
10273     }
10274     break;
10275   case MCK_rGPR:
10276     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
10277       return Match_Success;
10278     break;
10279   case MCK_GPRPair:
10280     if (Op.isReg() &&
10281         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
10282       return Match_Success;
10283     break;
10284   }
10285   return Match_InvalidOperand;
10286 }
10287